This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Auth;
use Magento\TestFramework\Bootstrap as TestHelper;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
class SessionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Model\Auth
*/
private $auth;
/**
* @var \Magento\Backend\Model\Auth\Session
*/
private $authSession;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class)
->setCurrentScope(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->auth = $this->objectManager->create(\Magento\Backend\Model\Auth::class);
$this->authSession = $this->objectManager->create(\Magento\Backend\Model\Auth\Session::class);
$this->authSession->setUser($this->objectManager->create(\Magento\User\Model\User::class));
$this->auth->setAuthStorage($this->authSession);
$this->auth->logout();
}
protected function tearDown(): void
{
$this->auth = null;
$this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class)->setCurrentScope(null);
}
/**
* @dataProvider loginDataProvider
*/
public function testIsLoggedIn($loggedIn)
{
if ($loggedIn) {
$this->auth->login(
TestHelper::ADMIN_NAME,
TestHelper::ADMIN_PASSWORD
);
}
$this->assertEquals($loggedIn, $this->authSession->isLoggedIn());
}
public function loginDataProvider()
{
return [[false], [true]];
}
}
@@ -0,0 +1,147 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Exception\AuthenticationException;
/**
* Test class for \Magento\Backend\Model\Auth.
*
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
class AuthTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Model\Auth
*/
protected $_model;
protected function setUp(): void
{
parent::setUp();
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Backend\Model\Auth::class);
}
/**
* @dataProvider getLoginDataProvider
* @param string $userName
* @param string $password
*/
public function testLoginFailed($userName, $password)
{
$this->expectException(\Magento\Framework\Exception\AuthenticationException::class);
$this->_model->login($userName, $password);
}
public function getLoginDataProvider()
{
return [
'Invalid credentials' => ['not_exists', 'not_exists'],
'Empty credentials' => ['', 'not_exists']
];
}
public function testSetGetAuthStorage()
{
// by default \Magento\Backend\Model\Auth\Session class will instantiate as a Authentication Storage
$this->assertInstanceOf(\Magento\Backend\Model\Auth\Session::class, $this->_model->getAuthStorage());
$mockStorage = $this->createMock(\Magento\Backend\Model\Auth\StorageInterface::class);
$this->_model->setAuthStorage($mockStorage);
$this->assertInstanceOf(\Magento\Backend\Model\Auth\StorageInterface::class, $this->_model->getAuthStorage());
$incorrectStorage = new \StdClass();
try {
$this->_model->setAuthStorage($incorrectStorage);
$this->fail('Incorrect authentication storage setted.');
} catch (AuthenticationException $e) {
// in case of exception - Auth works correct
$this->assertNotEmpty($e->getMessage());
}
}
public function testGetCredentialStorageList()
{
$storage = $this->_model->getCredentialStorage();
$this->assertInstanceOf(\Magento\Backend\Model\Auth\Credential\StorageInterface::class, $storage);
}
public function testLoginSuccessful()
{
$this->_model->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$this->assertInstanceOf(
\Magento\Backend\Model\Auth\Credential\StorageInterface::class,
$this->_model->getUser()
);
$this->assertGreaterThan(time() - 10, $this->_model->getAuthStorage()->getUpdatedAt());
}
public function testLoginFlushesFormKey()
{
/** @var FormKey $dataFormKey */
$dataFormKey = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(FormKey::class);
$beforeKey = $dataFormKey->getFormKey();
$this->_model->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$afterKey = $dataFormKey->getFormKey();
$this->assertNotEquals($beforeKey, $afterKey);
}
/**
* @magentoAppIsolation enabled
*/
public function testLogout()
{
$this->_model->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$this->assertNotEmpty($this->_model->getAuthStorage()->getData());
$this->_model->logout();
$this->assertEmpty($this->_model->getAuthStorage()->getData());
}
/**
* Disabled form security in order to prevent exit from the app
* @magentoAdminConfigFixture admin/security/session_lifetime 100
*/
public function testIsLoggedIn()
{
$this->_model->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$this->assertTrue($this->_model->isLoggedIn());
}
public function testGetUser()
{
$this->_model->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$this->assertNotNull($this->_model->getUser());
$this->assertGreaterThan(0, $this->_model->getUser()->getId());
$this->assertInstanceOf(
\Magento\Backend\Model\Auth\Credential\StorageInterface::class,
$this->_model->getUser()
);
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Backend\Model\Dashboard;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Payment;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\Stdlib\DateTime;
use DateTimeZone;
/**
* Verify chart data by different period.
*
* @magentoAppArea adminhtml
*/
class ChartTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Chart
*/
private $model;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->get(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,
string $orderIncrementId
): void {
$payment = $this->objectManager->get(Payment::class);
$payment->setMethod('checkmo');
$payment->setAdditionalInformation('last_trans_id', '11122');
$payment->setAdditionalInformation('metadata', [
'type' => 'free',
'fraudulent' => false
]);
$timezoneLocal = $this->objectManager->get(TimezoneInterface::class)->getConfigTimezone();
$dateTime = new \DateTime('now', new \DateTimeZone($timezoneLocal));
if ($period === '1m') {
$dateTime->modify('first day of this month')->format(DateTime::DATETIME_PHP_FORMAT);
} elseif ($period === '1y') {
$monthlyDateTime = clone $dateTime;
$monthlyDateTime->modify('first day of this month')->format(DateTime::DATETIME_PHP_FORMAT);
$monthlyDateTime->setTimezone(new DateTimeZone('UTC'));
$monthlyOrder = $this->objectManager->get(Order::class);
$monthlyOrder->loadByIncrementId('100000004');
$monthlyOrder->setCreatedAt($monthlyDateTime->format(DateTime::DATETIME_PHP_FORMAT));
$monthlyOrder->setPayment($payment);
$monthlyOrder->save();
$dateTime->modify('first day of january this year')->format(DateTime::DATETIME_PHP_FORMAT);
} elseif ($period === '2y') {
$dateTime->modify('first day of january last year')->format(DateTime::DATETIME_PHP_FORMAT);
}
$dateTime->setTimezone(new DateTimeZone('UTC'));
$order = $this->objectManager->get(Order::class);
$order->loadByIncrementId($orderIncrementId);
$order->setCreatedAt($dateTime->format(DateTime::DATETIME_PHP_FORMAT));
$order->setPayment($payment);
$order->save();
$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',
'100000002'
],
[
3,
'7d',
'quantity',
'100000003'
],
[
4,
'1m',
'quantity',
'100000004'
],
[
5,
'1y',
'quantity',
'100000005'
],
[
6,
'2y',
'quantity',
'100000006'
]
];
}
}
@@ -0,0 +1,123 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Locale;
use Magento\Framework\Locale\Resolver;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class ResolverTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Locale\ResolverInterface
*/
protected $_model;
protected function setUp(): void
{
parent::setUp();
$this->_model = Bootstrap::getObjectManager()->create(
\Magento\Backend\Model\Locale\Resolver::class
);
}
/**
* @covers \Magento\Backend\Model\Locale\Resolver::setLocale
*/
public function testSetLocaleWithDefaultLocale()
{
$this->_checkSetLocale(Resolver::DEFAULT_LOCALE);
}
/**
* @covers \Magento\Backend\Model\Locale\Resolver::setLocale
*/
public function testSetLocaleWithBaseInterfaceLocale()
{
$user = new \Magento\Framework\DataObject();
$session = Bootstrap::getObjectManager()->get(
\Magento\Backend\Model\Auth\Session::class
);
$session->setUser($user);
Bootstrap::getObjectManager()->get(
\Magento\Backend\Model\Auth\Session::class
)->getUser()->setInterfaceLocale(
'fr_FR'
);
$this->_checkSetLocale('fr_FR');
}
/**
* @covers \Magento\Backend\Model\Locale\Resolver::setLocale
*/
public function testSetLocaleWithSessionLocale()
{
Bootstrap::getObjectManager()->get(
\Magento\Backend\Model\Session::class
)->setSessionLocale(
'es_ES'
);
$this->_checkSetLocale('es_ES');
}
/**
* @covers \Magento\Backend\Model\Locale\Resolver::setLocale
*/
public function testSetLocaleWithRequestLocale()
{
$request = Bootstrap::getObjectManager()
->get(\Magento\Framework\App\RequestInterface::class);
$request->setPostValue(['locale' => 'de_DE']);
$this->_checkSetLocale('de_DE');
}
/**
* Tests setLocale() with parameter
*
* @param string|null $localeParam
* @param string|null $localeRequestParam
* @param string $localeExpected
* @dataProvider setLocaleWithParameterDataProvider
*/
public function testSetLocaleWithParameter(
?string $localeParam,
?string $localeRequestParam,
string $localeExpected
) {
$request = Bootstrap::getObjectManager()
->get(\Magento\Framework\App\RequestInterface::class);
$request->setPostValue(['locale' => $localeRequestParam]);
$this->_model->setLocale($localeParam);
$this->assertEquals($localeExpected, $this->_model->getLocale());
}
/**
* @return array
*/
public function setLocaleWithParameterDataProvider(): array
{
return [
['ko_KR', 'ja_JP', 'ja_JP'],
['ko_KR', null, 'ko_KR'],
[null, 'ja_JP', 'ja_JP'],
];
}
/**
* Check set locale
*
* @param string $localeCodeToCheck
* @return void
*/
protected function _checkSetLocale($localeCodeToCheck)
{
$this->_model->setLocale();
$localeCode = $this->_model->getLocale();
$this->assertEquals($localeCode, $localeCodeToCheck);
}
}
@@ -0,0 +1,180 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model;
/**
* Test class for \Magento\Backend\Model\Auth.
*
* @magentoAppArea adminhtml
*/
class MenuTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Model\Menu
*/
private $model;
/** @var \Magento\Framework\ObjectManagerInterface */
private $objectManager;
protected function setUp(): void
{
parent::setUp();
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(\Magento\Backend\Model\Auth::class);
$this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class)
->setCurrentScope(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
}
public function testMenuItemManipulation()
{
/* @var $menu \Magento\Backend\Model\Menu */
$menu = $this->objectManager->create(\Magento\Backend\Model\Menu\Config::class)->getMenu();
/* @var $itemFactory \Magento\Backend\Model\Menu\Item\Factory */
$itemFactory = $this->objectManager->create(\Magento\Backend\Model\Menu\Item\Factory::class);
// Add new item in top level
$menu->add(
$itemFactory->create(
[
'id' => 'Magento_Backend::system2',
'title' => 'Extended System',
'module' => 'Magento_Backend',
'resource' => 'Magento_Backend::system2',
]
)
);
// Add submenu
$menu->add(
$itemFactory->create(
[
'id' => 'Magento_Backend::system2_acl',
'title' => 'Acl',
'module' => 'Magento_Backend',
'action' => 'admin/backend/acl/index',
'resource' => 'Magento_Backend::system2_acl',
]
),
'Magento_Backend::system2'
);
// Modify existing menu item
$menu->get('Magento_Backend::system2')->setTitle('Base system')->setAction('admin/backend/system/base');
// remove dependency from config
// Change sort order
$menu->reorder('Magento_Backend::system', 40);
// Remove menu item
$menu->remove('Magento_Backend::catalog_attribute');
// Move menu item
$menu->move('Magento_Catalog::catalog_products', 'Magento_Backend::system2');
}
/**
* @magentoAppIsolation enabled
*/
public function testSerialize()
{
/** @var Menu $menu */
$menu = $this->objectManager->get(\Magento\Backend\Model\MenuFactory::class)->create();
/* @var \Magento\Backend\Model\Menu\Item\Factory $itemFactory */
$itemFactory = $this->objectManager->create(\Magento\Backend\Model\Menu\Item\Factory::class);
// Add new item in top level
$menu->add(
$itemFactory->create(
[
'id' => 'Magento_Backend::system3',
'title' => 'Extended System',
'module' => 'Magento_Backend',
'resource' => 'Magento_Backend::system3',
'dependsOnConfig' => 'dev/test/system',
]
)
);
// Add submenu
$menu->add(
$itemFactory->create(
[
'id' => 'Magento_Backend::system3_acl',
'title' => 'Acl',
'module' => 'Magento_Backend',
'action' => 'admin/backend/acl/index',
'resource' => 'Magento_Backend::system3_acl',
]
),
'Magento_Backend::system3'
);
$serializedString = $menu->serialize();
$expected = '[{"parent_id":null,"module":"Magento_Backend","sort_index":null,'
. '"dependsOnConfig":"dev\/test\/system",'
. '"id":"Magento_Backend::system3","resource":"Magento_Backend::system3","path":"","action":null,'
. '"dependsOnModule":null,"toolTip":null,"title":"Extended System",'
. '"target":null,"sub_menu":[{"parent_id":null,"module":"Magento_Backend","sort_index":null,'
. '"dependsOnConfig":null,"id":"Magento_Backend::system3_acl","resource":"Magento_Backend::system3_acl",'
. '"path":"","action":"admin\/backend\/acl\/index","dependsOnModule":null,"toolTip":null,"title":"Acl",'
. '"target":null,"sub_menu":null}]}]';
$this->assertEquals($expected, $serializedString);
}
/**
* @magentoAppIsolation enabled
*/
public function testUnserialize()
{
$serializedMenu = '[{"parent_id":null,"module":"Magento_Backend","sort_index":null,'
. '"dependsOnConfig":"dev\/test","id":"Magento_Backend::system3","resource":"Magento_Backend::system3",'
. '"path":"","action":null,"dependsOnModule":null,"toolTip":null,"title":"Extended System",'
. '"target":null,"sub_menu":[{"parent_id":null,"module":"Magento_Backend","sort_index":null,'
. '"dependsOnConfig":null,"id":"Magento_Backend::system3_acl","resource":"Magento_Backend::system3_acl",'
. '"path":"","action":"admin\/backend\/acl\/index","dependsOnModule":null,"toolTip":null,"title":"Acl",'
. '"target":null,"sub_menu":null}]}]';
/** @var Menu $menu */
$menu = $this->objectManager->get(\Magento\Backend\Model\MenuFactory::class)->create();
$menu->unserialize($serializedMenu);
$expected = [
[
'parent_id' => null,
'module' => 'Magento_Backend',
'sort_index' => null,
'dependsOnConfig' => 'dev/test',
'id' => 'Magento_Backend::system3',
'resource' => 'Magento_Backend::system3',
'path' => '',
'action' => null,
'dependsOnModule' => null,
'toolTip' => null,
'title' => 'Extended System',
'target' => null,
'sub_menu' =>
[
[
'parent_id' => null,
'module' => 'Magento_Backend',
'sort_index' => null,
'dependsOnConfig' => null,
'id' => 'Magento_Backend::system3_acl',
'resource' => 'Magento_Backend::system3_acl',
'path' => '',
'action' => 'admin/backend/acl/index',
'dependsOnModule' => null,
'toolTip' => null,
'title' => 'Acl',
'sub_menu' => null,
'target' => null
],
],
],
];
$this->assertEquals($expected, $menu->toArray());
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Search;
/**
* @SuppressWarnings("unused")
*/
class AuthorizationMock extends \Magento\Framework\Authorization
{
/**
* Check current user permission on resource and privilege
*
* @param string $resource
* @param string $privilege
* @return boolean
*/
public function isAllowed($resource, $privilege = null)
{
return true;
}
}
@@ -0,0 +1,159 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Search;
use Magento\Backend\App\Area\FrontNameResolver;
use Magento\Framework\App\Area;
use Magento\Framework\App\AreaList;
use Magento\Framework\App\Cache\State;
use Magento\Framework\App\Config\FileResolver;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Config\FileIteratorFactory;
use Magento\Framework\Config\ScopeInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.StaticAccess)
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider loadDataProvider
* @magentoConfigFixture current_store general/store_information/name Foo
*/
public function testLoad($query, $expectedResult)
{
/** @var \Magento\Backend\Model\Search\Config $configSearch */
$configSearch = $this->getConfigSearchInstance();
$configSearch->setQuery($query);
$configSearch->load();
/** SUT Execution */
$searchResults = $configSearch->getResults();
/** Ensure that search results are correct */
$this->assertCount(count($expectedResult), $searchResults, 'Quantity of search result items is invalid.');
foreach ($expectedResult as $itemIndex => $expectedItem) {
/** Validate URL to item */
$elementPathParts = explode('/', $expectedItem['id']);
// filter empty values
$elementPathParts = array_values(array_filter($elementPathParts));
foreach ($elementPathParts as $elementPathPart) {
$this->assertStringContainsString(
$elementPathPart,
$searchResults[$itemIndex]['url'],
'Item URL is invalid.'
);
}
unset($searchResults[$itemIndex]['url']);
/** Validate other item data */
$this->assertEquals($expectedItem, $searchResults[$itemIndex], "Data of item #$itemIndex is invalid.");
}
}
/**
* @return \Magento\Backend\Model\Search\Config
*/
private function getConfigSearchInstance()
{
Bootstrap::getInstance()->reinitialize([
State::PARAM_BAN_CACHE => true,
]);
Bootstrap::getObjectManager()
->get(ScopeInterface::class)
->setCurrentScope(FrontNameResolver::AREA_CODE);
Bootstrap::getObjectManager()->get(AreaList::class)
->getArea(FrontNameResolver::AREA_CODE)
->load(Area::PART_CONFIG);
Bootstrap::getObjectManager()->configure([
'preferences' => [
AuthorizationInterface::class => \Magento\Backend\Model\Search\AuthorizationMock::class
]
]);
$fileResolverMock = $this->getMockBuilder(FileResolver::class)->disableOriginalConstructor()->getMock();
$fileIteratorFactory = Bootstrap::getObjectManager()->get(FileIteratorFactory::class);
$fileIterator = $fileIteratorFactory->create(
[__DIR__ . '/_files/test_config.xml']
);
$fileResolverMock->expects($this->any())->method('get')->willReturn($fileIterator);
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Config\Model\Config\Structure\Reader $structureReader */
$structureReader = $objectManager->create(
\Magento\Config\Model\Config\Structure\Reader::class,
['fileResolver' => $fileResolverMock]
);
/** @var \Magento\Config\Model\Config\Structure\Data $structureData */
$structureData = $objectManager->create(
\Magento\Config\Model\Config\Structure\Data::class,
['reader' => $structureReader]
);
/** @var \Magento\Config\Model\Config\Structure $structure */
$structure = $objectManager->create(
\Magento\Config\Model\Config\Structure::class,
['structureData' => $structureData]
);
return $objectManager->create(
\Magento\Backend\Model\Search\Config::class,
['configStructure' => $structure]
);
}
/**
* @return array
*/
public static function loadDataProvider()
{
return [
'Search by field 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',
'description' => ' / Test Tab / Test Section / Test Group',
],
],
],
'Search by group name' => [
'Test Group',
[
[
'id' => 'test_section/test_group',
'type' => null,
'name' => 'Test Group',
'description' => ' / Test Tab / Test Section',
],
],
],
'Search by section name' => [
'Test Section',
[
[
'id' => '/test_section',
'type' => null,
'name' => 'Test Section',
'description' => ' / Test Tab',
],
],
],
];
}
}
@@ -0,0 +1,121 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Search;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Customer/_files/three_customers.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
class CustomerTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider loadDataProvider
*/
public function testLoad($query, $limit, $start, $expectedResult)
{
/** Preconditions */
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Backend\Model\Search\Customer $customerSearch */
$customerSearch = $objectManager->create(\Magento\Backend\Model\Search\Customer::class);
$customerSearch->setQuery($query);
$customerSearch->setLimit($limit);
$customerSearch->setStart($start);
$customerSearch->load();
/** SUT Execution */
$searchResults = $customerSearch->getResults();
/** Ensure that search results are correct */
$this->assertCount(count($expectedResult), $searchResults, 'Quantity of search result items is invalid.');
foreach ($expectedResult as $itemIndex => $expectedItem) {
/** Validate URL to item */
$customerId = substr($expectedItem['id'], 11); // 'customer/1/' is added to all actual customer IDs
$this->assertStringContainsString(
"customer/index/edit/id/$customerId",
$searchResults[$itemIndex]['url'],
'Item URL is invalid.'
);
unset($searchResults[$itemIndex]['url']);
/** Validate other item data */
$this->assertEquals($expectedItem, $searchResults[$itemIndex], "Data of item #$itemIndex is invalid.");
}
}
public static function loadDataProvider()
{
return [
'All items, first page' => [
'Firstname',
2, // Items on page
1, // Page number
[
[
'id' => 'customer/1/1',
'type' => 'Customer',
'name' => 'Firstname Lastname',
'description' => 'CompanyName',
],
[
'id' => 'customer/1/2',
'type' => 'Customer',
'name' => 'Firstname2 Lastname2',
'description' => null
]
],
],
'All items, second page' => [
'Firstname',
2, // Items on page
2, // Page number
[
[
'id' => 'customer/1/3',
'type' => 'Customer',
'name' => 'Firstname3 Lastname3',
'description' => null,
]
],
],
'Search by last name, second item only' => [
'Lastname2',
10, // Items on page
1, // Page number
[
[
'id' => 'customer/1/2',
'type' => 'Customer',
'name' => 'Firstname2 Lastname2',
'description' => null,
]
],
],
'No results' => [
'NotExistingCustomerName',
10, // Items on page
1, // Page number
[],
],
'Search by company name, first item only' => [
'CompanyName',
10, // Items on page
1, // Page number
[
[
'id' => 'customer/1/1',
'type' => 'Customer',
'name' => 'Firstname Lastname',
'description' => 'CompanyName',
],
],
],
];
}
}
@@ -0,0 +1,135 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Search;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/order.php
* @magentoDataFixture Magento/Sales/_files/order_shipping_address_different_to_billing.php
*/
class OrderTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider loadDataProvider
*/
public function testLoad($query, $limit, $start, $expectedResult)
{
/** @var $order \Magento\Sales\Model\Order */
$order = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Sales\Model\Order::class);
$orderIdByIncrementId = [];
foreach (['100000001', '100000002', '100000003'] as $incrementId) {
$orderIdByIncrementId[$incrementId] = $order->loadByIncrementId($incrementId)->getId();
}
/** Preconditions */
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Backend\Model\Search\Order $orderSearch */
$orderSearch = $objectManager->create(\Magento\Backend\Model\Search\Order::class);
$orderSearch->setQuery($query);
$orderSearch->setLimit($limit);
$orderSearch->setStart($start);
$orderSearch->load();
/** SUT Execution */
$searchResults = $orderSearch->getResults();
/** Ensure that search results are correct */
$this->assertCount(count($expectedResult), $searchResults, 'Quantity of search result items is invalid.');
foreach ($expectedResult as $itemIndex => $expectedItem) {
/** Validate URL to item */
$orderIncrementId = substr($expectedItem['id'], strlen('order/1/#'));
$this->assertStringContainsString(
"order/view/order_id/{$orderIdByIncrementId[$orderIncrementId]}",
$searchResults[$itemIndex]['url'],
'Item URL is invalid.'
);
$expectedItem['id'] = 'order/1/' . $orderIdByIncrementId[$orderIncrementId];
unset($searchResults[$itemIndex]['url']);
/** Validate other item data */
foreach ($expectedItem as $field => $value) {
$this->assertEquals(
$value,
(string)$searchResults[$itemIndex][$field],
"Data of item #$itemIndex is invalid."
);
}
}
}
public static function loadDataProvider()
{
return [
'All items, first page' => [
'10000000',
2, // Items on page
1, // Page number
[
[
'id' => 'order/1/#100000001',
'type' => 'Order',
'name' => 'Order #100000001',
'description' => 'firstname lastname',
],
[
'id' => 'order/1/#100000002',
'type' => 'Order',
'name' => 'Order #100000002',
'description' => 'guest guest'
]
],
],
'All items, second page' => [
'10000000',
2, // Items on page
2, // Page number
[
[
'id' => 'order/1/#100000003',
'type' => 'Order',
'name' => 'Order #100000003',
'description' => 'guest guest',
]
],
],
'Search by first name, first item only' => [
'First',
10, // Items on page
1, // Page number
[
[
'id' => 'order/1/#100000001',
'type' => 'Order',
'name' => 'Order #100000001',
'description' => 'firstname lastname',
]
],
],
'No results' => [
'NotExistingOrder',
10, // Items on page
1, // Page number
[],
],
'Search by last name, first item only' => [
'last',
10, // Items on page
1, // Page number
[
[
'id' => 'order/1/#100000001',
'type' => 'Order',
'name' => 'Order #100000001',
'description' => 'firstname lastname',
]
],
],
];
}
}
@@ -0,0 +1,28 @@
<?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>
<tab id="test" translate="label" sortOrder="100">
<label>Test Tab</label>
</tab>
<section id="test_section" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" type="text" sortOrder="0">
<label>Test Section</label>
<tab>test</tab>
<resource>Magento_Backend::test</resource>
<group id="test_group" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" type="text" sortOrder="10">
<label>Test Group</label>
<field id="test_field_1" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" type="text" sortOrder="20">
<label>Test Field</label>
</field>
<field id="test_field_2" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" type="text" sortOrder="20">
<label>Test Field</label>
</field>
</group>
</section>
</system>
</config>
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Session;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Magento\Backend\Model\Session\AdminConfig.
*
* @magentoAppArea adminhtml
*/
class AdminConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
protected function setUp(): void
{
parent::setUp();
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
public function testConstructor()
{
$model = $this->objectManager->create(\Magento\Backend\Model\Session\AdminConfig::class);
$this->assertEquals('/index.php/backend', $model->getCookiePath());
}
/**
* Test for setting session name for admin
*
*/
public function testSetSessionNameByConstructor()
{
$sessionName = 'adminHtmlSession';
$adminConfig = $this->objectManager->create(
\Magento\Backend\Model\Session\AdminConfig::class,
['sessionName' => $sessionName]
);
$this->assertSame($sessionName, $adminConfig->getName());
}
}
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Session;
/**
* Class QuoteTest
*/
class QuoteTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoAppIsolation enabled
*/
public function testGetQuote()
{
/** Preconditions */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$fixtureCustomerId = 1;
/** @var \Magento\Backend\Model\Session\Quote $backendQuoteSession */
$backendQuoteSession = $objectManager->get(\Magento\Backend\Model\Session\Quote::class);
$backendQuoteSession->setCustomerId($fixtureCustomerId);
/** @var \Magento\Backend\Model\Session\Quote $quoteSession */
$quoteSession = $objectManager->create(\Magento\Backend\Model\Session\Quote::class);
$quoteSession->setEntity(new \Magento\Framework\DataObject());
/** SUT execution */
$quote = $quoteSession->getQuote();
/** Ensure that customer data was added to quote correctly */
$this->assertEquals(
'John',
$quote->getCustomer()->getFirstname(),
'Customer data was set to quote incorrectly.'
);
}
}
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model;
/**
* Test class for \Magento\Backend\Model\Session.
*
* @magentoAppArea adminhtml
*/
class SessionTest extends \PHPUnit\Framework\TestCase
{
public function testContructor()
{
if (array_key_exists('adminhtml', $_SESSION)) {
unset($_SESSION['adminhtml']);
}
$logger = $this->createMock(\Psr\Log\LoggerInterface::class);
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Backend\Model\Session::class,
[$logger]
);
$this->assertArrayHasKey('adminhtml', $_SESSION);
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model\Translate;
/**
* @magentoAppArea adminhtml
*/
class InlineTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Translate\InlineInterface
*/
protected $_translateInline;
protected function setUp(): void
{
$this->_translateInline = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\Translate\InlineInterface::class
);
}
/**
* @magentoAdminConfigFixture dev/translate_inline/active_admin 1
* @covers \Magento\Framework\Translate\Inline::getAjaxUrl
*/
public function testAjaxUrl()
{
$body = '<html><body>some body</body></html>';
/** @var \Magento\Backend\Model\UrlInterface $url */
$url = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\UrlInterface::class);
$url->getUrl(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE . '/ajax/translate');
$this->_translateInline->processResponseBody($body, true);
$expected = str_replace(
[':', '/'],
['\u003A', '\u002F'],
$url->getUrl(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE . '/ajax/translate')
);
$this->assertStringContainsString($expected, $body);
}
}
@@ -0,0 +1,245 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\Model;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Escaper;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for \Magento\Backend\Model\UrlInterface.
*
* @magentoAppArea adminhtml
*/
class UrlTest extends \PHPUnit\Framework\TestCase
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var UrlInterface
*/
private $_model;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->request = $this->objectManager->get(RequestInterface::class);
$this->_model = $this->objectManager->create(UrlInterface::class);
}
/**
* App isolation is enabled to protect next tests from polluted registry by getUrl().
*
* @param string $routePath
* @param array $requestParams
* @param string $expectedResult
* @param array|null $routeParams
* @return void
*
* @dataProvider getUrlDataProvider
* @magentoAppIsolation enabled
*/
public function testGetUrl(
string $routePath,
array $requestParams,
string $expectedResult,
$routeParams = null
): void {
$this->request->setParams($requestParams);
$url = $this->_model->getUrl($routePath, $routeParams);
$this->assertStringContainsString($expectedResult, $url);
}
/**
* Data provider for getUrl method.
*
* @return array
*/
public function getUrlDataProvider(): array
{
/** @var $escaper Escaper */
$escaper = Bootstrap::getObjectManager()->get(Escaper::class);
return [
[
'routePath' => 'adminhtml/auth/login',
'requestParams' => [],
'expectedResult'=> 'admin/auth/login/key/',
],
[
'routePath' => 'adminhtml/auth/login',
'requestParams' => [],
'expectedResult'=> '/param1/a1==/',
'routeParams' => [
'_escape_params' => false,
'param1' => 'a1==',
],
],
[
'routePath' => 'adminhtml/auth/login',
'requestParams' => [],
'expectedResult'=> '/param1/a1==/',
'routeParams' => [
'_escape_params' => false,
'param1' => 'a1==',
],
],
[
'routePath' => 'adminhtml/auth/login',
'requestParams' => ['param2' => 'a2=='],
'expectedResult'=> '/param2/a2==/',
'routeParams' => [
'_current' => true,
'_escape_params' => false,
],
],
[
'routePath' => 'adminhtml/auth/login',
'requestParams' => [],
'expectedResult' => '/param3/' . $escaper->encodeUrlParam('a3==') . '/',
'routeParams' => [
'_escape_params' => true,
'param3' => 'a3==',
],
],
[
'routePath' => 'adminhtml/auth/login',
'requestParams' => ['param4' => 'a4=='],
'expectedResult' => '/param4/' . $escaper->encodeUrlParam('a4==') . '/',
'routeParams' => [
'_current' => true,
'_escape_params' => true,
],
],
[
'routePath' => 'route/controller/action/id/100',
'requestParams' => [],
'expectedResult' => 'id/100',
],
];
}
/**
* @param string $routeName
* @param string $controller
* @param string $action
* @param string $expectedHash
* @return void
*
* @dataProvider getSecretKeyDataProvider
* @magentoAppIsolation enabled
*/
public function testGetSecretKey(string $routeName, string $controller, string $action, string $expectedHash): void
{
$this->request->setControllerName('default_controller')
->setActionName('default_action')
->setRouteName('default_router');
$this->_model->setRequest($this->request);
$this->objectManager->get(SessionManagerInterface::class)->setData('_form_key', 'salt');
$this->assertEquals($expectedHash, $this->_model->getSecretKey($routeName, $controller, $action));
}
/**
* @return array
*/
public function getSecretKeyDataProvider(): array
{
/** @var $encryptor EncryptorInterface */
$encryptor = Bootstrap::getObjectManager()->get(EncryptorInterface::class);
return [
[
'',
'',
'',
$encryptor->getHash('default_router' . 'default_controller' . 'default_action' . 'salt'),
],
['', '', 'action', $encryptor->getHash('default_router' . 'default_controller' . 'action' . 'salt')],
[
'',
'controller',
'',
$encryptor->getHash('default_router' . 'controller' . 'default_action' . 'salt'),
],
[
'',
'controller',
'action',
$encryptor->getHash('default_router' . 'controller' . 'action' . 'salt'),
],
[
'adminhtml',
'',
'',
$encryptor->getHash('adminhtml' . 'default_controller' . 'default_action' . 'salt'),
],
[
'adminhtml',
'',
'action',
$encryptor->getHash('adminhtml' . 'default_controller' . 'action' . 'salt'),
],
[
'adminhtml',
'controller',
'',
$encryptor->getHash('adminhtml' . 'controller' . 'default_action' . 'salt'),
],
[
'adminhtml',
'controller',
'action',
$encryptor->getHash('adminhtml' . 'controller' . 'action' . 'salt'),
],
];
}
/**
* @magentoAppIsolation enabled
* @return void
*/
public function testGetSecretKeyForwarded(): void
{
/** @var $encryptor EncryptorInterface */
$encryptor = $this->objectManager->get(EncryptorInterface::class);
$this->request->setControllerName('controller')->setActionName('action');
$this->request->initForward()->setControllerName(uniqid())->setActionName(uniqid());
$this->_model->setRequest($this->request);
$this->objectManager->get(SessionManagerInterface::class)->setData('_form_key', 'salt');
$this->assertEquals($encryptor->getHash('controller' . 'action' . 'salt'), $this->_model->getSecretKey());
}
/**
* @return void
*/
public function testUseSecretKey(): void
{
$this->_model->setNoSecret(true);
$this->assertFalse($this->_model->useSecretKey());
$this->_model->setNoSecret(false);
$this->assertTrue($this->_model->useSecretKey());
}
}