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,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\App;
use Magento\TestFramework\Bootstrap;
/**
* Test class for \Magento\Backend\App\AbstractAction.
* @magentoAppArea adminhtml
*/
class AbstractActionTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Check redirection to startup page for logged user
* @magentoConfigFixture current_store admin/security/use_form_key 1
* @magentoAppIsolation enabled
*/
public function testPreDispatchWithEmptyUrlRedirectsToStartupPage()
{
$this->markTestSkipped('Session destruction doesn\'t work');
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Config\ScopeInterface::class
)->setCurrentScope(
\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE
);
$this->dispatch('backend');
/** @var $backendUrlModel \Magento\Backend\Model\UrlInterface */
$backendUrlModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Backend\Model\UrlInterface::class
);
$url = $backendUrlModel->getStartupPageUrl();
$expected = $backendUrlModel->getUrl($url);
$this->assertRedirect($this->stringStartsWith($expected));
}
/**
* Check login redirection
*
* @magentoDbIsolation enabled
*/
public function testInitAuthentication()
{
/**
* Logout current session
*/
$this->_auth->logout();
/** @var \Magento\Framework\Data\Form\FormKey $formKey */
$formKey = $this->_objectManager->get(\Magento\Framework\Data\Form\FormKey::class);
$postLogin = [
'login' => [
'username' => \Magento\TestFramework\Bootstrap::ADMIN_NAME,
'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD,
],
'form_key' => $formKey->getFormKey(),
];
$this->getRequest()->setPostValue($postLogin);
$this->dispatch('backend/admin/system_account/index');
$expected = 'backend/admin/system_account/index';
$this->assertRedirect($this->stringContains($expected));
}
/**
* Check layout attribute "acl" for check access to
*
* @param string $blockName
* @param string $resource
* @param bool $isLimitedAccess
* @dataProvider nodesWithAcl
*/
public function testAclInNodes($blockName, $resource, $isLimitedAccess)
{
/** @var $noticeInbox \Magento\AdminNotification\Model\Inbox */
$noticeInbox = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\AdminNotification\Model\Inbox::class
);
if (!$noticeInbox->loadLatestNotice()->getId()) {
$noticeInbox->addCritical('Test notice', 'Test description');
}
$this->_auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
/** @var $acl \Magento\Framework\Acl */
$acl = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Acl\Builder::class)
->getAcl();
if ($isLimitedAccess) {
$acl->deny(Bootstrap::ADMIN_ROLE_ID, $resource);
}
$this->dispatch('backend/admin/dashboard');
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
$actualBlocks = $layout->getAllBlocks();
$this->assertNotEmpty($actualBlocks);
if ($isLimitedAccess) {
$this->assertNotContains($blockName, array_keys($actualBlocks));
} else {
$this->assertContains($blockName, array_keys($actualBlocks));
}
}
/**
* Data provider with expected blocks with acl properties
*
* @return array
*/
public function nodesWithAcl()
{
return [
['notification_window', 'Magento_AdminNotification::show_toolbar', true],
['notification_window', 'Magento_AdminNotification::show_toolbar', false]
];
}
}
@@ -0,0 +1,49 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Backend\App\Area;
use PHPUnit\Framework\TestCase;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class FrontNameResolverTest extends TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* @var FrontNameResolver
*/
protected $model;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(
FrontNameResolver::class
);
$_SERVER['HTTP_HOST'] = 'localhost';
}
/**
* @magentoDbIsolation enabled
* @magentoConfigFixture current_store web/unsecure/base_url http://example.com/
*/
public function testIsHostBackend()
{
$this->assertTrue($this->model->isHostBackend());
}
}
@@ -0,0 +1,435 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Backend\App\Request;
use Magento\Backend\App\AbstractAction;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Auth;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\Phrase;
use Magento\TestFramework\Request;
use Magento\TestFramework\Response;
use PHPUnit\Framework\TestCase;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Bootstrap as TestBootstrap;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\App\Response\Http as HttpResponse;
use Laminas\Stdlib\Parameters;
use Magento\Backend\Model\UrlInterface as BackendUrl;
use Magento\Framework\App\Response\HttpFactory as HttpResponseFactory;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BackendValidatorTest extends TestCase
{
private const AWARE_VALIDATION_PARAM = 'test_param';
private const AWARE_LOCATION_VALUE = 'test1';
private const CSRF_AWARE_MESSAGE = 'csrf_aware';
/**
* @var ActionInterface
*/
private $mockUnawareAction;
/**
* @var AbstractAction
*/
private $mockAwareAction;
/**
* @var BackendValidator
*/
private $validator;
/**
* @var Request
*/
private $request;
/**
* @var FormKey
*/
private $formKey;
/**
* @var BackendUrl
*/
private $url;
/**
* @var Auth
*/
private $auth;
/**
* @var CsrfAwareActionInterface
*/
private $mockCsrfAwareAction;
/**
* @var HttpResponseFactory
*/
private $httpResponseFactory;
/**
* @return ActionInterface
*/
private function createUnawareAction(): ActionInterface
{
return new class implements ActionInterface {
/**
* @inheritDoc
*/
public function execute()
{
throw new NotFoundException(new Phrase('Not implemented'));
}
};
}
/**
* @return AbstractAction
*/
private function createAwareAction(): AbstractAction
{
$l = self::AWARE_LOCATION_VALUE;
$p = self::AWARE_VALIDATION_PARAM;
return new class($l, $p) extends AbstractAction{
/**
* @var string
*/
private $locationValue;
/**
* @var string
*/
private $param;
/**
* @param string $locationValue
* @param string $param
*/
public function __construct(
string $locationValue,
string $param
) {
parent::__construct(
Bootstrap::getObjectManager()->get(Context::class)
);
$this->locationValue= $locationValue;
$this->param = $param;
}
/**
* @inheritDoc
*/
public function execute()
{
throw new NotFoundException(new Phrase('Not implemented'));
}
/**
* @inheritDoc
*/
public function _processUrlKeys()
{
if ($this->_request->getParam($this->param)) {
return true;
} else {
/** @var Response $response */
$response = $this->_response;
$response->setHeader('Location', $this->locationValue);
return false;
}
}
};
}
/**
* @return CsrfAwareActionInterface
*/
private function createCsrfAwareAction(): CsrfAwareActionInterface
{
$r = Bootstrap::getObjectManager()
->get(ResponseInterface::class);
$m = self::CSRF_AWARE_MESSAGE;
return new class ($r, $m) implements CsrfAwareActionInterface {
/**
* @var ResponseInterface
*/
private $response;
/**
* @var string
*/
private $message;
/**
* @param ResponseInterface $response
* @param string $message
*/
public function __construct(
ResponseInterface $response,
string $message
) {
$this->response = $response;
$this->message = $message;
}
/**
* @inheritDoc
*/
public function execute()
{
return $this->response;
}
/**
* @inheritDoc
*/
public function createCsrfValidationException(
RequestInterface $request
): ?InvalidRequestException {
return new InvalidRequestException(
$this->response,
[new Phrase($this->message)]
);
}
/**
* @inheritDoc
*/
public function validateForCsrf(RequestInterface $request): ?bool
{
return false;
}
};
}
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->request = $objectManager->get(RequestInterface::class);
$this->validator = $objectManager->get(BackendValidator::class);
$this->mockUnawareAction = $this->createUnawareAction();
$this->mockAwareAction = $this->createAwareAction();
$this->formKey = $objectManager->get(FormKey::class);
$this->url = $objectManager->get(BackendUrl::class);
$this->auth = $objectManager->get(Auth::class);
$this->mockCsrfAwareAction = $this->createCsrfAwareAction();
$this->httpResponseFactory = $objectManager->get(
HttpResponseFactory::class
);
}
/**
* @magentoConfigFixture admin/security/use_form_key 1
* @magentoAppArea adminhtml
*/
public function testValidateWithValidKey()
{
$this->request->setMethod(HttpRequest::METHOD_GET);
$this->auth->login(
TestBootstrap::ADMIN_NAME,
TestBootstrap::ADMIN_PASSWORD
);
$this->request->setParams([
BackendUrl::SECRET_KEY_PARAM_NAME => $this->url->getSecretKey(),
]);
$this->validator->validate(
$this->request,
$this->mockUnawareAction
);
}
/**
*
* @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,
]);
$this->request->setMethod(HttpRequest::METHOD_GET);
$this->auth->login(
TestBootstrap::ADMIN_NAME,
TestBootstrap::ADMIN_PASSWORD
);
$this->validator->validate(
$this->request,
$this->mockUnawareAction
);
}
/**
*
* @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'])
);
$this->request->setMethod(HttpRequest::METHOD_POST);
$this->validator->validate(
$this->request,
$this->mockUnawareAction
);
}
/**
* @magentoConfigFixture admin/security/use_form_key 0
* @magentoAppArea adminhtml
*/
public function testValidateInvalidWithAwareAction()
{
$this->request->setParams([self::AWARE_VALIDATION_PARAM => '']);
/** @var InvalidRequestException|null $caught */
$caught = null;
try {
$this->validator->validate(
$this->request,
$this->mockAwareAction
);
} catch (InvalidRequestException $exception) {
$caught = $exception;
}
$this->assertNotNull($caught);
/** @var Response $response */
$response = $caught->getReplaceResult();
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals(
self::AWARE_LOCATION_VALUE,
$response->getHeader('Location')->getFieldValue()
);
$this->assertNull($caught->getMessages());
}
/**
* @magentoAppArea adminhtml
*/
public function testValidateValidWithAwareAction()
{
$this->request->setParams(
[self::AWARE_VALIDATION_PARAM => '1']
);
$this->validator->validate(
$this->request,
$this->mockAwareAction
);
}
/**
* @magentoConfigFixture admin/security/use_form_key 1
* @magentoAppArea adminhtml
*/
public function testValidateWithCsrfAwareAction()
{
//Setting up request that would be valid for default validation.
$this->request->setMethod(HttpRequest::METHOD_GET);
$this->auth->login(
TestBootstrap::ADMIN_NAME,
TestBootstrap::ADMIN_PASSWORD
);
$this->request->setParams([
BackendUrl::SECRET_KEY_PARAM_NAME => $this->url->getSecretKey(),
]);
/** @var InvalidRequestException|null $caught */
$caught = null;
try {
$this->validator->validate(
$this->request,
$this->mockCsrfAwareAction
);
} catch (InvalidRequestException $exception) {
$caught = $exception;
}
//Checking that custom validation was called and invalidated
//valid request.
$this->assertNotNull($caught);
$this->assertCount(1, $caught->getMessages());
$this->assertEquals(
self::CSRF_AWARE_MESSAGE,
$caught->getMessages()[0]->getText()
);
}
public function testInvalidAjaxRequest()
{
//Setting up AJAX request with invalid secret key.
$this->request->setMethod(HttpRequest::METHOD_GET);
$this->auth->login(
TestBootstrap::ADMIN_NAME,
TestBootstrap::ADMIN_PASSWORD
);
$this->request->setParams([
BackendUrl::SECRET_KEY_PARAM_NAME => 'invalid',
'isAjax' => '1'
]);
/** @var InvalidRequestException|null $caught */
$caught = null;
try {
$this->validator->validate(
$this->request,
$this->mockUnawareAction
);
} catch (InvalidRequestException $exception) {
$caught = $exception;
}
$this->assertNotNull($caught);
$this->assertInstanceOf(
ResultInterface::class,
$caught->getReplaceResult()
);
/** @var ResultInterface $result */
$result = $caught->getReplaceResult();
/** @var HttpResponse $response */
$response = $this->httpResponseFactory->create();
$result->renderResult($response);
$this->assertEmpty($response->getBody());
$this->assertEquals(401, $response->getHttpResponseCode());
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Backend\App;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class RouterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\App\Router
*/
protected $model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(\Magento\Backend\App\Router::class);
}
public function testRouterCanProcessRequestsWithProperPathInfo()
{
$request = $this->createMock(\Magento\Framework\App\Request\Http::class);
$request->expects($this->once())->method('getPathInfo')->willReturn('backend/admin/dashboard');
$this->assertInstanceOf(\Magento\Backend\Controller\Adminhtml\Dashboard::class, $this->model->match($request));
}
/**
* @param string $module
* @param string $controller
* @param string $className
*
* @dataProvider getControllerClassNameDataProvider
*/
public function testGetControllerClassName($module, $controller, $className)
{
$this->assertEquals($className, $this->model->getActionClassName($module, $controller));
}
public function getControllerClassNameDataProvider()
{
return [
['Magento_TestModule', 'controller', \Magento\TestModule\Controller\Adminhtml\Controller::class],
];
}
public function testMatchCustomNoRouteAction()
{
if (!\Magento\TestFramework\Helper\Bootstrap::canTestHeaders()) {
$this->markTestSkipped('Can\'t test get match without sending headers');
}
$routers = [
'testmodule' => [
'frontName' => 'testfixture',
'id' => 'testfixture',
'modules' => ['Magento_TestFixture'],
],
];
$routeConfig = $this->getMockBuilder(\Magento\Framework\App\Route\Config::class)
->setMethods(['_getRoutes'])
->setConstructorArgs(
[
'reader' => $this->objectManager->get(\Magento\Framework\App\Route\Config\Reader::class),
'cache' => $this->objectManager->get(\Magento\Framework\Config\CacheInterface::class),
'configScope' => $this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class),
'areaList' => $this->objectManager->get(\Magento\Framework\App\AreaList::class),
'cacheId' => 'RoutesConfig'
]
)
->getMock();
$routeConfig->expects($this->any())->method('_getRoutes')->willReturn($routers);
$defaultRouter = $this->objectManager->create(
\Magento\Backend\App\Router::class,
['routeConfig' => $routeConfig]
);
/** @var $request \Magento\TestFramework\Request */
$request = $this->objectManager->get(\Magento\TestFramework\Request::class);
$request->setPathInfo('backend/testfixture/test_controller');
$controller = $defaultRouter->match($request);
$this->assertInstanceOf(\Magento\TestFixture\Controller\Adminhtml\Noroute::class, $controller);
$this->assertEquals('noroute', $request->getActionName());
}
}