ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,36 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity;
use Magento\TestFramework\Helper\Bootstrap;
class DatabaseTest extends \PHPUnit\Framework\TestCase
{
/**
* Assure that there are no redundant indexes declared in database
*/
public function testDuplicateKeys()
{
if (!defined('PERCONA_TOOLKIT_BIN_DIR')) {
$this->markTestSkipped('Path to Percona Toolkit is not specified.');
}
$checkerPath = PERCONA_TOOLKIT_BIN_DIR . '/pt-duplicate-key-checker';
$db = Bootstrap::getInstance()->getBootstrap()->getApplication()->getDbInstance();
$command = $checkerPath . ' -d ' . $db->getSchema()
. ' h=' . $db->getHost()['db-host'] . ',u=' . $db->getUser() . ',p=' . $db->getPassword();
// exec() have to be here since this is test.
// phpcs:ignore Magento2.Security.InsecureFunction
exec($command, $output, $exitCode);
$this->assertEquals(0, $exitCode);
$output = implode(PHP_EOL, $output);
if (preg_match('/Total Duplicate Indexes\s+(\d+)/', $output, $matches)) {
$this->fail($matches[1] . ' duplicate indexes found.' . PHP_EOL . PHP_EOL . $output);
}
}
}
@@ -0,0 +1,337 @@
<?php
/**
* Layout nodes integrity tests
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class LayoutTest extends \PHPUnit\Framework\TestCase
{
/**
* Cached lists of files
*
* @var array
*/
protected static $_cachedFiles = [];
public static function setUpBeforeClass(): void
{
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->configure(
['preferences' => [\Magento\Theme\Model\Theme::class => \Magento\Theme\Model\Theme\Data::class]]
);
}
public static function tearDownAfterClass(): void
{
self::$_cachedFiles = []; // Free memory
}
/**
* Composes full layout xml for designated parameters
*
* @param \Magento\Framework\View\Design\ThemeInterface $theme
* @return \Magento\Framework\View\Layout\Element
*/
protected function _composeXml(\Magento\Framework\View\Design\ThemeInterface $theme)
{
/** @var \Magento\Framework\View\Layout\ProcessorInterface $layoutUpdate */
$layoutUpdate = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\View\Layout\ProcessorInterface::class,
['theme' => $theme]
);
return $layoutUpdate->getFileLayoutUpdatesXml();
}
/**
* Validate node's declared position in hierarchy and add errors to the specified array if found
*
* @param \SimpleXMLElement $node
* @param \Magento\Framework\View\Layout\Element $xml
* @param array &$errors
*/
protected function _collectHierarchyErrors($node, $xml, &$errors)
{
$name = $node->getName();
$refName = $node->getAttribute('type') == $node->getAttribute('parent');
if ($refName) {
$refNode = $xml->xpath("/layouts/{$refName}");
if (!$refNode) {
$errors[$name][] = "Node '{$refName}', referenced in hierarchy, does not exist";
}
}
}
/**
* List all themes available in the system
*
* A test that uses such data provider is supposed to gather view resources in provided scope
* and analyze their integrity. For example, merge and verify all layouts in this scope.
*
* Such tests allow to uncover complicated code integrity issues, that may emerge due to view fallback mechanism.
* For example, a module layout file is overlapped by theme layout, which has mistakes.
* Such mistakes can be uncovered only when to emulate this particular theme.
* Also emulating "no theme" mode allows to detect inversed errors: when there is a view file with mistake
* in a module, but it is overlapped by every single theme by files without mistake. Putting question of code
* duplication aside, it is even more important to detect such errors, than an error in a single theme.
*
* @return array
*/
public function areasAndThemesDataProvider()
{
$result = [];
$themeCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\View\Design\ThemeInterface::class
)->getCollection();
/** @var $theme \Magento\Framework\View\Design\ThemeInterface */
foreach ($themeCollection as $theme) {
$result[$theme->getFullPath() . ' [' . $theme->getId() . ']'] = [$theme];
}
return $result;
}
public function testHandleLabels()
{
$invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
$invoker(
/**
* @param \Magento\Framework\View\Design\ThemeInterface $theme
*/
function (\Magento\Framework\View\Design\ThemeInterface $theme) {
$xml = $this->_composeXml($theme);
$xpath = '/layouts/*[@design_abstraction]';
$handles = $xml->xpath($xpath) ?: [];
/** @var \Magento\Framework\View\Layout\Element $node */
$errors = [];
foreach ($handles as $node) {
if (!$node->xpath('@label')) {
$nodeId = $node->getAttribute('id') ? ' id=' . $node->getAttribute('id') : '';
$errors[] = $node->getName() . $nodeId;
}
}
if ($errors) {
$this->fail(
'The following handles must have label, but they don\'t have it:' . PHP_EOL . var_export(
$errors,
true
)
);
}
},
$this->areasAndThemesDataProvider()
);
}
public function testPageTypesDeclaration()
{
$invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
$invoker(
/**
* Check whether page types are declared only in layout update files allowed for it - base ones
*/
function (\Magento\Framework\View\File $layout) {
$content = simplexml_load_file($layout->getFilename());
$this->assertEmpty(
$content->xpath(\Magento\Framework\View\Model\Layout\Merge::XPATH_HANDLE_DECLARATION),
"Theme layout update '" . $layout->getFilename() . "' contains page type declaration(s)"
);
},
$this->pageTypesDeclarationDataProvider()
);
}
/**
* Get theme layout updates
*
* @return \Magento\Framework\View\File[]
*/
public function pageTypesDeclarationDataProvider()
{
/** @var $themeUpdates \Magento\Framework\View\File\Collector\ThemeModular */
$themeUpdates = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Framework\View\File\Collector\ThemeModular::class, ['subDir' => 'layout']);
/** @var $themeUpdatesOverride \Magento\Framework\View\File\Collector\Override\ThemeModular */
$themeUpdatesOverride = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(
\Magento\Framework\View\File\Collector\Override\ThemeModular::class,
['subDir' => 'layout/override/theme']
);
/** @var $themeCollection \Magento\Theme\Model\Theme\Collection */
$themeCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Theme\Model\Theme\Collection::class
);
/** @var $themeLayouts \Magento\Framework\View\File[] */
$themeLayouts = [];
/** @var $theme \Magento\Framework\View\Design\ThemeInterface */
foreach ($themeCollection as $theme) {
$themeLayouts = array_merge($themeLayouts, $themeUpdates->getFiles($theme, '*.xml'));
$themeLayouts = array_merge($themeLayouts, $themeUpdatesOverride->getFiles($theme, '*.xml'));
}
$result = [];
foreach ($themeLayouts as $layout) {
$result[$layout->getFileIdentifier()] = [$layout];
}
return $result;
}
public function testOverrideBaseFiles()
{
$invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
$invoker(
/**
* Check, that for an overriding file ($themeFile) in a theme ($theme), there is a corresponding base file
*
* @param \Magento\Framework\View\File $themeFile
* @param \Magento\Framework\View\Design\ThemeInterface $theme
*/
function ($themeFile, $theme) {
$baseFiles = self::_getCachedFiles(
$theme->getArea(),
\Magento\Framework\View\File\Collector\Base::class,
$theme
);
$fileKey = $themeFile->getModule() . '/' . $themeFile->getName();
$this->assertArrayHasKey(
$fileKey,
$baseFiles,
sprintf("Could not find base file, overridden by theme file '%s'.", $themeFile->getFilename())
);
},
$this->overrideBaseFilesDataProvider()
);
}
public function testOverrideThemeFiles()
{
$invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
$invoker(
/**
* Check, that for an ancestor-overriding file ($themeFile) in a theme ($theme),
* there is a corresponding file in that ancestor theme
*
* @param \Magento\Framework\View\File $themeFile
* @param \Magento\Framework\View\Design\ThemeInterface $theme
*/
function ($themeFile, $theme) {
// Find an ancestor theme, where a file is to be overridden
$ancestorTheme = $theme;
while ($ancestorTheme = $ancestorTheme->getParentTheme()) {
if ($ancestorTheme == $themeFile->getTheme()) {
break;
}
}
$this->assertNotNull(
$ancestorTheme,
sprintf(
'Could not find ancestor theme "%s", ' .
'its layout file is supposed to be overridden by file "%s".',
$themeFile->getTheme()->getCode(),
$themeFile->getFilename()
)
);
// Search for the overridden file in the ancestor theme
$ancestorFiles = self::_getCachedFiles(
$ancestorTheme->getFullPath(),
\Magento\Framework\View\File\Collector\ThemeModular::class,
$ancestorTheme
);
$fileKey = $themeFile->getModule() . '/' . $themeFile->getName();
$this->assertArrayHasKey(
$fileKey,
$ancestorFiles,
sprintf(
"Could not find original file in '%s' theme, overridden by file '%s'.",
$themeFile->getTheme()->getCode(),
$themeFile->getFilename()
)
);
},
$this->overrideThemeFilesDataProvider()
);
}
/**
* Retrieve list of cached source files
*
* @param string $cacheKey
* @param string $sourceClass
* @param \Magento\Framework\View\Design\ThemeInterface $theme
* @return \Magento\Framework\View\File[]
*/
protected static function _getCachedFiles(
$cacheKey,
$sourceClass,
\Magento\Framework\View\Design\ThemeInterface $theme
) {
if (!isset(self::$_cachedFiles[$cacheKey])) {
/* @var $fileList \Magento\Framework\View\File[] */
$fileList = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create($sourceClass, ['subDir' => 'layout'])->getFiles($theme, '*.xml');
$files = [];
foreach ($fileList as $file) {
$files[$file->getModule() . '/' . $file->getName()] = true;
}
self::$_cachedFiles[$cacheKey] = $files;
}
return self::$_cachedFiles[$cacheKey];
}
/**
* @return array
*/
public function overrideBaseFilesDataProvider()
{
return $this->_retrieveFilesForEveryTheme(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(
\Magento\Framework\View\File\Collector\Override\Base::class,
['subDir' => 'layout/override/base']
)
);
}
/**
* @return array
*/
public function overrideThemeFilesDataProvider()
{
return $this->_retrieveFilesForEveryTheme(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(
\Magento\Framework\View\File\Collector\Override\ThemeModular::class,
['subDir' => 'layout/override/theme']
)
);
}
/**
* Scan all the themes in the system, for each theme retrieve list of files via $filesRetriever,
* and return them as array of pairs [file, theme].
*
* @param \Magento\Framework\View\File\CollectorInterface $filesRetriever
* @return array
*/
protected function _retrieveFilesForEveryTheme(\Magento\Framework\View\File\CollectorInterface $filesRetriever)
{
$result = [];
/** @var $themeCollection \Magento\Theme\Model\Theme\Collection */
$themeCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Theme\Model\Theme\Collection::class
);
/** @var $theme \Magento\Framework\View\Design\ThemeInterface */
foreach ($themeCollection as $theme) {
foreach ($filesRetriever->getFiles($theme, '*.xml') as $file) {
$result['theme: ' . $theme->getFullPath() . ', ' . $file->getFilename()] = [$file, $theme];
}
}
return $result;
}
}
@@ -0,0 +1,157 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Locate all payment methods in the system and verify declaration of their blocks
*/
namespace Magento\Test\Integrity\Magento\Payment;
use Magento\Framework\App\State;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class MethodsTest extends \PHPUnit\Framework\TestCase
{
/**
* @param string $methodClass
* @param string $code
* @dataProvider paymentMethodDataProvider
* @magentoAppArea frontend
* @throws \Exception on various assertion failures
*/
public function testPaymentMethod($code, $methodClass)
{
if (in_array($code, ['free', 'substitution', 'vault', 'payflowpro_cc_vault', 'fake_vault'])) {
return;
}
Bootstrap::getObjectManager()->configure($this->getTestConfiguration());
/** @var $blockFactory \Magento\Framework\View\Element\BlockFactory */
$blockFactory = Bootstrap::getObjectManager()->get(
\Magento\Framework\View\Element\BlockFactory::class
);
$storeId = Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->getId();
/** @var $model \Magento\Payment\Model\MethodInterface */
if (empty($methodClass)) {
/**
* Note that $code is not whatever the payment method getCode() returns
*/
$this->fail("Model of '{$code}' payment method is not found.");
}
$model = Bootstrap::getObjectManager()->create($methodClass);
if ($code == \Magento\Payment\Model\Method\Substitution::CODE) {
$paymentInfo = $this->getMockBuilder(
\Magento\Payment\Model\Info::class
)->disableOriginalConstructor()->setMethods(
[]
)->getMock();
$paymentInfo->expects(
$this->any()
)->method(
'getAdditionalInformation'
)->willReturn(
'Additional data mock'
);
$model->setInfoInstance($paymentInfo);
}
Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class)
->setMode(State::MODE_DEVELOPER);
$this->assertNotEmpty($model->getTitle());
foreach ([$model->getFormBlockType(), $model->getInfoBlockType()] as $blockClass) {
if (is_array($blockClass)) {
$blockClass=$blockClass['instance'] ?? '';
}
$message = "Block class: {$blockClass}";
/** @var $block \Magento\Framework\View\Element\Template */
$block = $blockFactory->createBlock($blockClass);
$block->setArea('frontend');
if ($model->canUseInternal()) {
try {
Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->setId(
\Magento\Store\Model\Store::DEFAULT_STORE_ID
);
$block->setArea('adminhtml');
$this->assertFileExists((string)$block->getTemplateFile(), $message);
Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->setId(
$storeId
);
} catch (\Exception $e) {
Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->setId(
$storeId
);
throw $e;
}
}
}
Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class)
->setMode(State::MODE_DEFAULT);
}
/**
* @return array
*/
public function paymentMethodDataProvider()
{
/** @var $helper \Magento\Payment\Helper\Data */
$helper = Bootstrap::getObjectManager()->get(\Magento\Payment\Helper\Data::class);
$result = [];
foreach ($helper->getPaymentMethods() as $code => $method) {
if (!isset($method['model'])) {
$this->addWarning(
'The `model` node must be provided for payment method configuration with code: ' . $code
);
continue;
}
$result[] = [$code, $method['model']];
}
return $result;
}
/**
* @param string $path
* @return \RegexIterator
*/
private function collectFiles($path)
{
$ds = preg_quote(DIRECTORY_SEPARATOR);
$flags = \FilesystemIterator::CURRENT_AS_FILEINFO
| \FilesystemIterator::SKIP_DOTS;
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, $flags));
return new \RegexIterator(
$iterator,
'#' . $ds . 'etc' . $ds . 'di\.php$#',
\RegexIterator::MATCH,
\RegexIterator::USE_KEY
);
}
/**
* @return array
*/
private function getTestConfiguration()
{
$result = [];
$ds = DIRECTORY_SEPARATOR;
$path = __DIR__ . $ds . str_repeat('..' . $ds, 5) . 'Magento';
foreach ($this->collectFiles($path) as $file) {
$config = include $file->getPathname();
$result = array_replace_recursive($result, $config);
}
return $result;
}
}
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Magento\Widget;
class SkinFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider widgetPlaceholderImagesDataProvider
*/
public function testWidgetPlaceholderImages($skinImage)
{
/** @var \Magento\Framework\View\Asset\Repository $assetRepo */
$assetRepo = \Magento\TestFramework\Helper\Bootstrap::getObjectmanager()
->get(\Magento\Framework\View\Asset\Repository::class);
$this->assertFileExists(
$assetRepo->createAsset($skinImage, ['area' => 'adminhtml'])->getSourceFile()
);
}
/**
* @return array
*/
public function widgetPlaceholderImagesDataProvider()
{
$result = [];
/** @var $model \Magento\Widget\Model\Widget */
$model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Widget\Model\Widget::class
);
foreach ($model->getWidgetsArray() as $row) {
/** @var $instance \Magento\Widget\Model\Widget\Instance */
$instance = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Widget\Model\Widget\Instance::class
);
$config = $instance->setType($row['type'])->getWidgetConfigAsArray();
if (isset($config['placeholder_image'])) {
$result[] = [(string)$config['placeholder_image']];
}
}
return $result;
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Magento\Widget;
/**
* @magentoAppArea frontend
*/
class TemplateFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Check if all the declared widget templates actually exist
*
* @param string $class
* @param string $template
* @dataProvider widgetTemplatesDataProvider
*/
public function testWidgetTemplates($class, $template)
{
/** @var $blockFactory \Magento\Framework\View\Element\BlockFactory */
$blockFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\Element\BlockFactory::class
);
/** @var \Magento\Framework\View\Element\Template $block */
$block = $blockFactory->createBlock($class);
$this->assertInstanceOf(\Magento\Framework\View\Element\Template::class, $block);
$block->setTemplate((string)$template);
$this->assertFileExists($block->getTemplateFile());
}
/**
* Collect all declared widget blocks and templates
*
* @return array
*/
public function widgetTemplatesDataProvider()
{
$result = [];
/** @var $model \Magento\Widget\Model\Widget */
$model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Widget\Model\Widget::class
);
foreach ($model->getWidgetsArray() as $row) {
/** @var $instance \Magento\Widget\Model\Widget\Instance */
$instance = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Widget\Model\Widget\Instance::class
);
$config = $instance->setType($row['type'])->getWidgetConfigAsArray();
$class = $row['type'];
if (is_subclass_of($class, \Magento\Framework\View\Element\Template::class)) {
if (isset(
$config['parameters']
) && isset(
$config['parameters']['template']
) && isset(
$config['parameters']['template']['values']
)
) {
$templates = $config['parameters']['template']['values'];
foreach ($templates as $template) {
if (isset($template['value'])) {
$result[] = [$class, (string)$template['value']];
}
}
}
}
}
return $result;
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
/**
* AbstractMergedConfigTest can be used to test merging of config files
*/
abstract class AbstractMergedConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* attributes represent merging rules
* copied from original namespace Magento\Framework\App\Route\Config;
*
* class Reader
*
* @returns array
*/
abstract protected function getIdAttributes();
/**
* Path to tough XSD for merged file validation
*
* @returns string
*/
abstract protected function getMergedSchemaFile();
/**
* Returns an array of config files to test
*
* @return array
*/
abstract protected function getConfigFiles();
public function testMergedConfigFiles()
{
$invalidFiles = [];
$files = $this->getConfigFiles();
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(false);
$mergedConfig = new \Magento\Framework\Config\Dom(
'<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></config>',
$validationStateMock,
$this->getIdAttributes()
);
foreach ($files as $file) {
$content = file_get_contents($file[0]);
try {
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
new \Magento\Framework\Config\Dom($content, $validationStateMock, $this->getIdAttributes());
//merge won't be performed if file is invalid because of exception thrown
$mergedConfig->merge($content);
} catch (\Magento\Framework\Config\Dom\ValidationException $e) {
$invalidFiles[] = $file[0];
}
}
if (!empty($invalidFiles)) {
$this->fail('Found broken files: ' . implode("\n", $invalidFiles));
}
$errors = [];
$mergedConfig->validate($this->getMergedSchemaFile(), $errors);
if ($errors) {
$this->fail('Merged routes config is invalid: ' . "\n" . implode("\n", $errors));
}
}
}
@@ -0,0 +1,56 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class AclConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Configuration acl file list
*
* @var array
*/
protected $_fileList = [];
/**
* Path to scheme file
*
* @var string
*/
protected $_schemeFile;
protected function setUp(): void
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$this->_schemeFile = $urnResolver->getRealPath('urn:magento:framework:Acl/etc/acl.xsd');
}
/**
* Test each acl configuration file
* @param string $file
* @dataProvider aclConfigFileDataProvider
*/
public function testAclConfigFile($file)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$domConfig = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $domConfig->validate($this->_schemeFile, $errors);
$message = "Invalid XML-file: {$file}\n";
foreach ($errors as $error) {
$message .= "{$error}\n";
}
$this->assertTrue($result, $message);
}
/**
* @return array
*/
public function aclConfigFileDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('acl.xml');
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Customer\Model\Context;
/**
* This test ensures that all blocks have the appropriate constructor arguments that allow
* them to be instantiated via the objectManager.
*
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BlockInstantiationTest extends \Magento\TestFramework\TestCase\AbstractIntegrity
{
public function testBlockInstantiation()
{
$invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
$invoker(
function ($module, $class, $area) {
$this->assertNotEmpty($module);
$this->assertTrue(class_exists($class), "Block class: {$class}");
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Config\ScopeInterface::class
)->setCurrentScope(
$area
);
$context = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\Http\Context::class
);
$context->setValue(Context::CONTEXT_AUTH, false, false);
$context->setValue(
Context::CONTEXT_GROUP,
\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID,
\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID
);
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea($area);
try {
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create($class);
} catch (\Exception $e) {
throw new \Exception("Unable to instantiate '{$class}'", 0, $e);
}
},
$this->allBlocksDataProvider()
);
}
/**
* @return array
*/
public function allBlocksDataProvider()
{
$blockClass = '';
try {
/** @var $website \Magento\Store\Model\Website */
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->setWebsiteId(
0
);
$enabledModules = $this->_getEnabledModules();
$skipBlocks = $this->_getBlocksToSkip();
$templateBlocks = [];
$blockMods = \Magento\Framework\App\Utility\Classes::collectModuleClasses('Block');
foreach ($blockMods as $blockClass => $module) {
if (!isset($enabledModules[$module]) || isset($skipBlocks[$blockClass])) {
continue;
}
$class = new \ReflectionClass($blockClass);
if ($class->isAbstract() || !$class->isSubclassOf(\Magento\Framework\View\Element\Template::class)) {
continue;
}
$templateBlocks = $this->_addBlock($module, $blockClass, $class, $templateBlocks);
}
asort($templateBlocks);
return $templateBlocks;
} catch (\Exception $e) {
trigger_error(
"Corrupted data provider. Last known block instantiation attempt: '{$blockClass}'." .
" Exception: {$e}",
E_USER_ERROR
);
}
}
/**
* Loads block classes, that should not be instantiated during the instantiation test
*
* @return array
*/
protected function _getBlocksToSkip()
{
$result = [];
foreach (glob(__DIR__ . '/_files/skip_blocks*.php') as $file) {
$blocks = include $file;
$result = array_merge($result, $blocks);
}
return array_combine($result, $result);
}
/**
* @param $module
* @param $blockClass
* @param $class
* @param $templateBlocks
* @return mixed
*/
private function _addBlock($module, $blockClass, $class, $templateBlocks)
{
$area = 'frontend';
if ($module == 'Magento_Backend' || strpos(
$blockClass,
'\\Adminhtml\\'
) !== false || strpos(
$blockClass,
'_Backend_'
) !== false || $class->isSubclassOf(
\Magento\Backend\Block\Template::class
)
) {
$area = 'adminhtml';
}
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\AreaList::class
)->getArea(
\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE
)->load(
\Magento\Framework\App\Area::PART_CONFIG
);
$templateBlocks[$module . ', ' . $blockClass . ', ' . $area] = [$module, $blockClass, $area];
return $templateBlocks;
}
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class CacheFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @param string $area
* @dataProvider cacheConfigDataProvider
*/
public function testCacheConfig($area)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\Cache\Config\Reader $reader */
$reader = $objectManager->create(
\Magento\Framework\Cache\Config\Reader::class,
['validationState' => $validationStateMock]
);
try {
$reader->read($area);
} catch (\Magento\Framework\Exception\LocalizedException $exception) {
$this->fail($exception->getMessage());
}
}
public function cacheConfigDataProvider()
{
return ['global' => ['global'], 'adminhtml' => ['adminhtml'], 'frontend' => ['frontend']];
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Test configuration of Online Shipping carriers
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Module\Dir;
class CarrierConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Config\Model\Config\Structure\Reader
*/
protected $_reader;
protected function setUp(): void
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$schemaFile = $urnResolver->getRealPath('urn:magento:module:Magento_Config:etc/system.xsd');
$this->_reader = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Config\Model\Config\Structure\Reader::class,
['perFileSchema' => $schemaFile, 'isValidated' => true]
);
}
/**
* Tests that all source_models used in shipping are valid
*/
public function testValidateShippingSourceModels()
{
$config = $this->_reader->read('adminhtml');
$carriers = $config['config']['system']['sections']['carriers']['children'];
foreach ($carriers as $carrier) {
foreach ($carrier['children'] as $field) {
if (isset($field['source_model'])) {
$model = $field['source_model'];
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create($model);
}
}
}
}
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class CrontabConfigFilesTest extends AbstractMergedConfigTest
{
/**
* attributes represent merging rules
* copied from original class \Magento\Framework\App\Route\Config\Reader
*
* @var array
*/
protected function getIdAttributes()
{
return ['/config/group' => 'id', '/config/group/job' => 'name'];
}
/**
* Path to tough XSD for merged file validation
*
* @var string
*/
protected function getMergedSchemaFile()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
return $objectManager->get(\Magento\Cron\Model\Config\SchemaLocator::class)->getSchema();
}
protected function getConfigFiles()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('crontab.xml');
}
}
@@ -0,0 +1,163 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\App\Filesystem\DirectoryList;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class DiConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Primary DI configs from app/etc
* @var array
*/
protected static $_primaryFiles = [];
/**
* Global DI configs from all modules
* @var array
*/
protected static $_moduleGlobalFiles = [];
/**
* Area DI configs from all modules
* @var array
*/
protected static $_moduleAreaFiles = [];
protected function _prepareFiles()
{
//init primary configs
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $filesystem \Magento\Framework\Filesystem */
$filesystem = $objectManager->get(\Magento\Framework\Filesystem::class);
$configDirectory = $filesystem->getDirectoryRead(DirectoryList::CONFIG);
$fileIteratorFactory = $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class);
$search = [];
foreach ($configDirectory->search('{*/di.xml,di.xml}') as $path) {
$search[] = $configDirectory->getAbsolutePath($path);
}
self::$_primaryFiles = $fileIteratorFactory->create($search);
//init module global configs
/** @var $modulesReader \Magento\Framework\Module\Dir\Reader */
$modulesReader = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Module\Dir\Reader::class);
self::$_moduleGlobalFiles = $modulesReader->getConfigurationFiles('di.xml');
//init module area configs
$areas = ['adminhtml', 'frontend'];
foreach ($areas as $area) {
$moduleAreaFiles = $modulesReader->getConfigurationFiles($area . '/di.xml');
self::$_moduleAreaFiles[$area] = $moduleAreaFiles;
}
}
/**
* @param string $filePath
* @param string $xml
* @throws \Exception
* @dataProvider linearFilesProvider
*/
public function testDiConfigFileWithoutMerging($filePath, $xml)
{
/** @var \Magento\Framework\ObjectManager\Config\SchemaLocator $schemaLocator */
$schemaLocator = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\ObjectManager\Config\SchemaLocator::class
);
$dom = new \DOMDocument();
$dom->loadXML($xml);
libxml_use_internal_errors(true);
$result = \Magento\Framework\Config\Dom::validateDomDocument($dom, $schemaLocator->getSchema());
libxml_use_internal_errors(false);
if (!empty($result)) {
$this->fail(
'File ' . $filePath . ' has invalid xml structure. '
. implode("\n", $result)
);
}
}
public function linearFilesProvider()
{
if (empty(self::$_primaryFiles)) {
$this->_prepareFiles();
}
$common = array_merge(self::$_primaryFiles->toArray(), self::$_moduleGlobalFiles->toArray());
foreach (self::$_moduleAreaFiles as $files) {
$common = array_merge($common, $files->toArray());
}
$output = [];
foreach ($common as $path => $content) {
$output[] = [substr($path, strlen(BP)), $content];
}
return $output;
}
/**
* @param array $files
* @dataProvider mixedFilesProvider
*/
public function testMergedDiConfig(array $files)
{
$mapperMock = $this->createMock(\Magento\Framework\ObjectManager\Config\Mapper\Dom::class);
$fileResolverMock = $this->getMockBuilder(\Magento\Framework\Config\FileResolverInterface::class)
->setMethods(['read'])
->getMockForAbstractClass();
$fileResolverMock->expects($this->any())->method('read')->willReturn($files);
$validationStateMock = $this->createPartialMock(
\Magento\Framework\Config\ValidationStateInterface::class,
['isValidationRequired']
);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
/** @var \Magento\Framework\ObjectManager\Config\SchemaLocator $schemaLocator */
$schemaLocator = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\ObjectManager\Config\SchemaLocator::class
);
new \Magento\Framework\ObjectManager\Config\Reader\Dom(
$fileResolverMock,
$mapperMock,
$schemaLocator,
$validationStateMock
);
}
public function mixedFilesProvider()
{
if (empty(self::$_primaryFiles)) {
$this->_prepareFiles();
}
foreach (self::$_primaryFiles->toArray() as $file) {
$primaryFiles[] = [[$file]];
}
$primaryFiles['all primary config files'] = [self::$_primaryFiles->toArray()];
foreach (self::$_moduleGlobalFiles->toArray() as $file) {
$moduleFiles[] = [[$file]];
}
$moduleFiles['all module global config files'] = [self::$_moduleGlobalFiles->toArray()];
$areaFiles = [];
foreach (self::$_moduleAreaFiles as $area => $files) {
foreach ($files->toArray() as $file) {
$areaFiles[] = [[$file]];
}
$areaFiles["all {$area} config files"] = [self::$_moduleAreaFiles[$area]->toArray()];
}
return $primaryFiles + $moduleFiles + $areaFiles;
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class EavAttributesConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Eav\Model\Entity\Attribute\Config\Reader
*/
protected $_model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
$fileIteratorFactory = $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class);
$xmlFiles = $fileIteratorFactory->create(
$moduleDirSearch->collectFiles(ComponentRegistrar::MODULE, 'etc/{*/eav_attributes.xml,eav_attributes.xml}')
);
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolverMock->expects($this->any())->method('get')->willReturn($xmlFiles);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $objectManager->create(
\Magento\Eav\Model\Entity\Attribute\Config\Reader::class,
['fileResolver' => $fileResolverMock, 'validationState' => $validationStateMock]
);
}
public function testImportXmlFiles()
{
$this->_model->read('global');
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class EventConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
protected $_schemaFile;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_schemaFile = $objectManager->get(\Magento\Framework\Event\Config\SchemaLocator::class)->getSchema();
}
/**
* @param string $file
* @dataProvider eventConfigFilesDataProvider
*/
public function testEventConfigFiles($file)
{
$errors = [];
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$dom = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $dom->validate($this->_schemaFile, $errors);
$message = "Invalid XML-file: {$file}\n";
foreach ($errors as $error) {
$message .= "{$error->message} Line: {$error->line}\n";
}
$this->assertTrue($result, $message);
}
/**
* @return array
*/
public function eventConfigFilesDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('{*/events.xml,events.xml}');
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class ExportConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\ImportExport\Model\Export\Config\Reader
*/
protected $_model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
$fileIteratorFactory = $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class);
$xmlFiles = $fileIteratorFactory->create(
$moduleDirSearch->collectFiles(ComponentRegistrar::MODULE, 'etc/{*/export.xml,export.xml}')
);
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolverMock->expects($this->any())->method('get')->willReturn($xmlFiles);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $objectManager->create(
\Magento\ImportExport\Model\Export\Config\Reader::class,
['fileResolver' => $fileResolverMock, 'validationState' => $validationStateMock]
);
}
public function testExportXmlFiles()
{
$this->_model->read('global');
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Tests that existing fieldset.xml files are valid to schema individually and merged.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class FieldsetConfigFilesTest extends \Magento\TestFramework\TestCase\AbstractConfigFiles
{
/**
* Returns the reader class name that will be instantiated via ObjectManager
*
* @return string reader class name
*/
protected function _getReaderClassName()
{
return \Magento\Framework\DataObject\Copy\Config\Reader::class;
}
/**
* Returns a string that represents the path to the config file
*
* @return string
*/
protected function _getConfigFilePathGlob()
{
return 'etc/fieldset.xml';
}
/**
* Returns an absolute path to the XSD file corresponding to the XML files specified in _getConfigFilePathGlob
*
* @return string
*/
protected function _getXsdPath()
{
return $this->componentRegistrar->getPath(ComponentRegistrar::LIBRARY, 'magento/framework')
. '/DataObject/etc/fieldset_file.xsd';
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class ImportConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\ImportExport\Model\Import\Config\Reader
*/
protected $_model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
$fileIteratorFactory = $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class);
$xmlFiles = $fileIteratorFactory->create(
$moduleDirSearch->collectFiles(ComponentRegistrar::MODULE, 'etc/{*/import.xml,import.xml}')
);
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolverMock->expects($this->any())->method('get')->willReturn($xmlFiles);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $objectManager->create(
\Magento\ImportExport\Model\Import\Config\Reader::class,
['fileResolver' => $fileResolverMock, 'validationState' => $validationStateMock]
);
}
public function testImportXmlFiles()
{
$this->_model->read('global');
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Filesystem;
class IndexerConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Configuration acl file list
*
* @var array
*/
protected $fileList = [];
/**
* Path to scheme file
*
* @var string
*/
protected $schemaFile;
protected function setUp(): void
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$this->schemaFile = $urnResolver->getRealPath('urn:magento:framework:Indexer/etc/indexer.xsd');
}
/**
* Test each acl configuration file
* @param string $file
* @dataProvider indexerConfigFileDataProvider
*/
public function testIndexerConfigFile($file)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$domConfig = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $domConfig->validate($this->schemaFile, $errors);
$message = "Invalid XML-file: {$file}\n";
foreach ($errors as $error) {
$message .= "{$error}\n";
}
$this->assertTrue($result, $message);
}
/**
* @return array
*/
public function indexerConfigFileDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('indexer.xml');
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class LayoutConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Path to schema file
*
* @var string
*/
protected $schemaFile;
protected function setUp(): void
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$this->schemaFile = $urnResolver->getRealPath('urn:magento:framework:View/Layout/etc/elements.xsd');
}
/**
* Test a valid layout XML file
*/
public function testValidLayoutXmlFile()
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')->willReturn(true);
$domConfig = new \Magento\Framework\Config\Dom(
'<referenceBlock name="product.info.something" group="column_left"></referenceBlock>',
$validationStateMock
);
$result = $domConfig->validate($this->schemaFile, $errors);
$this->assertTrue($result);
$this->assertEmpty($errors);
}
/**
* Test a layout XML file having an invalid tag element
*/
public function testBrokenLayoutXmlFile()
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')->willReturn(true);
$domConfig = new \Magento\Framework\Config\Dom(
'<invalidElement name="some.name"></invalidElement>',
$validationStateMock
);
$result = $domConfig->validate($this->schemaFile, $errors);
$this->assertFalse($result);
$this->assertNotEmpty($errors);
}
}
@@ -0,0 +1,110 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class LayoutFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\View\Layout\Argument\Parser
*/
protected $_argParser;
/**
* @var \Magento\Framework\Data\Argument\InterpreterInterface
*/
protected $_argInterpreter;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_argParser = $objectManager->get(\Magento\Framework\View\Layout\Argument\Parser::class);
$this->_argInterpreter = $objectManager->get('layoutArgumentGeneratorInterpreter');
}
/**
* @param string $area
* @param string $layoutFile
* @dataProvider layoutArgumentsDataProvider
*/
public function testLayoutArguments($area, $layoutFile)
{
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea($area);
$dom = new \DOMDocument();
$dom->load($layoutFile);
$xpath = new \DOMXPath($dom);
$argumentNodes = $xpath->query('/layout//arguments/argument | /layout//action/argument');
/** @var \DOMNode $argumentNode */
foreach ($argumentNodes as $argumentNode) {
try {
$argumentData = $this->_argParser->parse($argumentNode);
if ($this->isSkippedArgument($argumentData)) {
continue;
}
$this->_argInterpreter->evaluate($argumentData);
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
}
}
/**
* @return array
*/
public function layoutArgumentsDataProvider()
{
$areas = ['adminhtml', 'frontend', 'email'];
$data = [];
foreach ($areas as $area) {
$layoutFiles = \Magento\Framework\App\Utility\Files::init()->getLayoutFiles(['area' => $area], false);
foreach ($layoutFiles as $layoutFile) {
$data[substr($layoutFile, strlen(BP))] = [$area, $layoutFile];
}
}
return $data;
}
/**
* Whether an argument should be skipped, because it cannot be evaluated in the testing environment
*
* @param array $argumentData
* @return bool
*/
protected function isSkippedArgument(array $argumentData)
{
// Do not take into account argument name, shared and parameters
unset($argumentData['name'], $argumentData['param'], $argumentData['shared']);
$isUpdater = isset($argumentData['updater']);
unset($argumentData['updater']);
// Arguments, evaluation of which causes a run-time error, because of unsafe assumptions to the environment
$typeAttr = \Magento\Framework\View\Model\Layout\Merge::TYPE_ATTRIBUTE;
$prCollection =
\Magento\GroupedProduct\Model\ResourceModel\Product\Type\Grouped\AssociatedProductsCollection::class;
$ignoredArguments = [
[
$typeAttr => 'object',
'value' => $prCollection,
],
[$typeAttr => 'object', 'value' => \Magento\Wishlist\Model\ResourceModel\Item\Collection\Grid::class],
[
$typeAttr => 'object',
'value' => \Magento\CustomerSegment\Model\ResourceModel\Segment\Report\Detail\Collection::class
],
[$typeAttr => 'options', 'model' => \Magento\Logging\Model\ResourceModel\Grid\ActionsGroup::class],
[$typeAttr => 'options', 'model' => \Magento\Logging\Model\ResourceModel\Grid\Actions::class],
];
$isIgnoredArgument = in_array($argumentData, $ignoredArguments, true);
unset($argumentData[$typeAttr]);
$hasValue = !empty($argumentData);
return $isIgnoredArgument || $isUpdater && !$hasValue;
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular\Magento\Catalog;
class AttributeConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
protected $_schemaFile;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Catalog\Model\Attribute\Config\SchemaLocator $schemaLocator */
$schemaLocator = $objectManager->get(\Magento\Catalog\Model\Attribute\Config\SchemaLocator::class);
$this->_schemaFile = $schemaLocator->getSchema();
}
/**
* @param string $file
* @dataProvider fileFormatDataProvider
*/
public function testFileFormat($file)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$dom = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $dom->validate($this->_schemaFile, $errors);
$this->assertTrue($result, print_r($errors, true));
}
/**
* @return array
*/
public function fileFormatDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('catalog_attributes.xml');
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular\Magento\Customer;
class AddressFormatsFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
protected $_schemaFile;
protected function setUp(): void
{
/** @var \Magento\Customer\Model\Address\Config\SchemaLocator $schemaLocator */
$schemaLocator = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Customer\Model\Address\Config\SchemaLocator::class
);
$this->_schemaFile = $schemaLocator->getSchema();
}
/**
* @param string $file
* @dataProvider fileFormatDataProvider
*/
public function testFileFormat($file)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$dom = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $dom->validate($this->_schemaFile, $errors);
$this->assertTrue($result, print_r($errors, true));
}
/**
* @return array
*/
public function fileFormatDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles(
'{*/address_formats.xml,address_formats.xml}'
);
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular\Magento\Email;
class EmailTemplateConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Test that email template configuration file matches the format
*
* @param string $file
* @dataProvider fileFormatDataProvider
*/
public function testFileFormat($file)
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$schemaFile = $urnResolver->getRealPath('urn:magento:module:Magento_Email:etc/email_templates.xsd');
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$dom = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $dom->validate($schemaFile, $errors);
$this->assertTrue($result, print_r($errors, true));
}
/**
* @return array
*/
public function fileFormatDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('email_templates.xml');
}
/**
* Test that email template configuration contains references to existing template files
*
* @param string $templateId
* @dataProvider templateReferenceDataProvider
*/
public function testTemplateReference($templateId)
{
/** @var \Magento\Email\Model\Template\Config $emailConfig */
$emailConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Email\Model\Template\Config::class
);
$parts = $emailConfig->parseTemplateIdParts($templateId);
$templateId = $parts['templateId'];
$designParams = [];
$theme = $parts['theme'];
if ($theme) {
$designParams['theme'] = $theme;
}
$templateFilename = $emailConfig->getTemplateFilename($templateId, $designParams);
$this->assertFileExists($templateFilename, 'Email template file, specified in the configuration, must exist');
}
/**
* @return array
*/
public function templateReferenceDataProvider()
{
$data = [];
/** @var \Magento\Email\Model\Template\Config $emailConfig */
$emailConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Email\Model\Template\Config::class
);
foreach ($emailConfig->getAvailableTemplates() as $template) {
$data[$template['value']] = [$template['value']];
}
return $data;
}
/**
* Test that merged configuration of email templates matches the format
*/
public function testMergedFormat()
{
$validationState = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationState->expects($this->any())->method('isValidationRequired')->willReturn(true);
/** @var \Magento\Email\Model\Template\Config\Reader $reader */
$reader = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Email\Model\Template\Config\Reader::class,
['validationState' => $validationState]
);
try {
$reader->read();
} catch (\Exception $e) {
$this->fail('Merged email templates configuration does not pass XSD validation: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular\Magento\Sales;
class PdfConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @param string $file
* @dataProvider fileFormatDataProvider
*/
public function testFileFormat($file)
{
/** @var \Magento\Sales\Model\Order\Pdf\Config\SchemaLocator $schemaLocator */
$schemaLocator = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Sales\Model\Order\Pdf\Config\SchemaLocator::class
);
$schemaFile = $schemaLocator->getPerFileSchema();
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$dom = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $dom->validate($schemaFile, $errors);
$this->assertTrue($result, print_r($errors, true));
}
/**
* @return array
*/
public function fileFormatDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('pdf.xml');
}
public function testMergedFormat()
{
$validationState = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationState->expects($this->any())->method('isValidationRequired')->willReturn(true);
/** @var \Magento\Sales\Model\Order\Pdf\Config\Reader $reader */
$reader = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Sales\Model\Order\Pdf\Config\Reader::class,
['validationState' => $validationState]
);
try {
$reader->read();
} catch (\Exception $e) {
$this->fail('Merged pdf.xml files do not pass XSD validation: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Module\Dir;
class MenuConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Model\Menu\Config\Reader
*/
protected $_model;
protected function setUp(): void
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$schemaFile = $urnResolver->getRealPath('urn:magento:module:Magento_Backend:etc/menu.xsd');
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Backend\Model\Menu\Config\Reader::class,
['perFileSchema' => $schemaFile, 'isValidated' => true]
);
}
public function testValidateMenuFiles()
{
$this->_model->read('adminhtml');
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\App\Filesystem\DirectoryList;
class MviewConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* Configuration acl file list
*
* @var array
*/
protected $fileList = [];
/**
* Path to scheme file
*
* @var string
*/
protected $schemaFile;
protected function setUp(): void
{
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$this->schemaFile = $urnResolver->getRealPath('urn:magento:framework:Mview/etc/mview.xsd');
}
/**
* Test each acl configuration file
* @param string $file
* @dataProvider mviewConfigFileDataProvider
*/
public function testIndexerConfigFile($file)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$domConfig = new \Magento\Framework\Config\Dom(file_get_contents($file), $validationStateMock);
$result = $domConfig->validate($this->schemaFile, $errors);
$message = "Invalid XML-file: {$file}\n";
foreach ($errors as $error) {
$message .= "{$error}\n";
}
$this->assertTrue($result, $message);
}
/**
* @return array
*/
public function mviewConfigFileDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('mview.xml');
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Tests that existing payment.xml files are valid to schema individually and merged.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class PaymentConfigFilesTest extends \Magento\TestFramework\TestCase\AbstractConfigFiles
{
/**
* Returns the reader class name that will be instantiated via ObjectManager
*
* @return string reader class name
*/
protected function _getReaderClassName()
{
return \Magento\Payment\Model\Config\Reader::class;
}
/**
* Returns a string that represents the path to the config file
*
* @return string
*/
protected function _getConfigFilePathGlob()
{
return 'etc/payment.xml';
}
/**
* Returns an absolute path to the XSD file corresponding to the XML files specified in _getConfigFilePathGlob
*
* @return string
*/
protected function _getXsdPath()
{
return $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Magento_Payment')
. '/etc/payment_file.xsd';
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class ProductOptionsConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Model\ProductOptions\Config\Reader
*/
protected $_model;
protected function setUp(): void
{
//init primary configs
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
$fileIteratorFactory = $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class);
$xmlFiles = $fileIteratorFactory->create(
$moduleDirSearch->collectFiles(
ComponentRegistrar::MODULE,
'etc/{*/product_options.xml,product_options.xml}'
)
);
$fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolverMock->expects($this->any())->method('get')->willReturn($xmlFiles);
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $objectManager->create(
\Magento\Catalog\Model\ProductOptions\Config\Reader::class,
['fileResolver' => $fileResolverMock, 'validationState' => $validationStateMock]
);
}
public function testProductOptionsXmlFiles()
{
$this->_model->read('global');
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class ProductTypesConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Model\ProductTypes\Config\Reader
*/
protected $_model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
$fileIteratorFactory = $objectManager->get(\Magento\Framework\Config\FileIteratorFactory::class);
$xmlFiles = $fileIteratorFactory->create(
$moduleDirSearch->collectFiles(ComponentRegistrar::MODULE, 'etc/{*/product_types.xml,product_types.xml}')
);
$fileResolverMock = $this->createMock(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolverMock->expects($this->any())->method('get')->willReturn($xmlFiles);
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $objectManager->create(
\Magento\Catalog\Model\ProductTypes\Config\Reader::class,
['fileResolver' => $fileResolverMock, 'validationState' => $validationStateMock]
);
}
public function testProductTypesXmlFiles()
{
$this->_model->read('global');
}
}
@@ -0,0 +1,68 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\ResourceConnection\Config\Reader;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Component\DirSearch;
use Magento\Framework\Config\FileIteratorFactory;
use Magento\Framework\Config\FileResolverInterface;
use Magento\Framework\Config\ValidationStateInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class ResourcesConfigFilesTest extends TestCase
{
/**
* @var Reader
*/
protected $model;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var $moduleDirSearch DirSearch */
$moduleDirSearch = $objectManager->get(DirSearch::class);
$fileIteratorFactory = $objectManager->get(FileIteratorFactory::class);
$xmlFiles = $fileIteratorFactory->create(
$moduleDirSearch->collectFiles(ComponentRegistrar::MODULE, 'etc/{*/resources.xml,resources.xml}')
);
$fileResolverMock = $this->createMock(FileResolverInterface::class);
$fileResolverMock->expects($this->any())->method('get')->willReturn($xmlFiles);
$validationStateMock = $this->createMock(ValidationStateInterface::class);
$validationStateMock->expects($this->any())->method('isValidationRequired')->willReturn(true);
$deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->addMethods(['getConfiguration'])
->getMock();
$deploymentConfigMock->expects($this->any())->method('getConfiguration')->willReturn([]);
$objectManager = Bootstrap::getObjectManager();
$this->model = $objectManager->create(
Reader::class,
[
'fileResolver' => $fileResolverMock,
'validationState' => $validationStateMock,
'deploymentConfig' => $deploymentConfigMock
]
);
}
public function testResourcesXmlFiles()
{
$this->model->read('global');
}
}
@@ -0,0 +1,98 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class RouteConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Config\ValidationStateInterface
*/
protected $validationStateMock;
/**
* attributes represent merging rules
* copied from original class \Magento\Framework\App\Route\Config\Reader
* @var array
*/
protected $_idAttributes = [
'/config/routers' => 'id',
'/config/routers/route' => 'id',
'/config/routers/route/module' => 'name',
];
/**
* Path to loose XSD for per file validation
*
* @var string
*/
protected $schemaFile;
/**
* Path to tough XSD for merged file validation
*
* @var string
*/
protected $mergedSchemaFile;
protected function setUp(): void
{
$this->validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$this->validationStateMock->method('isValidationRequired')
->willReturn(true);
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$this->schemaFile = $urnResolver->getRealPath('urn:magento:framework:App/etc/routes.xsd');
$this->mergedSchemaFile = $urnResolver->getRealPath('urn:magento:framework:App/etc/routes_merged.xsd');
}
public function testRouteConfigsValidation()
{
$invalidFiles = [];
$componentRegistrar = new ComponentRegistrar();
$files = [];
foreach ($componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $moduleDir) {
$mask = $moduleDir . '/etc/*/routes.xml';
$files = array_merge($files, glob($mask));
}
$mergedConfig = new \Magento\Framework\Config\Dom(
'<config><router/></config>',
$this->validationStateMock,
$this->_idAttributes
);
foreach ($files as $file) {
$content = file_get_contents($file);
try {
new \Magento\Framework\Config\Dom(
$content,
$this->validationStateMock,
$this->_idAttributes,
null,
$this->schemaFile
);
//merge won't be performed if file is invalid because of exception thrown
$mergedConfig->merge($content);
} catch (\Magento\Framework\Config\Dom\ValidationException $e) {
$invalidFiles[] = $file;
}
}
if (!empty($invalidFiles)) {
$this->fail('Found broken files: ' . implode("\n", $invalidFiles));
}
try {
$errors = [];
$mergedConfig->validate($this->mergedSchemaFile, $errors);
} catch (\Exception $e) {
$this->fail('Merged routes config is invalid: ' . "\n" . implode("\n", $errors));
}
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class SalesConfigFilesTest extends AbstractMergedConfigTest
{
/**
* attributes represent merging rules
* copied from original namespace Magento\Framework\App\Route\Config;
*
* class Reader
*
* @var array
*/
protected function getIdAttributes()
{
return [
'/config/section' => 'name',
'/config/section/group' => 'name',
'/config/section/group/item' => 'name',
'/config/section/group/item/renderer' => 'name',
'/config/order/available_product_type' => 'name',
];
}
/**
* Path to tough XSD for merged file validation
*
* @var string
*/
protected function getMergedSchemaFile()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
return $objectManager->get(\Magento\Sales\Model\Config\SchemaLocator::class)->getSchema();
}
protected function getConfigFiles()
{
return \Magento\Framework\App\Utility\Files::init()->getConfigFiles('sales.xml');
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Component\ComponentRegistrar;
class SystemConfigFilesTest extends \PHPUnit\Framework\TestCase
{
public function testConfiguration()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
// disable config caching to not pollute it
/** @var $cacheState \Magento\Framework\App\Cache\StateInterface */
$cacheState = $objectManager->get(\Magento\Framework\App\Cache\StateInterface::class);
$cacheState->setEnabled(\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER, false);
/** @var \Magento\Framework\Filesystem $filesystem */
$filesystem = $objectManager->get(\Magento\Framework\Filesystem::class);
$modulesDir = $filesystem->getDirectoryRead(DirectoryList::ROOT);
/** @var $moduleDirSearch \Magento\Framework\Component\DirSearch */
$moduleDirSearch = $objectManager->get(\Magento\Framework\Component\DirSearch::class);
$fileList = $moduleDirSearch
->collectFiles(ComponentRegistrar::MODULE, 'etc/adminhtml/system.xml');
$configMock = $this->createPartialMock(
\Magento\Framework\Module\Dir\Reader::class,
['getConfigurationFiles', 'getModuleDir']
);
$configMock->expects($this->any())->method('getConfigurationFiles')->willReturn($fileList);
$configMock->expects(
$this->any()
)->method(
'getModuleDir'
)->with(
'etc',
'Magento_Backend'
)->willReturn(
$modulesDir->getAbsolutePath() . '/app/code/Magento/Backend/etc'
);
try {
$objectManager->create(
\Magento\Config\Model\Config\Structure\Reader::class,
['moduleReader' => $configMock, 'runtimeValidation' => true]
);
} catch (\Magento\Framework\Exception\LocalizedException $exp) {
$this->fail($exp->getMessage());
}
}
}
@@ -0,0 +1,144 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Customer\Model\Context;
/**
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class TemplateFilesTest extends \Magento\TestFramework\TestCase\AbstractIntegrity
{
public function testAllTemplates()
{
$invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
$invoker(
function ($module, $template, $class, $area) {
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\DesignInterface::class
)->setDefaultDesignTheme();
// intentionally to make sure the module files will be requested
$params = [
'area' => $area,
'themeModel' => \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\View\Design\ThemeInterface::class
),
'module' => $module,
];
$file = \Magento\TestFramework\Helper\Bootstrap::getObjectmanager()->get(
\Magento\Framework\View\FileSystem::class
)->getTemplateFileName(
$template,
$params
);
$this->assertIsString($file, "Block class: {$class} {$template}");
$this->assertFileExists($file, "Block class: {$class}");
},
$this->allTemplatesDataProvider()
);
}
/**
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function allTemplatesDataProvider()
{
$blockClass = '';
try {
/** @var $website \Magento\Store\Model\Website */
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)->getStore()->setWebsiteId(
0
);
$templates = [];
$skippedBlocks = $this->_getBlocksToSkip();
foreach (\Magento\Framework\App\Utility\Classes::collectModuleClasses('Block') as $blockClass => $module) {
if (!in_array($module, $this->_getEnabledModules()) || in_array($blockClass, $skippedBlocks)) {
continue;
}
$class = new \ReflectionClass($blockClass);
if ($class->isAbstract() || !$class->isSubclassOf(\Magento\Framework\View\Element\Template::class)) {
continue;
}
$area = 'frontend';
if ($module == 'Magento_Backend' || strpos(
$blockClass,
'\\Adminhtml\\'
) !== false || strpos(
$blockClass,
'\\Backend\\'
) !== false || $class->isSubclassOf(
\Magento\Backend\Block\Template::class
)
) {
$area = 'adminhtml';
}
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\AreaList::class
)->getArea(
$area
)->load(
\Magento\Framework\App\Area::PART_CONFIG
);
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Config\ScopeInterface::class
)->setCurrentScope(
$area
);
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\State::class
)->setAreaCode(
$area
);
$context = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\Http\Context::class
);
$context->setValue(Context::CONTEXT_AUTH, false, false);
$context->setValue(
Context::CONTEXT_GROUP,
\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID,
\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID
);
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create($blockClass);
$template = $block->getTemplate();
if ($template) {
$templates[$module . ', ' . $template . ', ' . $blockClass . ', ' . $area] = [
$module,
$template,
$blockClass,
$area,
];
}
}
return $templates;
} catch (\Exception $e) {
trigger_error(
"Corrupted data provider. Last known block instantiation attempt: '{$blockClass}'." .
" Exception: {$e}",
E_USER_ERROR
);
}
}
/**
* @return array
*/
protected function _getBlocksToSkip()
{
$result = [];
foreach (glob(__DIR__ . '/_files/skip_template_blocks*.php') as $file) {
$blocks = include $file;
$result = array_merge($result, $blocks);
}
return array_combine($result, $result);
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Tests that existing page_layouts.xml files are valid to schema individually and merged.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class ThemeConfigFilesTest extends \Magento\TestFramework\TestCase\AbstractConfigFiles
{
/**
* Returns the reader class name that will be instantiated via ObjectManager
*
* @return string reader class name
*/
protected function _getReaderClassName()
{
return \Magento\Theme\Model\Layout\Config\Reader::class;
}
/**
* Returns a string that represents the path to the config file
*
* @return string
*/
protected function _getConfigFilePathGlob()
{
return 'view/*/layouts.xml';
}
/**
* Returns an absolute path to the XSD file corresponding to the XML files specified in _getConfigFilePathGlob
*
* @return string
*/
protected function _getXsdPath()
{
return $this->componentRegistrar->getPath(ComponentRegistrar::LIBRARY, 'magento/framework')
. '/View/PageLayout/etc/layouts.xsd';
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class ViewConfigFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @param string $file
* @dataProvider viewConfigFileDataProvider
*/
public function testViewConfigFile($file)
{
$validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$validationStateMock->method('isValidationRequired')
->willReturn(true);
$domConfig = new \Magento\Framework\Config\Dom($file, $validationStateMock);
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$result = $domConfig->validate(
$urnResolver->getRealPath('urn:magento:framework:Config/etc/view.xsd'),
$errors
);
$message = "Invalid XML-file: {$file}\n";
foreach ($errors as $error) {
$message .= "{$error->message} Line: {$error->line}\n";
}
$this->assertTrue($result, $message);
}
/**
* @return array
*/
public function viewConfigFileDataProvider()
{
$result = [];
$files = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Module\Dir\Reader::class
)->getConfigurationFiles(
'view.xml'
);
foreach ($files as $file) {
$result[] = [$file];
}
return $result;
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Tests that existing widget.xml files are valid to schema individually and merged.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
use Magento\Framework\Component\ComponentRegistrar;
class WidgetConfigFilesTest extends \Magento\TestFramework\TestCase\AbstractConfigFiles
{
/**
* Returns the reader class name that will be instantiated via ObjectManager
*
* @return string reader class name
*/
protected function _getReaderClassName()
{
return \Magento\Widget\Model\Config\Reader::class;
}
/**
* Returns a string that represents the path to the config file
*
* @return string
*/
protected function _getConfigFilePathGlob()
{
return 'etc/widget.xml';
}
/**
* Returns an absolute path to the XSD file corresponding to the XML files specified in _getConfigFilePathGlob
*
* @return string
*/
protected function _getXsdPath()
{
return $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Magento_Widget')
. '/etc/widget_file.xsd';
}
}
@@ -0,0 +1,23 @@
<?php
/**
* List of blocks to be skipped from instantiation test
*
* Format: array('Block_Class_Name', ...)
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
// Blocks with abstract constructor arguments
\Magento\Email\Block\Adminhtml\Template::class,
\Magento\Email\Block\Adminhtml\Template\Edit::class,
\Magento\Config\Block\System\Config\Edit::class,
\Magento\Config\Block\System\Config\Form::class,
\Magento\Config\Block\System\Config\Tabs::class,
\Magento\Review\Block\Form::class,
// Fails because of dependence on registry
\Magento\Reminder\Block\Adminhtml\Reminder\Edit\Tab\Customers::class,
\Magento\LayeredNavigation\Block\Navigation::class,
\Magento\LayeredNavigation\Block\Navigation\State::class,
\Magento\Paypal\Block\Express\InContext\Minicart\Button::class,
];
@@ -0,0 +1,16 @@
<?php
/**
* List of blocks to be skipped from template files test
*
* Format: array('Block_Class_Name', ...)
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
// Fails because of dependence on registry
\Magento\Reminder\Block\Adminhtml\Reminder\Edit\Tab\Customers::class,
\Magento\LayeredNavigation\Block\Navigation::class,
\Magento\LayeredNavigation\Block\Navigation\State::class,
\Magento\Paypal\Block\Express\InContext\Minicart\Button::class,
];
@@ -0,0 +1,340 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity;
use Magento\Framework\App\Filesystem\DirectoryList;
/**
* An integrity test that searches for references to static files and asserts that they are resolved via fallback
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class StaticFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\View\Design\FileResolution\Fallback\StaticFile
*/
private $fallback;
/**
* @var \Magento\Framework\View\Design\FileResolution\Fallback\Resolver\Simple
*/
private $explicitFallback;
/**
* @var \Magento\Framework\View\Design\Theme\FlyweightFactory
*/
private $themeRepo;
/**
* @var \Magento\Framework\View\DesignInterface
*/
private $design;
/**
* @var \Magento\Framework\View\Design\ThemeInterface
*/
private $baseTheme;
/**
* @var \Magento\Framework\View\Design\FileResolution\Fallback\Resolver\Alternative
*/
private $alternativeResolver;
/**
* Factory for simple rule
*
* @var \Magento\Framework\View\Design\Fallback\Rule\SimpleFactory
*/
private $simpleFactory;
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
protected function setUp(): void
{
$om = \Magento\TestFramework\Helper\Bootstrap::getObjectmanager();
$this->fallback = $om->get(\Magento\Framework\View\Design\FileResolution\Fallback\StaticFile::class);
$this->explicitFallback = $om->get(
\Magento\Framework\View\Design\FileResolution\Fallback\Resolver\Simple::class
);
$this->themeRepo = $om->get(\Magento\Framework\View\Design\Theme\FlyweightFactory::class);
$this->design = $om->get(\Magento\Framework\View\DesignInterface::class);
$this->baseTheme = $om->get(\Magento\Framework\View\Design\ThemeInterface::class);
$this->alternativeResolver = $om->get(
\Magento\Framework\View\Design\FileResolution\Fallback\Resolver\Alternative::class
);
$this->simpleFactory = $om->get(\Magento\Framework\View\Design\Fallback\Rule\SimpleFactory::class);
$this->filesystem = $om->get(\Magento\Framework\Filesystem::class);
}
/**
* Scan references to files from other static files and assert they are correct
*
* The CSS or LESS files may refer to other resources using `import` or url() notation
* We want to check integrity of all these references
* Note that the references may have syntax specific to the Magento preprocessing subsystem
*
* @param string $area
* @param string $themePath
* @param string $locale
* @param string $module
* @param string $filePath
* @param string $absolutePath
* @dataProvider referencesFromStaticFilesDataProvider
*/
public function testReferencesFromStaticFiles($area, $themePath, $locale, $module, $filePath, $absolutePath)
{
$contents = file_get_contents($absolutePath);
preg_match_all(
\Magento\Framework\View\Url\CssResolver::REGEX_CSS_RELATIVE_URLS,
$contents,
$matches
);
foreach ($matches[1] as $relatedResource) {
if (false !== strpos($relatedResource, '@')) { // unable to parse paths with LESS variables/mixins
continue;
}
list($relatedModule, $relatedPath) =
\Magento\Framework\View\Asset\Repository::extractModule($relatedResource);
if ($relatedModule) {
$fallbackModule = $relatedModule;
} else {
if ('less' == pathinfo($filePath, PATHINFO_EXTENSION)) {
/**
* The LESS library treats the related resources with relative links not in the same way as CSS:
* when another LESS file is included, it is embedded directly into the resulting document, but the
* relative paths of related resources are not adjusted accordingly to the new root file.
* Probably it is a bug of the LESS library.
*/
$this->markTestSkipped("Due to LESS library specifics, the '{$relatedResource}' cannot be tested.");
}
$fallbackModule = $module;
$relatedPath = \Magento\Framework\View\FileSystem::getRelatedPath($filePath, $relatedResource);
}
// the $relatedPath will be suitable for feeding to the fallback system
$staticFile = $this->getStaticFile($area, $themePath, $locale, $relatedPath, $fallbackModule);
if (empty($staticFile) && substr($relatedPath, 0, 2) === '..') {
//check if static file exists on lib level
$path = substr($relatedPath, 2);
$libDir = rtrim($this->filesystem->getDirectoryRead(DirectoryList::LIB_WEB)->getAbsolutePath(), '/');
$rule = $this->simpleFactory->create(['pattern' => $libDir]);
$params = ['area' => $area, 'theme' => $themePath, 'locale' => $locale];
$staticFile = $this->alternativeResolver->resolveFile($rule, $path, $params);
}
$this->assertNotEmpty(
$staticFile,
"The related resource cannot be resolved through fallback: '{$relatedResource}'"
);
}
}
/**
* Get a default theme path for specified area
*
* @param string $area
* @return string
* @throws \LogicException
*/
private function getDefaultThemePath($area)
{
switch ($area) {
case 'frontend':
return $this->design->getConfigurationDesignTheme($area);
case 'adminhtml':
return $this->design->getConfigurationDesignTheme($area);
case 'doc':
return 'Magento/blank';
default:
throw new \LogicException('Unable to determine theme path');
}
}
/**
* Get static file through fallback system using specified params
*
* @param string $area
* @param string|\Magento\Framework\View\Design\ThemeInterface $theme - either theme path (string) or theme object
* @param string $locale
* @param string $filePath
* @param string $module
* @param bool $isExplicit
* @return bool|string
*/
private function getStaticFile($area, $theme, $locale, $filePath, $module = null, $isExplicit = false)
{
if ($area == 'base') {
$theme = $this->baseTheme;
}
if (!is_object($theme)) {
$themePath = $theme ?: $this->getDefaultThemePath($area);
$theme = $this->themeRepo->create($themePath, $area);
}
if ($isExplicit) {
$type = \Magento\Framework\View\Design\Fallback\RulePool::TYPE_STATIC_FILE;
return $this->explicitFallback->resolve($type, $filePath, $area, $theme, $locale, $module);
}
return $this->fallback->getFile($area, $theme, $locale, $filePath, $module);
}
/**
* @return array
*/
public function referencesFromStaticFilesDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getStaticPreProcessingFiles('*.{less,css}');
}
/**
* There must be either .css or .less file, because if there are both, then .less will not be found by fallback
*
* @param string $area
* @param string $themePath
* @param string $locale
* @param string $module
* @param string $filePath
* @dataProvider lessNotConfusedWithCssDataProvider
*/
public function testLessNotConfusedWithCss($area, $themePath, $locale, $module, $filePath)
{
if (false !== strpos($filePath, 'widgets.css')) {
$filePath .= '';
}
$fileName = pathinfo($filePath, PATHINFO_FILENAME);
$dirName = dirname($filePath);
if ('.' == $dirName) {
$dirName = '';
} else {
$dirName .= '/';
}
$cssPath = $dirName . $fileName . '.css';
$lessPath = $dirName . $fileName . '.less';
$cssFile = $this->getStaticFile($area, $themePath, $locale, $cssPath, $module, true);
$lessFile = $this->getStaticFile($area, $themePath, $locale, $lessPath, $module, true);
$this->assertFalse(
$cssFile && $lessFile,
"A resource file of only one type must exist. Both found: '$cssFile' and '$lessFile'"
);
}
/**
* @return array
*/
public function lessNotConfusedWithCssDataProvider()
{
return \Magento\Framework\App\Utility\Files::init()->getStaticPreProcessingFiles('*.{less,css}');
}
/**
* Test if references $this->getViewFileUrl() in .phtml-files are correct
*
* @param string $phtmlFile
* @param string $area
* @param string $themePath
* @param string $fileId
* @dataProvider referencesFromPhtmlFilesDataProvider
*/
public function testReferencesFromPhtmlFiles($phtmlFile, $area, $themePath, $fileId)
{
list($module, $filePath) = \Magento\Framework\View\Asset\Repository::extractModule($fileId);
$this->assertNotEmpty(
$this->getStaticFile($area, $themePath, 'en_US', $filePath, $module),
"Unable to locate '{$fileId}' reference from {$phtmlFile}"
);
}
/**
* @return array
*/
public function referencesFromPhtmlFilesDataProvider()
{
$result = [];
foreach (\Magento\Framework\App\Utility\Files::init()->getPhtmlFiles(true, false) as $info) {
list($area, $themePath, , , $file) = $info;
foreach ($this->collectGetViewFileUrl($file) as $fileId) {
$result[] = [$file, $area, $themePath, $fileId];
}
}
return $result;
}
/**
* Find invocations of $block->getViewFileUrl() and extract the first argument value
*
* @param string $file
* @return array
*/
private function collectGetViewFileUrl($file)
{
$result = [];
if (preg_match_all('/\$block->getViewFileUrl\(\'([^\']+?)\'\)/', file_get_contents($file), $matches)) {
foreach ($matches[1] as $fileId) {
$result[] = $fileId;
}
}
return $result;
}
/**
* @param string $layoutFile
* @param string $area
* @param string $themePath
* @param string $fileId
* @dataProvider referencesFromLayoutFilesDataProvider
*/
public function testReferencesFromLayoutFiles($layoutFile, $area, $themePath, $fileId)
{
list($module, $filePath) = \Magento\Framework\View\Asset\Repository::extractModule($fileId);
$this->assertNotEmpty(
$this->getStaticFile($area, $themePath, 'en_US', $filePath, $module),
"Unable to locate '{$fileId}' reference from layout XML in {$layoutFile}"
);
}
/**
* @return array
*/
public function referencesFromLayoutFilesDataProvider()
{
$result = [];
$files = \Magento\Framework\App\Utility\Files::init()->getLayoutFiles(['with_metainfo' => true], false);
foreach ($files as $metaInfo) {
list($area, $themePath, , , $file) = array_pad($metaInfo, 5, null);
if (!is_string($file)) {
$this->addWarning(
'Wrong layout file configuration provided. The `file` meta info must be the type of string'
);
continue;
}
foreach ($this->collectFileIdsFromLayout($file) as $fileId) {
$result[] = [$file, $area, $themePath, $fileId];
}
}
return $result;
}
/**
* Collect view file declarations in layout XML-files
*
* @param string $file
* @return array
*/
private function collectFileIdsFromLayout($file)
{
$xml = simplexml_load_file($file);
$elements = $xml->xpath('//head/css|link|script');
$result = [];
if ($elements) {
foreach ($elements as $node) {
$result[] = (string)$node;
}
}
return $result;
}
}
@@ -0,0 +1,148 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Theme;
class TemplateFilesTest extends \Magento\TestFramework\TestCase\AbstractIntegrity
{
/**
* Note that data provider is not used in conventional way in order to not overwhelm test statistics
*/
public function testTemplates()
{
$invalidTemplates = [];
foreach ($this->templatesDataProvider() as $template) {
list($area, $themeId, $module, $file, $xml) = $template;
$params = ['area' => $area, 'themeId' => $themeId, 'module' => $module];
try {
$templateFilename = \Magento\TestFramework\Helper\Bootstrap::getObjectmanager()
->get(\Magento\Framework\View\FileSystem::class)
->getTemplateFileName($file, $params);
$this->assertFileExists($templateFilename);
} catch (\PHPUnit\Framework\ExpectationFailedException $e) {
$invalidTemplates[] = "File \"{$templateFilename}\" does not exist." .
PHP_EOL .
"Parameters: {$area}/{$themeId} {$module}::{$file}" .
PHP_EOL .
'Layout update: ' .
$xml;
}
}
$this->assertEmpty(
$invalidTemplates,
"Invalid templates found:\n\n" . implode("\n-----\n", $invalidTemplates)
);
}
public function templatesDataProvider()
{
$templates = [];
$themes = $this->_getDesignThemes();
foreach ($themes as $theme) {
/** @var \Magento\Framework\View\Layout\ProcessorInterface $layoutUpdate */
$layoutUpdate = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\View\Layout\ProcessorInterface::class,
['theme' => $theme]
);
$layoutTemplates = $this->_getLayoutTemplates($layoutUpdate->getFileLayoutUpdatesXml());
foreach ($layoutTemplates as $templateData) {
$templates[] = array_merge([$theme->getArea(), $theme->getId()], $templateData);
}
}
return $templates;
}
/**
* Get templates list that are defined in layout
*
* @param \SimpleXMLElement $layoutXml
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function _getLayoutTemplates($layoutXml)
{
$templates = [];
$blocks = $layoutXml->xpath('//block');
foreach ($blocks as $block) {
$attributes = $block->attributes();
if (isset($attributes['template'])) {
$module = $this->_getBlockModule($block);
if (!$this->_isTemplateForDisabledModule($module, (string)$attributes['template'])) {
$templates[] = [$module, (string)$attributes['template'], $block->asXML()];
}
}
}
$layoutTemplates = $layoutXml->xpath('//template');
foreach ($layoutTemplates as $template) {
$action = $template->xpath("parent::*");
$attributes = $action[0]->attributes();
switch ($attributes['method']) {
case 'setTemplate':
$parent = $action[0]->xpath("parent::*");
$attributes = $parent[0]->attributes();
$referenceName = (string)$attributes['name'];
$block = $layoutXml->xpath(
"//block[@name='{$referenceName}'] | //referenceBlock[@name='{$referenceName}']"
);
$module = $this->_getBlockModule($block[0]);
if (!$template->attributes() && !$this->_isTemplateForDisabledModule($module, (string)$template)) {
$templates[] = [$module, (string)$template, $parent[0]->asXml()];
}
break;
case 'addInformationRenderer':
case 'addMergeSettingsBlockType':
$blockType = $action[0]->xpath('block');
$module = $this->_getBlockModule($blockType[0]);
if (!$this->_isTemplateForDisabledModule($module, (string)$template)) {
$templates[] = [$module, (string)$template, $action[0]->asXml()];
}
break;
default:
break;
}
}
return $templates;
}
/**
* Get module name based on block definition in xml layout
*
* @param \SimpleXMLElement $xmlNode
* @return string
*/
protected function _getBlockModule($xmlNode)
{
$attributes = $xmlNode->attributes();
if (isset($attributes['type'])) {
$class = (string)$attributes['type'];
} else {
$class = (string)$xmlNode;
}
$blockModule = substr($class, 0, strpos($class, '_Block'));
return $blockModule;
}
/**
* Returns whether template belongs to a disabled module
*
* @param string $blockModule Module of a block that will render this template
* @param string $template
* @return bool
*/
protected function _isTemplateForDisabledModule($blockModule, $template)
{
$enabledModules = $this->_getEnabledModules();
if (!isset($enabledModules[$blockModule])) {
return true;
}
return $this->_isFileForDisabledModule($template);
}
}
@@ -0,0 +1,124 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Theme;
use Magento\Framework\Component\ComponentRegistrar;
class XmlFilesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Config\ValidationStateInterface
*/
protected $validationStateMock;
protected function setUp(): void
{
$this->validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class);
$this->validationStateMock->method('isValidationRequired')
->willReturn(true);
}
/**
* @param string $file
* @dataProvider viewConfigFileDataProvider
*/
public function testViewConfigFile($file)
{
$domConfig = new \Magento\Framework\Config\Dom(
file_get_contents($file),
$this->validationStateMock
);
$errors = [];
$urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
$result = $domConfig->validate(
$urnResolver->getRealPath('urn:magento:framework:Config/etc/view.xsd'),
$errors
);
$this->assertTrue($result, "Invalid XML-file: {$file}\n" . join("\n", $errors));
}
/**
* @return array
*/
public function viewConfigFileDataProvider()
{
$result = [];
/** @var \Magento\Framework\Component\DirSearch $componentDirSearch */
$componentDirSearch = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Component\DirSearch::class);
$files = $componentDirSearch->collectFiles(ComponentRegistrar::THEME, 'etc/view.xml');
foreach ($files as $file) {
$result[substr($file, strlen(BP))] = [$file];
}
return $result;
}
/**
* @param string $themeDir
* @dataProvider themeConfigFileExistsDataProvider
*/
public function testThemeConfigFileExists($themeDir)
{
$this->assertFileExists($themeDir . '/theme.xml');
}
/**
* @return array
*/
public function themeConfigFileExistsDataProvider()
{
$result = [];
/** @var \Magento\Framework\Component\ComponentRegistrar $componentRegistrar */
$componentRegistrar = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Component\ComponentRegistrar::class);
foreach ($componentRegistrar->getPaths(ComponentRegistrar::THEME) as $themeDir) {
$result[substr($themeDir, strlen(BP))] = [$themeDir];
}
return $result;
}
/**
* @param string $file
* @dataProvider themeConfigFileDataProvider
*/
public function testThemeConfigFileSchema($file)
{
$domConfig = new \Magento\Framework\Config\Dom(file_get_contents($file), $this->validationStateMock);
$errors = [];
$result = $domConfig->validate('urn:magento:framework:Config/etc/theme.xsd', $errors);
$this->assertTrue($result, "Invalid XML-file: {$file}\n" . join("\n", $errors));
}
/**
* Configuration should declare a single package/theme that corresponds to the file system directories
*
* @param string $file
* @dataProvider themeConfigFileDataProvider
*/
public function testThemeConfigFileHasSingleTheme($file)
{
/** @var $configXml \SimpleXMLElement */
$configXml = simplexml_load_file($file);
$actualThemes = $configXml->xpath('/theme');
$this->assertCount(1, $actualThemes, 'Single theme declaration is expected.');
}
/**
* @return array
*/
public function themeConfigFileDataProvider()
{
$result = [];
/** @var \Magento\Framework\Component\DirSearch $componentDirSearch */
$componentDirSearch = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Component\DirSearch::class);
$files = $componentDirSearch->collectFiles(ComponentRegistrar::THEME, 'theme.xml');
foreach ($files as $file) {
$result[substr($file, strlen(BP))] = [$file];
}
return $result;
}
}
@@ -0,0 +1,276 @@
<?php
/**
* Test constructions of layout files
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* This test finds usages of modular view files, searched in non-modular context - it is obsolete and buggy
* functionality, initially introduced in Magento 2.
*
* The test goes through modular calls of view files, and finds out, whether there are theme non-modular files
* with the same path. Before fixing the bug, such call return theme files instead of modular files, which is
* incorrect. After fixing the bug, such calls will start returning modular files, which is not a file we got used
* to see, so such cases are probably should be fixed. The test finds such suspicious places.
*
* The test is intended to be deleted before Magento 2 release. With the release, having non-modular files with the
* same paths as modular ones, is legitimate.
*/
namespace Magento\Test\Integrity;
use Magento\Framework\Component\ComponentRegistrar;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ViewFileReferenceTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\View\Design\Fallback\Rule\RuleInterface
*/
protected static $_fallbackRule;
/**
* @var \Magento\Framework\View\Design\FileResolution\Fallback\StaticFile
*/
protected static $_viewFilesFallback;
/**
* @var \Magento\Framework\View\Design\FileResolution\Fallback\File
*/
protected static $_filesFallback;
/**
* @var array
*/
protected static $_checkThemeLocales = [];
/**
* @var \Magento\Theme\Model\Theme\Collection
*/
protected static $_themeCollection;
/**
* @var \Magento\Framework\Component\ComponentRegistrar
*/
protected static $_componentRegistrar;
public static function setUpBeforeClass(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->configure(
['preferences' => [\Magento\Theme\Model\Theme::class => \Magento\Theme\Model\Theme\Data::class]]
);
self::$_componentRegistrar = $objectManager->get(\Magento\Framework\Component\ComponentRegistrar::class);
/** @var $fallbackPool \Magento\Framework\View\Design\Fallback\RulePool */
$fallbackPool = $objectManager->get(\Magento\Framework\View\Design\Fallback\RulePool::class);
self::$_fallbackRule = $fallbackPool->getRule(
$fallbackPool::TYPE_STATIC_FILE
);
self::$_viewFilesFallback = $objectManager->get(
\Magento\Framework\View\Design\FileResolution\Fallback\StaticFile::class
);
self::$_filesFallback = $objectManager->get(\Magento\Framework\View\Design\FileResolution\Fallback\File::class);
// Themes to be checked
self::$_themeCollection = $objectManager->get(\Magento\Theme\Model\Theme\Collection::class);
// Compose list of locales, needed to be checked for themes
self::$_checkThemeLocales = [];
foreach (self::$_themeCollection as $theme) {
$themeLocales = self::_getThemeLocales($theme);
$themeLocales[] = null;
// Default non-localized file will need to be checked as well
self::$_checkThemeLocales[$theme->getFullPath()] = $themeLocales;
}
}
/**
* Return array of locales, supported by the theme
*
* @param \Magento\Framework\View\Design\ThemeInterface $theme
* @return array
*/
protected static function _getThemeLocales(\Magento\Framework\View\Design\ThemeInterface $theme)
{
$result = [];
$patternDir = self::_getLocalePatternDir($theme);
foreach (\ResourceBundle::getLocales('') as $locale) {
$dir = str_replace('<locale_placeholder>', $locale, $patternDir);
if (is_dir($dir)) {
$result[] = $locale;
}
}
return $result;
}
/**
* Return pattern for theme locale directories, where <locale_placeholder> is placed to mark a locale's location.
*
* @param \Magento\Framework\View\Design\ThemeInterface $theme
* @return string
* @throws \Exception
*/
protected static function _getLocalePatternDir(\Magento\Framework\View\Design\ThemeInterface $theme)
{
$localePlaceholder = '<locale_placeholder>';
$params = ['area' => $theme->getArea(), 'theme' => $theme, 'locale' => $localePlaceholder];
$patternDirs = self::$_fallbackRule->getPatternDirs($params);
$themePath = self::$_componentRegistrar->getPath(
\Magento\Framework\Component\ComponentRegistrar::THEME,
$theme->getFullPath()
);
foreach ($patternDirs as $patternDir) {
$patternPath = $patternDir . '/';
if ((strpos($patternPath, $themePath) !== false) // It is theme's directory
&& (strpos($patternPath, $localePlaceholder) !== false) // It is localized directory
) {
return $patternDir;
}
}
throw new \Exception('Unable to determine theme locale path');
}
/**
* @param string $modularCall
* @param array $usages
* @param null|string $area
* @dataProvider modularFallbackDataProvider
*/
public function testModularFallback($modularCall, array $usages, $area)
{
list(, $file) = explode(\Magento\Framework\View\Asset\Repository::FILE_ID_SEPARATOR, $modularCall);
$wrongResolutions = [];
foreach (self::$_themeCollection as $theme) {
if ($area && $theme->getArea() != $area) {
continue;
}
$found = $this->_getFileResolutions($theme, $file);
$wrongResolutions = array_merge($wrongResolutions, $found);
}
if ($wrongResolutions) {
// If file is found, then old functionality (find modular files in non-modular locations) is used
$message = sprintf(
"Found modular call:\n %s in\n %s\n which may resolve to non-modular location(s):\n %s",
$modularCall,
implode(', ', $usages),
implode(', ', $wrongResolutions)
);
$this->fail($message);
}
}
/**
* Resolves file to find its fallback'ed paths
*
* @param \Magento\Framework\View\Design\ThemeInterface $theme
* @param string $file
* @return array
*/
protected function _getFileResolutions(\Magento\Framework\View\Design\ThemeInterface $theme, $file)
{
$found = [];
$fileResolved = self::$_filesFallback->getFile($theme->getArea(), $theme, $file);
if (file_exists($fileResolved)) {
$found[$fileResolved] = $fileResolved;
}
foreach (self::$_checkThemeLocales[$theme->getFullPath()] as $locale) {
$fileResolved = self::$_viewFilesFallback->getFile($theme->getArea(), $theme, $locale, $file);
if (file_exists($fileResolved)) {
$found[$fileResolved] = $fileResolved;
}
}
return $found;
}
/**
* @return array
*/
public static function modularFallbackDataProvider()
{
$result = [];
foreach (self::_getFilesToProcess() as $file) {
$file = (string)$file;
$modulePattern = '[A-Z][a-z]+_[A-Z][a-z]+';
$filePattern = '[[:alnum:]_/-]+\\.[[:alnum:]_./-]+';
$pattern = '#' . $modulePattern
. preg_quote(\Magento\Framework\View\Asset\Repository::FILE_ID_SEPARATOR)
. $filePattern . '#S';
if (!preg_match_all($pattern, file_get_contents($file), $matches)) {
continue;
}
$area = self::_getArea($file);
foreach ($matches[0] as $modularCall) {
$dataSetKey = $modularCall . ' @ ' . ($area ?: 'any area');
if (!isset($result[$dataSetKey])) {
$result[$dataSetKey] = ['modularCall' => $modularCall, 'usages' => [], 'area' => $area];
}
$result[$dataSetKey]['usages'][$file] = $file;
}
}
return $result;
}
/**
* Return list of files, that must be processed, searching for modular calls to view files
*
* @return array
*/
protected static function _getFilesToProcess()
{
$result = [];
$componentRegistrar = new \Magento\Framework\Component\ComponentRegistrar();
$dirs = array_merge(
$componentRegistrar->getPaths(ComponentRegistrar::MODULE),
$componentRegistrar->getPaths(ComponentRegistrar::THEME)
);
foreach ($dirs as $dir) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS)
);
$result = array_merge($result, iterator_to_array($iterator));
}
return $result;
}
/**
* Get the area, where file is located.
*
* Null is returned, if the file is not within an area, e.g. it is a model/block/helper php-file.
*
* @param string $file
* @return string|null
*/
protected static function _getArea($file)
{
$file = str_replace('\\', '/', $file);
$areaPatterns = [];
$componentRegistrar = new ComponentRegistrar();
foreach ($componentRegistrar->getPaths(ComponentRegistrar::THEME) as $themeDir) {
$areaPatterns[] = '#' . $themeDir . '/([^/]+)/#S';
}
foreach ($componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $moduleDir) {
$areaPatterns[] = '#' . $moduleDir . '/view/([^/]+)/#S';
}
foreach ($areaPatterns as $pattern) {
if (preg_match($pattern, $file, $matches)) {
return $matches[1];
}
}
return null;
}
}