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,137 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase;
use Magento\Framework\Acl\Builder as AclBuilder;
use Magento\TestFramework\Bootstrap;
/**
* A parent class for backend controllers - contains directives for admin user creation and authentication.
*
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/
abstract class AbstractBackendController extends \Magento\TestFramework\TestCase\AbstractController
{
/**
* @var \Magento\Backend\Model\Auth\Session
*/
protected $_session;
/**
* @var \Magento\Backend\Model\Auth
*/
protected $_auth;
/**
* The resource used to authorize action
*
* @var string
*/
protected $resource = null;
/**
* The uri at which to access the controller
*
* @var string
*/
protected $uri = null;
/**
* @var string|null
*/
protected $httpMethod;
/**
* Expected no access response
*
* @var int
*/
protected $expectedNoAccessResponseCode = 403;
/**
* @inheritDoc
*
* @throws \Magento\Framework\Exception\AuthenticationException
*/
protected function setUp(): void
{
parent::setUp();
$this->_objectManager->get(\Magento\Backend\Model\UrlInterface::class)->turnOffSecretKey();
/**
* Authorization can be created on test bootstrap...
* If it will be created on test bootstrap we will have invalid RoleLocator object.
* As tests by default are run not from adminhtml area...
*/
\Magento\TestFramework\ObjectManager::getInstance()->removeSharedInstance(
\Magento\Framework\Authorization::class
);
$this->_auth = $this->_objectManager->get(\Magento\Backend\Model\Auth::class);
$this->_session = $this->_auth->getAuthStorage();
$credentials = $this->_getAdminCredentials();
$this->_auth->login($credentials['user'], $credentials['password']);
$this->_objectManager->get(\Magento\Security\Model\Plugin\Auth::class)->afterLogin($this->_auth);
}
/**
* Get credentials to login admin user
*
* @return array
*/
protected function _getAdminCredentials()
{
return [
'user' => \Magento\TestFramework\Bootstrap::ADMIN_NAME,
'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
];
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
$this->_auth->getAuthStorage()->destroy(['send_expire_cookie' => false]);
$this->_auth = null;
$this->_session = null;
$this->_objectManager->get(\Magento\Backend\Model\UrlInterface::class)->turnOnSecretKey();
parent::tearDown();
}
/**
* Test ACL configuration for action working.
*/
public function testAclHasAccess()
{
if ($this->uri === null) {
$this->markTestSkipped('AclHasAccess test is not complete');
}
if ($this->httpMethod) {
$this->getRequest()->setMethod($this->httpMethod);
}
$this->dispatch($this->uri);
$this->assertNotSame(404, $this->getResponse()->getHttpResponseCode());
$this->assertNotSame($this->expectedNoAccessResponseCode, $this->getResponse()->getHttpResponseCode());
}
/**
* Test ACL actually denying access.
*/
public function testAclNoAccess()
{
if ($this->resource === null || $this->uri === null) {
$this->markTestSkipped('Acl test is not complete');
}
if ($this->httpMethod) {
$this->getRequest()->setMethod($this->httpMethod);
}
$acl = $this->_objectManager->get(AclBuilder::class)->getAcl();
$acl->deny($this->_auth->getUser()->getRoles(), $this->resource);
$this->dispatch($this->uri);
$this->assertSame($this->expectedNoAccessResponseCode, $this->getResponse()->getHttpResponseCode());
}
}
@@ -0,0 +1,170 @@
<?php
/**
* Abstract class that helps in writing tests that validate config xml files
* are valid both individually and when merged.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\TestCase;
use Magento\Framework\Component\ComponentRegistrar;
abstract class AbstractConfigFiles extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
protected $_schemaFile;
/**
* @var \Magento\Framework\Config\Reader\Filesystem
*/
protected $_reader;
/**
* @var \PHPUnit\Framework\MockObject\MockObject
*/
protected $_fileResolverMock;
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
/**
* @var ComponentRegistrar
*/
protected $componentRegistrar;
protected function setUp(): void
{
$this->componentRegistrar = new ComponentRegistrar();
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$xmlFiles = $this->getXmlConfigFiles();
if (!empty($xmlFiles)) {
$this->_fileResolverMock = $this->getMockBuilder(
\Magento\Framework\App\Arguments\FileResolver\Primary::class
)->disableOriginalConstructor()->getMock();
/* Enable Validation regardless of MAGE_MODE */
$validateStateMock = $this->getMockBuilder(
\Magento\Framework\Config\ValidationStateInterface::class
)->disableOriginalConstructor()->getMock();
$validateStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$this->_reader = $this->_objectManager->create(
$this->_getReaderClassName(),
[
'configFiles' => $xmlFiles,
'fileResolver' => $this->_fileResolverMock,
'validationState' => $validateStateMock
]
);
$this->_schemaFile = $this->_getXsdPath();
}
}
protected function tearDown(): void
{
$this->_objectManager->removeSharedInstance($this->_getReaderClassName());
}
/**
* @dataProvider xmlConfigFileProvider
*/
public function testXmlConfigFile($file, $skip = false)
{
if ($skip) {
$this->markTestSkipped('There are no xml files in the system for this test.');
}
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(false);
$domConfig = new \Magento\Framework\Config\Dom($file, $validationStateMock);
$errors = [];
$result = $domConfig->validate($this->_schemaFile, $errors);
$message = "Invalid XML-file: {$file}\n";
foreach ($errors as $error) {
$message .= "{$error}\n";
}
$this->assertTrue($result, $message);
}
public function testMergedConfig()
{
$files = $this->getXmlConfigFiles();
if (empty($files)) {
$this->markTestSkipped('There are no xml files in the system for this test.');
}
// have the file resolver return all relevant xml files
$this->_fileResolverMock->expects($this->any())
->method('get')
->willReturn($this->getXmlConfigFiles());
try {
// this will merge all xml files and validate them
$this->_reader->read('global');
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->fail($e->getMessage());
}
}
/**
* Returns an array of all the config xml files for this test.
*
* Handles the case where no files were found and notifies the test to skip.
* This is needed to avoid a fatal error caused by a provider returning an empty array.
*
* @return array
*/
public function xmlConfigFileProvider()
{
$fileList = $this->getXmlConfigFiles();
$result = [];
foreach ($fileList as $fileContent) {
$result[] = [$fileContent];
}
return $result;
}
/**
* Finds all config xml files based on a path glob.
*
* @return \Magento\Framework\Config\FileIterator
*/
public function getXmlConfigFiles()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
return $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class)
->create($moduleDirSearch->collectFiles(ComponentRegistrar::MODULE, $this->_getConfigFilePathGlob()));
}
/**
* Returns the reader class name that will be instantiated via ObjectManager
*
* @return string reader class name
*/
abstract protected function _getReaderClassName();
/**
* Returns a string that represents the path to the config file, starting in the app directory.
*
* Format is glob, so * is allowed.
*
* @return string
*/
abstract protected function _getConfigFilePathGlob();
/**
* Returns an absolute path to the XSD file corresponding to the XML files specified in _getConfigFilePathGlob
*
* @return string
*/
abstract protected function _getXsdPath();
}
@@ -0,0 +1,339 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* 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 PHPUnit\Framework\TestCase;
/**
* Set of methods useful for performing requests to Controllers.
*
* @SuppressWarnings(PHPMD.NumberOfChildren)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class AbstractController extends TestCase
{
protected $_runCode = '';
protected $_runScope = 'store';
protected $_runOptions = [];
/**
* @var RequestInterface
*/
protected $_request;
/**
* @var ResponseInterface
*/
protected $_response;
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
/**
* Whether absence of session error messages has to be asserted automatically upon a test completion
*
* @var bool
*/
protected $_assertSessionErrors = false;
/**
* Bootstrap instance getter
*
* @return \Magento\TestFramework\Helper\Bootstrap
*/
protected function _getBootstrap()
{
return \Magento\TestFramework\Helper\Bootstrap::getInstance();
}
/**
* Bootstrap application before any test
*/
protected function setUp(): void
{
$this->_assertSessionErrors = false;
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_objectManager->removeSharedInstance(\Magento\Framework\App\ResponseInterface::class);
$this->_objectManager->removeSharedInstance(\Magento\Framework\App\RequestInterface::class);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
$this->_request = null;
$this->_response = null;
$this->_objectManager = null;
}
/**
* Ensure that there were no error messages displayed on the admin panel
*/
protected function assertPostConditions(): void
{
if ($this->_assertSessionErrors) {
// equalTo() is intentionally used instead of isEmpty() to provide the informative diff
$this->assertSessionMessages(
$this->equalTo([]),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
}
/**
* Run request
*
* @param string $uri
*/
public function dispatch($uri)
{
$request = $this->getRequest();
$request->setDispatched(false);
$request->setRequestUri($uri);
if ($request->isPost()
&& !property_exists($request->getPost(), 'form_key')
) {
/** @var FormKey $formKey */
$formKey = $this->_objectManager->get(FormKey::class);
$request->setPostValue('form_key', $formKey->getFormKey());
}
$this->_getBootstrap()->runApp();
}
/**
* Request getter
*
* @return RequestInterface
*/
public function getRequest()
{
if (!$this->_request) {
$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 ResponseInterface
*/
public function getResponse()
{
if (!$this->_response) {
$this->_response = $this->_objectManager->get(ResponseInterface::class);
}
return $this->_response;
}
/**
* Assert that response is '404 Not Found'
*/
public function assert404NotFound()
{
$this->assertEquals('noroute', $this->getRequest()->getControllerName());
$this->assertStringContainsString('404 Not Found', $this->getResponse()->getBody());
}
/**
* Analyze response object and look for header with specified name, and assert a regex towards its value
*
* @param string $headerName
* @param string $valueRegex
* @throws \PHPUnit\Framework\AssertionFailedError when header not found
*/
public function assertHeaderPcre($headerName, $valueRegex)
{
$headerFound = false;
$headers = $this->getResponse()->getHeaders();
foreach ($headers as $header) {
if ($header->getFieldName() === $headerName) {
$headerFound = true;
$this->assertMatchesRegularExpression($valueRegex, $header->getFieldValue());
}
}
if (!$headerFound) {
$this->fail("Header '{$headerName}' was not found. Headers dump:\n" . var_export($headers, 1));
}
}
/**
* Assert that there is a redirect to expected URL.
* Omit expected URL to check that redirect to wherever has been occurred.
* Examples of usage:
* $this->assertRedirect($this->equalTo($expectedUrl));
* $this->assertRedirect($this->stringStartsWith($expectedUrlPrefix));
* $this->assertRedirect($this->stringEndsWith($expectedUrlSuffix));
* $this->assertRedirect($this->stringContains($expectedUrlSubstring));
*
* @param \PHPUnit\Framework\Constraint\Constraint|null $urlConstraint
*/
public function assertRedirect(\PHPUnit\Framework\Constraint\Constraint $urlConstraint = null)
{
$this->assertTrue($this->getResponse()->isRedirect(), 'Redirect was expected, but none was performed.');
if ($urlConstraint) {
$actualUrl = '';
foreach ($this->getResponse()->getHeaders() as $header) {
if ($header->getFieldName() == 'Location') {
$actualUrl = $header->getFieldValue();
break;
}
}
$this->assertThat($actualUrl, $urlConstraint, 'Redirection URL does not match expectations');
}
}
/**
* Assert that actual session messages meet expectations:
* Usage examples:
* $this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR);
* $this->assertSessionMessages($this->equalTo(['Entity has been saved.'],
* \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS);
*
* @param \PHPUnit\Framework\Constraint\Constraint $constraint Constraint to compare actual messages against
* @param string|null $messageType Message type filter,
* one of the constants \Magento\Framework\Message\MessageInterface::*
* @param string $messageManagerClass Class of the session model that manages messages
*/
public function assertSessionMessages(
\PHPUnit\Framework\Constraint\Constraint $constraint,
$messageType = null,
$messageManagerClass = \Magento\Framework\Message\Manager::class
) {
$this->_assertSessionErrors = false;
/** @var MessageInterface[]|string[] $messageObjects */
$messages = $this->getMessages($messageType, $messageManagerClass);
/** @var string[] $messages */
$messagesFiltered = array_map(
function ($message) {
/** @var MessageInterface|string $message */
return ($message instanceof MessageInterface) ? $message->toString() : $message;
},
$messages
);
$this->assertThat(
$messagesFiltered,
$constraint,
'Session messages do not meet expectations ' . var_export($messagesFiltered, true)
);
}
/**
* Return all stored messages
*
* @param string|null $messageType
* @param string $messageManagerClass
* @return array
*/
protected function getMessages(
$messageType = null,
$messageManagerClass = \Magento\Framework\Message\Manager::class
) {
return array_merge(
$this->getSessionMessages($messageType, $messageManagerClass),
$this->getCookieMessages($messageType)
);
}
/**
* Return messages stored in session
*
* @param string|null $messageType
* @param string $messageManagerClass
* @return array
*/
protected function getSessionMessages(
$messageType = null,
$messageManagerClass = \Magento\Framework\Message\Manager::class
) {
/** @var $messageManager \Magento\Framework\Message\ManagerInterface */
$messageManager = $this->_objectManager->get($messageManagerClass);
/** @var $messages \Magento\Framework\Message\AbstractMessage[] */
if ($messageType === null) {
$messages = $messageManager->getMessages()->getItems();
} else {
$messages = $messageManager->getMessages()->getItemsByType($messageType);
}
/** @var $messageManager InterpretationStrategyInterface */
$interpretationStrategy = $this->_objectManager->get(InterpretationStrategyInterface::class);
$actualMessages = [];
foreach ($messages as $message) {
$actualMessages[] = $interpretationStrategy->interpret($message);
}
return $actualMessages;
}
/**
* Return messages stored in cookies by type
*
* @param string|null $messageType
* @return array
*/
protected function getCookieMessages($messageType = null)
{
/** @var $cookieManager CookieManagerInterface */
$cookieManager = $this->_objectManager->get(CookieManagerInterface::class);
/** @var $jsonSerializer \Magento\Framework\Serialize\Serializer\Json */
$jsonSerializer = $this->_objectManager->get(\Magento\Framework\Serialize\Serializer\Json::class);
try {
$messages = $jsonSerializer->unserialize(
$cookieManager->getCookie(
MessagePlugin::MESSAGES_COOKIES_NAME,
$jsonSerializer->serialize([])
)
);
if (!is_array($messages)) {
$messages = [];
}
} catch (\InvalidArgumentException $e) {
$messages = [];
}
$actualMessages = [];
foreach ($messages as $message) {
if ($messageType === null || $message['type'] == $messageType) {
$actualMessages[] = $message['text'];
}
}
return $actualMessages;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* An ancestor class for integrity tests
*/
namespace Magento\TestFramework\TestCase;
abstract class AbstractIntegrity extends \PHPUnit\Framework\TestCase
{
/**
* Cached index of enabled modules
*
* @var array
*/
protected $_enabledModules = null;
/**
* Returns array of enabled modules
*
* @return array
*/
protected function _getEnabledModules()
{
if ($this->_enabledModules === null) {
/** @var $helper \Magento\TestFramework\Helper\Config */
$helper = \Magento\TestFramework\Helper\Factory::getHelper(\Magento\TestFramework\Helper\Config::class);
$enabledModules = $helper->getEnabledModules();
$this->_enabledModules = array_combine($enabledModules, $enabledModules);
}
return $this->_enabledModules;
}
/**
* Checks resource file declaration - whether it is for disabled module (e.g. 'Disabled_Module::file.ext').
*
* @param string $file
* @return bool
*/
protected function _isFileForDisabledModule($file)
{
$enabledModules = $this->_getEnabledModules();
if (preg_match('/^(.*)::/', $file, $matches)) {
$module = $matches[1];
if (!isset($enabledModules[$module])) {
return true;
}
}
return false;
}
/**
* Returns flat array of themes currently located in system
*
* @return \Magento\Theme\Model\Theme[]
*/
protected function _getDesignThemes()
{
$themeItems = [];
/** @var $themeCollection \Magento\Theme\Model\Theme\Collection */
$themeCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Theme\Model\ResourceModel\Theme\Collection::class
);
/** @var $theme \Magento\Framework\View\Design\ThemeInterface */
foreach ($themeCollection as $theme) {
$themeItems[$theme->getId()] = $theme;
}
return $themeItems;
}
}