This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,234 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionException;
/**
* Class consist of dataFixtures base logic
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class AbstractDataFixture
{
/**
* @var array
*/
protected $_appliedFixtures = [];
/**
* @var array
*/
protected $fixtures = [];
/**
* Retrieve fixtures from annotation
*
* @param TestCase $test
* @param string|null $scope
* @return array
*/
protected function _getFixtures(TestCase $test, $scope = null)
{
$annotationKey = $this->getAnnotation();
if (!empty($this->fixtures[$annotationKey][$this->getTestKey($test)])) {
return $this->fixtures[$annotationKey][$this->getTestKey($test)];
}
$resolver = Resolver::getInstance();
$resolver->setCurrentFixtureType($annotationKey);
$parsers = Bootstrap::getObjectManager()
->create(
\Magento\TestFramework\Annotation\Parser\Composite::class,
[
'parsers' => $this->getParsers()
]
);
$fixtures = [];
try {
$fixtures = $parsers->parse($test, $scope ?: ParserInterface::SCOPE_METHOD);
if (!$fixtures && !$scope) {
$fixtures = $parsers->parse($test, ParserInterface::SCOPE_CLASS);
}
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse fixtures',
get_class($test),
$test->getName(false),
$exception
);
}
/* Need to be applied even test does not have added fixtures because fixture can be added via config */
$this->fixtures[$annotationKey][$this->getTestKey($test)] = $resolver->applyDataFixtures(
$test,
$fixtures,
$annotationKey
);
return $this->fixtures[$annotationKey][$this->getTestKey($test)] ?? [];
}
/**
* Get method annotations.
*
* Overwrites class-defined annotations.
*
* @param TestCase $test
* @return array
*/
protected function getAnnotations(TestCase $test): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
return array_replace((array)$annotations['class'], (array)$annotations['method']);
}
/**
* Execute fixture scripts if any
*
* @param array $fixtures
* @param TestCase $test
* @return void
*/
protected function _applyFixtures(array $fixtures, TestCase $test)
{
$objectManager = Bootstrap::getObjectManager();
$testsIsolation = $objectManager->get(TestsIsolation::class);
$dbIsolationState = $this->getDbIsolationState($test);
$testsIsolation->createDbSnapshot($test, $dbIsolationState);
$dataFixtureSetup = $objectManager->get(DataFixtureSetup::class);
/* Execute fixture scripts */
foreach ($fixtures as $fixture) {
if (is_callable([get_class($test), $fixture['factory']])) {
$fixture['factory'] = get_class($test) . '::' . $fixture['factory'];
}
$fixture['test'] = [
'class' => get_class($test),
'method' => $test->getName(false),
'dataSet' => $test->dataName(),
];
try {
$fixture['result'] = $dataFixtureSetup->apply($fixture);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to apply fixture: ' . $this->getFixtureReference($fixture),
$fixture['test']['class'],
$fixture['test']['method'],
$exception
);
}
$this->_appliedFixtures[] = $fixture;
}
$resolver = Resolver::getInstance();
$resolver->setCurrentFixtureType(null);
}
/**
* Revert changes done by fixtures
*
* @param TestCase|null $test
* @return void
*/
protected function _revertFixtures(?TestCase $test = null)
{
$objectManager = Bootstrap::getObjectManager();
$dataFixtureSetup = $objectManager->get(DataFixtureSetup::class);
$resolver = Resolver::getInstance();
$resolver->setCurrentFixtureType($this->getAnnotation());
$appliedFixtures = array_reverse($this->_appliedFixtures);
foreach ($appliedFixtures as $fixture) {
try {
$dataFixtureSetup->revert($fixture);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to revert fixture: ' . $this->getFixtureReference($fixture),
$fixture['test']['class'],
$fixture['test']['method'],
$exception
);
}
}
$this->_appliedFixtures = [];
$resolver->setCurrentFixtureType(null);
if (null !== $test) {
/** @var TestsIsolation $testsIsolation */
$testsIsolation = $objectManager->get(TestsIsolation::class);
$dbIsolationState = $this->getDbIsolationState($test);
$testsIsolation->checkTestIsolation($test, $dbIsolationState);
}
}
/**
* Get reference to the fixture definition
*
* @param array $fixture
* @return string
*/
private function getFixtureReference(array $fixture): string
{
return sprintf(
'%s%s',
$fixture['factory'],
$fixture['name'] ? ' (' . $fixture['name'] . ')' : '',
);
}
/**
* Return fixtures parser
*
* @return ParserInterface[]
*/
protected function getParsers(): array
{
$parsers = [];
$parsers[] = Bootstrap::getObjectManager()->create(
\Magento\TestFramework\Annotation\Parser\DataFixture::class,
['annotation' => $this->getAnnotation()]
);
return $parsers;
}
/**
* Return is explicit set isolation state
*
* @param TestCase $test
* @return array|null
*/
protected function getDbIsolationState(TestCase $test)
{
$isEnabled = Bootstrap::getObjectManager()->get(DbIsolationState::class)->isEnabled($test);
return $isEnabled === null ? null : [$isEnabled ? 'enabled' : 'disabled'];
}
/**
* Get uniq test cache key
*
* @param TestCase $test
* @return string
*/
private function getTestKey(TestCase $test): string
{
return sprintf('%s::%s', get_class($test), $test->getName());
}
/**
* Get annotation name
*
* @return string
*/
abstract protected function getAnnotation(): string;
}
@@ -0,0 +1,135 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Implementation of the @magentoAdminConfigFixture DocBlock annotation
*/
namespace Magento\TestFramework\Annotation;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use PHPUnit\Framework\TestCase;
/**
* Handler for applying magentoAdminConfigFixture annotation
*/
class AdminConfigFixture
{
public const ANNOTATION = 'magentoAdminConfigFixture';
/**
* The test instance that is available between 'startTest' and 'stopTest' events.
*
* @var TestCase
*/
protected $_currentTest;
/**
* Original values for global configuration options that need to be restored
*
* @var array
*/
private $_configValues = [];
/**
* Retrieve configuration node value
*
* @param string $configPath
* @return string
*/
protected function _getConfigValue($configPath)
{
return Bootstrap::getObjectManager()->get(MutableScopeConfigInterface::class)->getValue($configPath);
}
/**
* Assign configuration node value
*
* @param string $configPath
* @param string $value
* @return void
*/
protected function _setConfigValue($configPath, $value)
{
Bootstrap::getObjectManager()->get(MutableScopeConfigInterface::class)->setValue($configPath, $value);
}
/**
* Assign required config values and save original ones
*
* @param TestCase $test
* @return void
*/
protected function _assignConfigData(TestCase $test)
{
$resolver = Resolver::getInstance();
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$existingFixtures = $annotations['method'][self::ANNOTATION] ?? [];
/* Need to be applied even test does not have added fixtures because fixture can be added via config */
$testAnnotations = $resolver->applyConfigFixtures($test, $existingFixtures, self::ANNOTATION);
foreach ($testAnnotations as $configPathAndValue) {
list($configPath, $requiredValue) = preg_split('/\s+/', $configPathAndValue, 2);
$originalValue = $this->_getConfigValue($configPath);
$this->_configValues[$configPath] = $originalValue;
$this->_setConfigValue($configPath, $requiredValue);
}
}
/**
* Restore original values for changed config options
*
* @return void
*/
protected function _restoreConfigData()
{
foreach ($this->_configValues as $configPath => $originalValue) {
$this->_setConfigValue($configPath, $originalValue);
}
$this->_configValues = [];
}
/**
* Handler for 'startTest' event
*
* @param TestCase $test
* @return void
*/
public function startTest(TestCase $test)
{
$this->_currentTest = $test;
$this->_assignConfigData($test);
}
/**
* Handler for 'endTest' event
*
* @param TestCase $test
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function endTest(TestCase $test)
{
$this->_currentTest = null;
$this->_restoreConfigData();
}
/**
* Reassign configuration data whenever application is reset
*
* @return void
*/
public function initStoreAfter()
{
/* process events triggered from within a test only */
if ($this->_currentTest) {
$this->_assignConfigData($this->_currentTest);
}
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Annotation;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Application;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class AppArea
{
public const ANNOTATION_NAME = 'magentoAppArea';
/**
* @var Application
*/
private $_application;
/**
* List of allowed areas.
*
* @var array
*/
private $_allowedAreas = [
\Magento\Framework\App\Area::AREA_GLOBAL,
\Magento\Framework\App\Area::AREA_ADMINHTML,
\Magento\Framework\App\Area::AREA_FRONTEND,
\Magento\Framework\App\Area::AREA_WEBAPI_REST,
\Magento\Framework\App\Area::AREA_WEBAPI_SOAP,
\Magento\Framework\App\Area::AREA_CRONTAB,
\Magento\Framework\App\Area::AREA_GRAPHQL
];
/**
* @param Application $application
*/
public function __construct(Application $application)
{
$this->_application = $application;
}
/**
* Get current application area
*
* @param array $annotations
* @return string
* @throws LocalizedException
*/
protected function _getTestAppArea($annotations)
{
$area = isset(
$annotations['method'][self::ANNOTATION_NAME]
) ? current(
$annotations['method'][self::ANNOTATION_NAME]
) : (isset(
$annotations['class'][self::ANNOTATION_NAME]
) ? current(
$annotations['class'][self::ANNOTATION_NAME]
) : \Magento\TestFramework\Application::DEFAULT_APP_AREA);
if (false == in_array($area, $this->_allowedAreas)) {
throw new \Magento\Framework\Exception\LocalizedException(
__(
'Invalid "@magentoAppArea" annotation, can be "%1" only.',
implode('", "', $this->_allowedAreas)
)
);
}
return $area;
}
/**
* Start test case event observer
*
* @param TestCase $test
* @throws LocalizedException
*/
public function startTest(TestCase $test)
{
$values = [];
try {
$values = $this->parse($test);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse fixtures',
get_class($test),
$test->getName(false),
$exception
);
}
$area = $values[0]['area'] ?? Application::DEFAULT_APP_AREA;
if ($this->_application->getArea() !== $area) {
$this->_application->reinitialize();
if ($this->_application->getArea() !== $area) {
$this->_application->loadArea($area);
}
}
}
/**
* Returns AppArea fixtures configuration
*
* @param TestCase $test
* @return array
* @throws LocalizedException
*/
private function parse(TestCase $test): array
{
$objectManager = Bootstrap::getObjectManager();
$parsers = $objectManager
->create(
\Magento\TestFramework\Annotation\Parser\Composite::class,
[
'parsers' => [
$objectManager->get(\Magento\TestFramework\Annotation\Parser\AppArea::class),
$objectManager->get(\Magento\TestFramework\Fixture\Parser\AppArea::class)
]
]
);
$values = $parsers->parse($test, ParserInterface::SCOPE_METHOD)
?: $parsers->parse($test, ParserInterface::SCOPE_CLASS);
if (count($values) > 1) {
throw new LocalizedException(
__('Only one "@magentoAppArea" annotation is allowed per test')
);
}
return $values;
}
}
@@ -0,0 +1,141 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Implementation of the @magentoAppIsolation DocBlock annotation - isolation of global application objects in memory
*/
namespace Magento\TestFramework\Annotation;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Application;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractController;
use PHPUnit\Framework\TestCase;
class AppIsolation
{
/**
* Flag to prevent an excessive test case isolation if the last test has been just isolated
*
* @var bool
*/
private $hasNonIsolatedTests = true;
/**
* @var Application
*/
private $application;
/**
* @var array
*/
private $serverGlobalBackup;
/**
* Constructor
*
* @param Application $application
*/
public function __construct(Application $application)
{
$this->application = $application;
}
/**
* Isolate global application objects
*/
protected function _isolateApp()
{
if ($this->hasNonIsolatedTests) {
$this->application->reinitialize();
$_SESSION = [];
$_COOKIE = [];
session_write_close();
$this->hasNonIsolatedTests = false;
}
}
/**
* Isolate application before running test case
*/
public function startTestSuite()
{
$this->serverGlobalBackup = $_SERVER;
$this->_isolateApp();
}
/**
* Isolate application after running test case
*/
public function endTestSuite()
{
$_SERVER = $this->serverGlobalBackup;
}
/**
* Handler for 'endTest' event
*
* @param TestCase $test
* @throws LocalizedException
*/
public function endTest(TestCase $test)
{
$this->hasNonIsolatedTests = true;
$values = [];
try {
$values = $this->parse($test);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse annotations',
get_class($test),
$test->getName(false),
$exception
);
}
if ($values) {
$isIsolationEnabled = $values[0]['enabled'];
} else {
/* Controller tests should be isolated by default */
$isIsolationEnabled = $test instanceof AbstractController;
}
if ($isIsolationEnabled) {
$this->_isolateApp();
}
}
/**
* Returns AppIsolation fixtures configuration
*
* @param TestCase $test
* @return array
* @throws LocalizedException
*/
private function parse(TestCase $test): array
{
$objectManager = Bootstrap::getObjectManager();
$parsers = $objectManager
->create(
\Magento\TestFramework\Annotation\Parser\Composite::class,
[
'parsers' => [
$objectManager->get(\Magento\TestFramework\Annotation\Parser\AppIsolation::class),
$objectManager->get(\Magento\TestFramework\Fixture\Parser\AppIsolation::class)
]
]
);
$values = $parsers->parse($test, ParserInterface::SCOPE_METHOD)
?: $parsers->parse($test, ParserInterface::SCOPE_CLASS);
if (count($values) > 1) {
throw new LocalizedException(
__('Only one "@magentoAppIsolation" annotation is allowed per test')
);
}
return $values;
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Annotation;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Implementation of the @magentoCache DocBlock annotation
*/
class Cache
{
/**
* Original values for cache type states
*
* @var array
*/
private $origValues = [];
/**
* Handler for 'startTest' event
*
* @param TestCase $test
* @return void
*/
public function startTest(TestCase $test)
{
$statusList = [];
try {
$statusList = $this->parse($test);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse fixtures',
get_class($test),
$test->getName(false),
$exception
);
}
if ($statusList) {
$values = [];
$typeList = self::getTypeList();
foreach ($statusList as $cache) {
if ('all' === $cache['type']) {
foreach ($typeList->getTypes() as $type) {
$values[$type['id']] = $cache['status'];
}
} else {
$values[$cache['type']] = $cache['status'];
}
}
$this->setValues($values, $test);
}
}
/**
* Handler for 'endTest' event
*
* @param TestCase $test
* @return void
*/
public function endTest(TestCase $test)
{
if ($this->origValues) {
$this->setValues($this->origValues, $test);
$this->origValues = [];
}
}
/**
* Sets the values of cache types
*
* @param array $values
* @param TestCase $test
*/
private function setValues($values, TestCase $test)
{
$typeList = self::getTypeList();
if (!$this->origValues) {
$this->origValues = [];
foreach ($typeList->getTypes() as $type => $row) {
$this->origValues[$type] = $row['status'];
}
}
/** @var \Magento\Framework\App\Cache\StateInterface $states */
$states = Bootstrap::getInstance()->getObjectManager()->get(\Magento\Framework\App\Cache\StateInterface::class);
foreach ($values as $type => $isEnabled) {
if (!isset($this->origValues[$type])) {
ExceptionHandler::handle(
"Unknown cache type specified: '{$type}' in @magentoCache",
get_class($test),
$test->getName(false)
);
}
$states->setEnabled($type, $isEnabled);
}
}
/**
* Getter for cache types list
*
* @return \Magento\Framework\App\Cache\TypeListInterface
*/
private static function getTypeList()
{
return Bootstrap::getInstance()->getObjectManager()->get(\Magento\Framework\App\Cache\TypeListInterface::class);
}
/**
* Returns Cache fixtures configuration
*
* @param TestCase $test
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function parse(TestCase $test): array
{
$objectManager = Bootstrap::getObjectManager();
$parsers = $objectManager
->create(
\Magento\TestFramework\Annotation\Parser\Composite::class,
[
'parsers' => [
$objectManager->get(\Magento\TestFramework\Annotation\Parser\Cache::class),
$objectManager->get(\Magento\TestFramework\Fixture\Parser\Cache::class)
]
]
);
return $parsers->parse($test, ParserInterface::SCOPE_METHOD)
?: $parsers->parse($test, ParserInterface::SCOPE_CLASS);
}
}
@@ -0,0 +1,178 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Annotation;
use FilesystemIterator;
use InvalidArgumentException;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\Parser\Composite;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;
use RegexIterator;
use SplFileInfo;
use Throwable;
/**
* Implementation of the @magentoComponentsDir DocBlock annotation
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ComponentRegistrarFixture
{
public const ANNOTATION_NAME = 'magentoComponentsDir';
/**#@+
* Properties of components registrar
*/
public const REGISTRAR_CLASS = ComponentRegistrar::class;
public const PATHS_FIELD = 'paths';
/**#@-*/
/**
* Fixtures base dir
*
* @var string
*/
private $fixtureBaseDir;
/**
* Original values of registered components
*
* @var array
*/
private $origComponents = null;
/**
* Constructor
*
* @param string $fixtureBaseDir
*/
public function __construct($fixtureBaseDir)
{
$this->fixtureBaseDir = $fixtureBaseDir;
}
/**
* Handler for 'startTest' event
*
* @param TestCase $test
* @return void
*/
public function startTest(TestCase $test)
{
$this->registerComponents($test);
}
/**
* Handler for 'endTest' event
*
* @param TestCase $test
* @return void
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function endTest(TestCase $test)
{
$this->restoreComponents();
}
/**
* Register fixture components
*
* @param TestCase $test
*/
private function registerComponents(TestCase $test)
{
$values = [];
try {
$values = $this->parse($test);
} catch (Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse fixtures',
get_class($test),
$test->getName(false),
$exception
);
}
if (!$values) {
return;
}
$componentAnnotations = array_unique(array_column($values, 'path'));
$reflection = new ReflectionClass(self::REGISTRAR_CLASS);
$paths = $reflection->getProperty(self::PATHS_FIELD);
$paths->setAccessible(true);
$this->origComponents = $paths->getValue();
$paths->setAccessible(false);
foreach ($componentAnnotations as $fixturePath) {
$fixturesDir = $this->fixtureBaseDir . '/' . $fixturePath;
if (!file_exists($fixturesDir)) {
throw new InvalidArgumentException(
self::ANNOTATION_NAME . " fixture '$fixturePath' does not exist"
);
}
$iterator = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($fixturesDir, FilesystemIterator::SKIP_DOTS)
),
'/^.+\/registration\.php$/'
);
/**
* @var SplFileInfo $registrationFile
*/
foreach ($iterator as $registrationFile) {
require $registrationFile->getRealPath();
}
}
}
/**
* Restore registered components list to the original
*/
private function restoreComponents()
{
if (null !== $this->origComponents) {
$reflection = new ReflectionClass(self::REGISTRAR_CLASS);
$paths = $reflection->getProperty(self::PATHS_FIELD);
$paths->setAccessible(true);
$paths->setValue(null, $this->origComponents);
$paths->setAccessible(false);
$this->origComponents = null;
}
}
/**
* Returns ComponentsDir fixtures configuration
*
* @param TestCase $test
* @return array
* @throws LocalizedException
*/
private function parse(TestCase $test): array
{
$objectManager = Bootstrap::getObjectManager();
$parsers = $objectManager
->create(
Composite::class,
[
'parsers' => [
$objectManager->get(\Magento\TestFramework\Annotation\Parser\ComponentsDir::class),
$objectManager->get(\Magento\TestFramework\Fixture\Parser\ComponentsDir::class)
]
]
);
return array_merge(
$parsers->parse($test, ParserInterface::SCOPE_CLASS),
$parsers->parse($test, ParserInterface::SCOPE_METHOD)
);
}
}
@@ -0,0 +1,329 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Implementation of the @magentoConfigFixture DocBlock annotation
*/
namespace Magento\TestFramework\Annotation;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\ScopeInterface;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\Parser\Config as ConfigFixtureParser;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use PHPUnit\Framework\TestCase;
/**
* Handler which works with magentoConfigFixture annotations
*/
class ConfigFixture
{
public const ANNOTATION = 'magentoConfigFixture';
/**
* Test instance that is available between 'startTest' and 'stopTest' events
*
* @var TestCase
*/
protected $_currentTest;
/**
* Original values for global configuration options that need to be restored
*
* @var array
*/
protected $globalConfigValues = [];
/**
* Original values for website-scoped configuration options that need to be restored
*
* @var array
*/
protected $websiteConfigValues = [];
/**
* Original values for store-scoped configuration options that need to be restored
*
* @var array
*/
protected $storeConfigValues = [];
/**
* Retrieve configuration node value
*
* @param string $configPath
* @param string|bool|null $scopeCode
* @return string
*/
protected function _getConfigValue($configPath, $scopeCode = null)
{
return $this->getScopeConfigValue($configPath, ScopeInterface::SCOPE_STORE, $scopeCode);
}
/**
* Retrieve scope configuration node value
*
* @param string $configPath
* @param string $scopeType
* @param string|null $scopeCode
* @return mixed|null
*/
protected function getScopeConfigValue(string $configPath, string $scopeType, string $scopeCode = null)
{
$result = null;
if ($scopeCode !== false) {
$scopeConfig = $this->getScopeConfig();
$result = $scopeConfig->getValue($configPath, $scopeType, $scopeCode);
}
return $result;
}
/**
* Assign configuration node value
*
* @param string $configPath
* @param string $value
* @param string|bool|null $storeCode
* @return void
*/
protected function _setConfigValue($configPath, $value, $storeCode = false)
{
$scopeType = $storeCode === false ? ScopeConfigInterface::SCOPE_TYPE_DEFAULT : ScopeInterface::SCOPE_STORE;
$this->setScopeConfigValue($configPath, $value, $scopeType, $storeCode);
}
/**
* Set config scope value
*
* @param string $configPath
* @param string|null $value
* @param string $scopeType
* @param string|null $scopeCode
* @return void
*/
protected function setScopeConfigValue(
string $configPath,
?string $value,
string $scopeType,
?string $scopeCode
): void {
$config = $this->getMutableScopeConfig();
if (strpos($configPath, 'default/') === 0) {
$configPath = substr($configPath, 8);
$config->setValue($configPath, $value, ScopeConfigInterface::SCOPE_TYPE_DEFAULT);
} else {
$config->setValue($configPath, $value, $scopeType, $scopeCode);
}
}
/**
* Get mutable config object
*
* @return MutableScopeConfigInterface
*/
protected function getMutableScopeConfig(): MutableScopeConfigInterface
{
return Bootstrap::getObjectManager()->get(MutableScopeConfigInterface::class);
}
/**
* Get config object
*
* @return ScopeConfigInterface
*/
protected function getScopeConfig(): ScopeConfigInterface
{
return Bootstrap::getObjectManager()->get(ScopeConfigInterface::class);
}
/**
* Assign required config values and save original ones
*
* @param TestCase $test
* @return void
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
protected function _assignConfigData(TestCase $test)
{
$resolver = Resolver::getInstance();
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$existingFixtures = array_merge(
$annotations['method'][self::ANNOTATION] ?? [],
$this->getConfigFixturesFromAttribute($test)
);
/* Need to be applied even test does not have added fixtures because fixture can be added via config */
$testAnnotations = $resolver->applyConfigFixtures(
$test,
$existingFixtures,
self::ANNOTATION
);
foreach ($testAnnotations as $configPathAndValue) {
if (preg_match('/^[^\/]+?(?=_store\s)/', $configPathAndValue, $matches)) {
$this->setStoreConfigValue($matches ?? [], $configPathAndValue);
} elseif (preg_match('/^[^\/]+?(?=_website\s)/', $configPathAndValue, $matches)) {
$this->setWebsiteConfigValue($matches ?? [], $configPathAndValue);
} else {
$this->setGlobalConfigValue($configPathAndValue);
}
}
}
/**
* Sets store-scoped config value
*
* @param array $matches
* @param string $configPathAndValue
* @return void
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
protected function setStoreConfigValue(array $matches, $configPathAndValue): void
{
$storeCode = $matches[0] != 'current' ? $matches[0] : null;
$parts = preg_split('/\s+/', $configPathAndValue, 3);
list($configScope, $configPath, $requiredValue) = $parts + ['', '', ''];
$originalValue = $this->_getConfigValue($configPath, $storeCode);
$this->storeConfigValues[$storeCode][$configPath] = $originalValue;
$this->_setConfigValue($configPath, $requiredValue, $storeCode);
}
/**
* Sets website-scoped config value
*
* @param array $matches
* @param string $configPathAndValue
* @return void
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
protected function setWebsiteConfigValue(array $matches, $configPathAndValue): void
{
$websiteCode = $matches[0] != 'current' ? $matches[0] : null;
$parts = preg_split('/\s+/', $configPathAndValue, 3);
list($configScope, $configPath, $requiredValue) = $parts + ['', '', ''];
$originalValue = $this->getScopeConfigValue($configPath, ScopeInterface::SCOPE_WEBSITES, $websiteCode);
$this->websiteConfigValues[$websiteCode][$configPath] = $originalValue;
$this->setScopeConfigValue($configPath, $requiredValue, ScopeInterface::SCOPE_WEBSITES, $websiteCode);
}
/**
* Sets global config value
*
* @param string $configPathAndValue
* @return void
*/
protected function setGlobalConfigValue($configPathAndValue): void
{
/* Global config value */
list($configPath, $requiredValue) = preg_split('/\s+/', $configPathAndValue, 2);
$configPath = str_starts_with($configPath, 'default/') ? substr($configPath, 8) : $configPath;
$originalValue = $this->_getConfigValue($configPath);
$this->globalConfigValues[$configPath] = $originalValue;
$this->_setConfigValue($configPath, $requiredValue);
}
/**
* Restore original values for changed config options
*
* @return void
*/
protected function _restoreConfigData()
{
/* Restore global values */
foreach ($this->globalConfigValues as $configPath => $originalValue) {
$this->_setConfigValue($configPath, $originalValue);
}
$this->globalConfigValues = [];
/* Restore store-scoped values */
foreach ($this->storeConfigValues as $storeCode => $originalData) {
foreach ($originalData as $configPath => $originalValue) {
if (empty($storeCode)) {
$storeCode = null;
}
$this->setScopeConfigValue($configPath, $originalValue, ScopeInterface::SCOPE_STORES, $storeCode);
}
}
$this->storeConfigValues = [];
/* Restore website-scoped values */
foreach ($this->websiteConfigValues as $websiteCode => $originalData) {
foreach ($originalData as $configPath => $originalValue) {
if (empty($websiteCode)) {
$websiteCode = null;
}
$this->setScopeConfigValue($configPath, $originalValue, ScopeInterface::SCOPE_WEBSITES, $websiteCode);
}
}
$this->websiteConfigValues = [];
}
/**
* Handler for 'startTest' event
*
* @param TestCase $test
* @return void
*/
public function startTest(TestCase $test)
{
$this->_currentTest = $test;
$this->_assignConfigData($test);
}
/**
* Handler for 'endTest' event
*
* @param TestCase $test
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function endTest(TestCase $test)
{
$this->_currentTest = null;
$this->_restoreConfigData();
}
/**
* Reassign configuration data whenever application is reset
*
* @return void
*/
public function initStoreAfter()
{
/* process events triggered from within a test only */
if ($this->_currentTest) {
$this->_assignConfigData($this->_currentTest);
}
}
/**
* Returns config fixtures defined using Config attribute
*
* @param TestCase $test
* @return array
* @throws LocalizedException
*/
private function getConfigFixturesFromAttribute(TestCase $test): array
{
$parser = Bootstrap::getObjectManager()->get(ConfigFixtureParser::class);
$configs = [];
foreach ($parser->parse($test, ParserInterface::SCOPE_METHOD) as $data) {
$configs[] = sprintf(
'%s%s %s',
$data['scopeType'] === ScopeConfigInterface::SCOPE_TYPE_DEFAULT
? 'default/'
: ($data['scopeValue'] ?? 'current') . '_' . $data['scopeType'] . ' ',
$data['path'],
$data['value'],
);
}
return $configs;
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use Magento\TestFramework\Event\Param\Transaction;
use Magento\TestFramework\Fixture\Parser\DataFixtureAttributesParser;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Implementation of the @magentoDataFixture DocBlock annotation.
*/
class DataFixture extends AbstractDataFixture
{
public const ANNOTATION = 'magentoDataFixture';
/**
* Handler for 'startTestTransactionRequest' event
*
* @param TestCase $test
* @param Transaction $param
* @return void
*/
public function startTestTransactionRequest(TestCase $test, Transaction $param): void
{
$fixtures = $this->_getFixtures($test);
/* Start transaction before applying first fixture to be able to revert them all further */
if ($fixtures) {
if ($this->getDbIsolationState($test) !== ['disabled']) {
$param->requestTransactionStart();
} else {
$this->_applyFixtures($fixtures, $test);
}
}
}
/**
* Handler for 'endTestNeedTransactionRollback' event
*
* @param TestCase $test
* @param Transaction $param
* @return void
*/
public function endTestTransactionRequest(TestCase $test, Transaction $param): void
{
/* Isolate other tests from test-specific fixtures */
if ($this->_appliedFixtures && $this->_getFixtures($test)) {
if ($this->getDbIsolationState($test) !== ['disabled']) {
$param->requestTransactionRollback();
} else {
$this->_revertFixtures($test);
}
}
}
/**
* Handler for 'startTransaction' event
*
* @param TestCase $test
* @return void
*/
public function startTransaction(TestCase $test): void
{
$this->_applyFixtures($this->_getFixtures($test), $test);
}
/**
* Handler for 'rollbackTransaction' event
*
* @param TestCase $test
* @return void
*/
public function rollbackTransaction(): void
{
$this->_revertFixtures();
}
/**
* @inheritdoc
*/
protected function getAnnotation(): string
{
return self::ANNOTATION;
}
/**
* @inheritdoc
*/
protected function getParsers(): array
{
$parsers = [];
$parsers[] = Bootstrap::getObjectManager()->get(
\Magento\TestFramework\Fixture\Parser\DataFixture::class
);
return array_merge(
parent::getParsers(),
$parsers
);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Annotation;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Implementation of the @magentoDataFixtureBeforeTransaction DocBlock annotation
*/
class DataFixtureBeforeTransaction extends AbstractDataFixture
{
public const ANNOTATION = 'magentoDataFixtureBeforeTransaction';
/**
* Handler for 'startTest' event
*
* @param TestCase $test
*/
public function startTest(TestCase $test)
{
$fixtures = $this->_getFixtures($test);
if ($fixtures) {
$this->_applyFixtures($fixtures, $test);
}
}
/**
* Handler for 'endTest' event
*
* @param TestCase $test
*/
public function endTest(TestCase $test)
{
/* Isolate other tests from test-specific fixtures */
if ($this->_appliedFixtures && $this->_getFixtures($test)) {
$this->_revertFixtures($test);
}
}
/**
* @inheritdoc
*/
protected function getAnnotation(): string
{
return self::ANNOTATION;
}
/**
* @inheritdoc
*/
protected function getParsers(): array
{
$parsers = [];
$parsers[] = Bootstrap::getObjectManager()->create(
\Magento\TestFramework\Fixture\Parser\DataFixture::class,
[
'attributeClass' => \Magento\TestFramework\Fixture\DataFixtureBeforeTransaction::class
]
);
return array_merge(
parent::getParsers(),
$parsers
);
}
}
@@ -0,0 +1,149 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Fixture\DataFixtureFactory;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Fixture\RevertibleDataFixtureInterface;
use Magento\TestFramework\ScopeSwitcherInterface;
/**
* Apply and revert data fixtures
*/
class DataFixtureSetup
{
/**
* @param Registry $registry
* @param DataFixtureFactory $dataFixtureFactory
* @param ScopeSwitcherInterface $scopeSwitcher
*/
public function __construct(
private Registry $registry,
private DataFixtureFactory $dataFixtureFactory,
private ScopeSwitcherInterface $scopeSwitcher
) {
}
/**
* Applies data fixture and returns the result.
*
* @param array $fixture
* @return DataObject|null
* @throws LocalizedException
*/
public function apply(array $fixture): ?DataObject
{
$data = $this->resolveVariables($fixture['data'] ?? []);
$factory = $this->dataFixtureFactory->create($fixture['factory']);
if (isset($fixture['scope'])) {
$scope = DataFixtureStorageManager::getStorage()->get($fixture['scope']);
$fromScope = $this->scopeSwitcher->switch($scope);
try {
$result = $factory->apply($data);
} finally {
$this->scopeSwitcher->switch($fromScope);
}
} else {
$result = $factory->apply($data);
}
if ($result !== null && !empty($fixture['name'])) {
DataFixtureStorageManager::getStorage()->persist(
$fixture['name'],
$result
);
}
return $result;
}
/**
* Revert data fixture.
*
* @param array $fixture
*/
public function revert(array $fixture): void
{
$isSecureArea = $this->registry->registry('isSecureArea');
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
try {
$factory = $this->dataFixtureFactory->create($fixture['factory']);
if ($factory instanceof RevertibleDataFixtureInterface) {
$factory->revert($fixture['result'] ?? new DataObject());
}
} catch (NoSuchEntityException $exception) {
//ignore
} finally {
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', $isSecureArea);
}
}
/**
* Replace fixtures references in the data by their value
*
* Supported formats:
* - $fixture$
* - $fixture.attribute$
*
* @param array $data
* @return array
* @throws LocalizedException
*/
private function resolveVariables(array $data): array
{
foreach ($data as $key => $value) {
if (is_array($value)) {
$data[$key] = $this->resolveVariables($value);
} else {
if (is_string($value)) {
$value = $this->parseFixtureKeyValue($value);
if ($value) {
$data[$key] = $value;
}
}
}
if (is_string($key)) {
$newKey = $this->parseFixtureKeyValue($key);
if (is_string($newKey)) {
$value = $data[$key];
unset($data[$key]);
$data[$newKey] = $value;
}
}
}
return $data;
}
/**
* Parse either key or value of the fixture data
*
* @param string $data
* @return DataObject|mixed|void
* @throws LocalizedException
*/
private function parseFixtureKeyValue(string $data)
{
if (preg_match('/^\$\w+(\.\w+)?\$$/', $data)) {
list($fixtureName, $attribute) = array_pad(explode('.', trim($data, '$')), 2, null);
$fixtureData = DataFixtureStorageManager::getStorage()->get($fixtureName);
if (!$fixtureData) {
throw new \InvalidArgumentException("Unable to resolve fixture reference '$data'");
}
return $attribute ? $fixtureData->getDataUsingMethod($attribute) : $fixtureData;
}
return false;
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Annotation;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Event\Param\Transaction;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Implementation of the @magentoDbIsolation DocBlock annotation
*/
class DbIsolation
{
public const MAGENTO_DB_ISOLATION = 'magentoDbIsolation';
/**
* @var bool
*/
protected $_isIsolationActive = false;
/**
* Handler for 'startTestTransactionRequest' event
*
* @param TestCase $test
* @param Transaction $param
*/
public function startTestTransactionRequest(TestCase $test, Transaction $param)
{
$methodIsolation = $this->_getIsolation($test);
if ($this->_isIsolationActive) {
if ($methodIsolation === false) {
$param->requestTransactionRollback();
}
} elseif ($methodIsolation || ($methodIsolation === null && $this->_getIsolation($test))) {
$param->requestTransactionStart();
}
}
/**
* Handler for 'endTestTransactionRequest' event
*
* @param TestCase $test
* @param Transaction $param
*/
public function endTestTransactionRequest(TestCase $test, Transaction $param)
{
if ($this->_isIsolationActive && $this->_getIsolation($test)) {
$param->requestTransactionRollback();
}
}
/**
* Handler for 'startTransaction' event
*
* @param TestCase $test
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function startTransaction(TestCase $test)
{
$this->_isIsolationActive = true;
}
/**
* Handler for 'rollbackTransaction' event
*/
public function rollbackTransaction()
{
$this->_isIsolationActive = false;
}
/**
* Retrieve database isolation annotation value for the current scope.
* Possible results:
* NULL - annotation is not defined
* TRUE - annotation is defined as 'enabled'
* FALSE - annotation is defined as 'disabled'
*
* @param TestCase $test
* @return bool|null Returns NULL, if isolation is not defined for the current scope
*/
protected function _getIsolation(TestCase $test)
{
$state = null;
try {
$state = Bootstrap::getObjectManager()->get(DbIsolationState::class)->isEnabled($test);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse fixtures',
get_class($test),
$test->getName(false),
$exception
);
}
return $state;
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class DbIsolationState
{
/**
* Returns the db isolation state
*
* @param TestCase $test
* @return bool|null
* @throws LocalizedException
*/
public function isEnabled(TestCase $test): ?bool
{
$objectManager = Bootstrap::getObjectManager();
$parsers = $objectManager
->create(
\Magento\TestFramework\Annotation\Parser\Composite::class,
[
'parsers' => [
$objectManager->get(\Magento\TestFramework\Annotation\Parser\DbIsolation::class),
$objectManager->get(\Magento\TestFramework\Fixture\Parser\DbIsolation::class)
]
]
);
$values = $parsers->parse($test, ParserInterface::SCOPE_METHOD)
?: $parsers->parse($test, ParserInterface::SCOPE_CLASS);
if (count($values) > 1) {
throw new LocalizedException(
__('Only one "@%1" annotation is allowed per test', DbIsolation::MAGENTO_DB_ISOLATION)
);
}
return $values[0]['enabled'] ?? null;
}
}
@@ -0,0 +1,86 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use PHPUnit\Framework\Exception;
use ReflectionClass;
use ReflectionException;
class ExceptionHandler
{
/**
* Format exception message and throws PHPUnit\Framework\Exception
*
* @param string $message
* @param string $testClass
* @param string|null $testMethod
* @param \Throwable|null $previous
* @return void
*/
public static function handle(
string $message,
string $testClass,
string $testMethod = null,
\Throwable $previous = null
): void {
try {
$reflected = new ReflectionClass($testClass);
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
$e
);
}
$name = $testMethod;
if ($name && $reflected->hasMethod($name)) {
try {
$reflected = $reflected->getMethod($name);
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
$e
);
}
}
$location = sprintf(
"%s(%d): %s->%s()",
$reflected->getFileName(),
$reflected->getStartLine(),
$testClass,
$testMethod
);
$summary = '';
if ($previous) {
$exception = $previous;
do {
$summary .= PHP_EOL
. PHP_EOL
. 'Caused By: '
. $exception->getMessage()
. PHP_EOL
. $exception->getTraceAsString();
} while ($exception = $exception->getPrevious());
}
throw new Exception(
sprintf(
"%s\n#0 %s%s",
$message,
$location,
$summary
),
0,
$previous
);
}
}
@@ -0,0 +1,168 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use Magento\Catalog\Model\Indexer\Product\Price\DimensionModeConfiguration;
use Magento\Catalog\Model\Indexer\Product\Price\ModeSwitcher;
use Magento\Catalog\Model\Indexer\Product\Price\ModeSwitcherConfiguration;
use Magento\Catalog\Model\Indexer\Product\Price\Processor;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\App\Config;
use Magento\TestFramework\Fixture\ParserInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Implementation of the @magentoIndexerDimensionMode DocBlock annotation
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class IndexerDimensionMode
{
/** @var TypeListInterface */
private $cacheTypeList;
/** @var ScopeConfigInterface */
private $configReader;
/** @var ModeSwitcher */
private $modeSwitcher;
/** @var ObjectManagerInterface */
private $objectManager;
/** @var \Magento\TestFramework\Db\Mysql */
private $db;
/** @var bool */
private $isDimensionMode = false;
/**
* Restore db
*/
private function restoreDb()
{
$this->db = Bootstrap::getInstance()->getBootstrap()->getApplication()->getDbInstance();
$this->objectManager = Bootstrap::getObjectManager();
$this->db->restoreFromDbDump();
$this->cacheTypeList = $this->objectManager->get(TypeListInterface::class);
$this->cacheTypeList->cleanType('config');
$this->objectManager->get(Config::class)->clean();
}
/**
* Tries to set a Dimension mode if it wasn't set.
*
* @param string $mode
* @param TestCase $test
*
* @return void
* @throws \Exception
*/
private function setDimensionMode(string $mode, TestCase $test)
{
$this->objectManager = Bootstrap::getObjectManager();
$this->modeSwitcher = $this->objectManager->get(ModeSwitcher::class);
$this->configReader = $this->objectManager->get(ScopeConfigInterface::class);
$this->cacheTypeList = $this->objectManager->get(TypeListInterface::class);
$this->configReader->clean();
$previousMode = $this->configReader->getValue(ModeSwitcherConfiguration::XML_PATH_PRICE_DIMENSIONS_MODE) ?:
DimensionModeConfiguration::DIMENSION_NONE;
if ($previousMode !== $mode) {
//Create new tables and move data
$this->modeSwitcher->switchMode($mode, $previousMode);
$this->objectManager->get(Config::class)->clean();
} else {
ExceptionHandler::handle(
'Dimensions mode for indexer has not been changed',
get_class($test),
$test->getName(false)
);
}
}
/**
* Handler for 'startTest' event
*
* @param TestCase $test
* @return void
* @throws \Exception
*/
public function startTest(TestCase $test)
{
$values = [];
try {
$values = $this->parse($test);
} catch (\Throwable $exception) {
ExceptionHandler::handle(
'Unable to parse fixtures',
get_class($test),
$test->getName(false),
$exception
);
}
if ($values) {
$dbIsolation = Bootstrap::getObjectManager()->get(DbIsolationState::class)->isEnabled($test);
if ($dbIsolation) {
ExceptionHandler::handle(
'@magentoDbIsolation must be disabled when using @magentoIndexerDimensionMode',
get_class($test),
$test->getName(false)
);
}
if ($values[0]['indexer'] === Processor::INDEXER_ID) {
$this->isDimensionMode = true;
$this->setDimensionMode($values[0]['dimension'], $test);
}
}
}
/**
* Handler for 'endTest' event
*
* @return void
*/
public function endTest()
{
if ($this->isDimensionMode) {
$this->restoreDb();
$this->isDimensionMode = false;
}
}
/**
* Returns IndexerDimensionMode fixtures configuration
*
* @param TestCase $test
* @return array
* @throws LocalizedException
*/
private function parse(TestCase $test): array
{
$objectManager = Bootstrap::getObjectManager();
$parsers = $objectManager
->create(
\Magento\TestFramework\Annotation\Parser\Composite::class,
[
'parsers' => [
$objectManager->get(\Magento\TestFramework\Annotation\Parser\IndexerDimensionMode::class),
$objectManager->get(\Magento\TestFramework\Fixture\Parser\IndexerDimensionMode::class)
]
]
);
return $parsers->parse($test, ParserInterface::SCOPE_METHOD)
?: $parsers->parse($test, ParserInterface::SCOPE_CLASS);
}
}
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class AppArea implements ParserInterface
{
/**
* @var string
*/
private const ANNOTATION = 'magentoAppArea';
/**
* List of allowed areas.
*
* @var array
*/
private const ALLOWED_AREAS = [
\Magento\Framework\App\Area::AREA_GLOBAL,
\Magento\Framework\App\Area::AREA_ADMINHTML,
\Magento\Framework\App\Area::AREA_FRONTEND,
\Magento\Framework\App\Area::AREA_WEBAPI_REST,
\Magento\Framework\App\Area::AREA_WEBAPI_SOAP,
\Magento\Framework\App\Area::AREA_CRONTAB,
\Magento\Framework\App\Area::AREA_GRAPHQL
];
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$values = [];
foreach ($annotations[$scope][self::ANNOTATION] ?? [] as $value) {
if (!in_array($value, self::ALLOWED_AREAS, true)) {
throw new LocalizedException(
__(
"Invalid annotation format: @%1 %2. The valid format is: @%1 [%3].",
self::ANNOTATION,
$value,
implode('|', self::ALLOWED_AREAS)
)
);
}
$values[] = ['area' => $value];
}
return $values;
}
}
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class AppIsolation implements ParserInterface
{
/**
* @var string
*/
private const ANNOTATION = 'magentoAppIsolation';
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$values = [];
foreach ($annotations[$scope][self::ANNOTATION] ?? [] as $value) {
if (!in_array($value, ['enabled', 'disabled'])) {
throw new LocalizedException(
__(
"Invalid annotation format: @%1 %2. The valid format is: @%1 enabled|disabled.",
self::ANNOTATION,
$value
)
);
}
$values[] = ['enabled' => $value === 'enabled'];
}
return $values;
}
}
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class Cache implements ParserInterface
{
/**
* @var string
*/
private const ANNOTATION = 'magentoCache';
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$values = [];
foreach ($annotations[$scope][self::ANNOTATION] ?? [] as $value) {
if (!preg_match('/^([a-z_]+)\s(enabled|disabled)$/', $value, $matches)) {
throw new LocalizedException(
__(
"Invalid annotation format: @%1 %2. The valid format is: @%1 [<type>|all] [enabled|disabled].",
self::ANNOTATION,
$value
)
);
}
$values[] = ['type' => $matches[1], 'status' => $matches[2] === 'enabled'];
}
return $values;
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class ComponentsDir implements ParserInterface
{
/**
* @var string
*/
private const ANNOTATION = 'magentoComponentsDir';
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$values = [];
foreach ($annotations[$scope][self::ANNOTATION] ?? [] as $value) {
$values[] = ['path' => $value];
}
return $values;
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class Composite implements ParserInterface
{
public const STRATEGY_MERGE = 0;
public const STRATEGY_REPLACE = 1;
/**
* @var ParserInterface[]
*/
private array $parsers;
/**
* @var string
*/
private int $strategy;
/**
* @param ParserInterface[] $parsers
* @param int $strategy
*/
public function __construct(
array $parsers,
int $strategy = self::STRATEGY_MERGE
) {
$this->parsers = $parsers;
$this->strategy = $strategy;
}
/**
* @inheritdoc
*/
public function parse(TestCase $testCase, string $scope)
{
$results = [];
foreach ($this->parsers as $parser) {
$results[] = $parser->parse($testCase, $scope);
}
return $this->strategy === self::STRATEGY_MERGE
? array_merge(...$results)
: (array_reverse(array_filter($results))[0] ?? []);
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class DataFixture implements ParserInterface
{
/**
* @var string
*/
private string $annotation;
/**
* @param string $annotation
*/
public function __construct(
string $annotation
) {
$this->annotation = $annotation;
}
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$fixtures = [];
foreach ($annotations[$scope][$this->annotation] ?? [] as $fixture) {
list($factory, $extraParams) = array_pad(array_values(array_filter(explode(' ', $fixture, 2))), 2, '');
if (str_contains($factory, '\\') && !is_callable($factory)) {
if (class_exists($factory)) {
throw new LocalizedException(
__(
'Support for fixture class %1 in data fixture annotation was dropped' .
' in favor to data fixture attribute. Please see documentation',
$factory
)
);
}
throw new LocalizedException(
__(
'Data Fixture annotation expects argument #1 to be the fixture filename or a callable,' .
' %1 given',
$factory
)
);
}
if ($extraParams) {
throw new LocalizedException(
__(
'Data Fixture annotation expects only one argument: %1',
$fixture
)
);
}
$fixtures[] = [
'name' => null,
'factory' => $factory,
'data' => [],
];
}
return $fixtures;
}
}
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class DbIsolation implements ParserInterface
{
/**
* @var string
*/
private const ANNOTATION = 'magentoDbIsolation';
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$values = [];
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
foreach ($annotations[$scope][self::ANNOTATION] ?? [] as $value) {
if (!in_array($value, ['enabled', 'disabled'])) {
throw new LocalizedException(
__(
"Invalid annotation format: @%1 %2. The valid format is: @%1 enabled|disabled.",
self::ANNOTATION,
$value
)
);
}
$values[] = ['enabled' => $value === 'enabled'];
}
return $values;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation\Parser;
use Magento\Framework\Exception\LocalizedException;
use Magento\TestFramework\Annotation\TestCaseAnnotation;
use Magento\TestFramework\Fixture\ParserInterface;
use PHPUnit\Framework\TestCase;
class IndexerDimensionMode implements ParserInterface
{
/**
* @var string
*/
private const ANNOTATION = 'magentoIndexerDimensionMode';
/**
* @inheritdoc
*/
public function parse(TestCase $test, string $scope): array
{
$annotations = TestCaseAnnotation::getInstance()->getAnnotations($test);
$values = [];
foreach ($annotations[$scope][self::ANNOTATION] ?? [] as $value) {
$args = explode(' ', $value);
if (count($args) !== 2) {
throw new LocalizedException(
__(
"Invalid annotation format: @%1 %2. The valid format is: @%1 <indexer> <dimension>.",
self::ANNOTATION,
$value
)
);
}
$values[] = ['indexer' => $args[0], 'dimension' => $args[1]];
}
return $values;
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Annotation;
use PHPUnit\Framework\TestCase;
use PHPUnit\Util\Test as TestUtil;
/**
* Returns annotations for given testcase.
*/
class TestCaseAnnotation
{
/**
* @var TestCaseAnnotation
*/
private static $instance;
/**
* Get instance of test case annotation access service.
*
* @return TestCaseAnnotation
*/
public static function getInstance(): TestCaseAnnotation
{
return self::$instance ?? self::$instance = new TestCaseAnnotation();
}
/**
* Get annotations for the given test case.
*
* @param TestCase $testCase
*
* @return array
*/
public function getAnnotations(TestCase $testCase): array
{
return TestUtil::parseTestMethodAnnotations(
get_class($testCase),
$testCase->getName(false)
);
}
}
@@ -0,0 +1,199 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Annotation;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ResourceConnection;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\AssertionFailedError;
/**
* Validates tests isolation. Makes sure that test does not keep exceed data in DB.
*/
class TestsIsolation
{
/**
* This variable was created to keep initial data cached
*
* @var array
*/
private $dbTableState = [];
/**
* @var string[]
*/
private $testTypesToCheckIsolation = [
'integration',
];
/**
* @var int
*/
private $isolationLevel = 0;
/**
* @var string[]
*/
private $dbStateTables = [
'catalog_product_entity',
'eav_attribute',
'catalog_category_entity',
'eav_attribute_set',
'store',
'store_website',
'url_rewrite'
];
/**
* Pull data from specific table
*
* @param string $table
* @return array
*/
private function pullDbState(string $table): array
{
// phpcs:ignore Magento2.PHP.AutogeneratedClassNotInConstructor
$resource = ObjectManager::getInstance()->get(ResourceConnection::class);
$connection = $resource->getConnection();
$select = $connection->select()->from($table);
return $connection->fetchAll($select);
}
/**
* Create DB snapshot before test run.
*
* @param TestCase $test
* @param array|null $dbIsolationState
* @return void
*/
public function createDbSnapshot(TestCase $test, ?array $dbIsolationState): void
{
if (null !== $dbIsolationState
&& ($dbIsolationState !== ['enabled'])
&& ($this->checkIsolationRequired($test))
) {
++$this->isolationLevel;
if ($this->isolationLevel === 1) {
$this->saveDbStateBeforeTestRun($test);
}
}
}
/**
* Check DB isolation when test ended.
*
* @param TestCase $test
* @param array|null $dbIsolationState
* @return void
*/
public function checkTestIsolation(TestCase $test, ?array $dbIsolationState): void
{
if (null !== $dbIsolationState
&& ($dbIsolationState !== ['enabled'])
&& ($this->checkIsolationRequired($test))
) {
--$this->isolationLevel;
if ($this->isolationLevel === 1) {
$this->checkResidualData($test);
}
}
}
/**
* Saving DB snapshot before fixtures applying.
*
* @param TestCase $test
* @return void
*/
private function saveDbStateBeforeTestRun(TestCase $test): void
{
try {
if (empty($this->dbTableState)) {
foreach ($this->dbStateTables as $table) {
$this->dbTableState[$table] = $this->pullDbState($table);
}
}
} catch (\Throwable $e) {
$test->getTestResultObject()->addFailure($test, new AssertionFailedError($e->getMessage()), 0);
}
}
/**
* Check if test isolation is required for given scope of tests.
*
* @param TestCase $test
* @return bool
*/
private function checkIsolationRequired(TestCase $test): bool
{
$isRequired = false;
if (!$test->getTestResultObject()) {
return $isRequired;
}
$passedClasses = $test->getTestResultObject()->passedClasses();
if ($passedClasses) {
$testFilename = current($passedClasses);
foreach ($this->testTypesToCheckIsolation as $testType) {
if (false !== strpos($testFilename, \sprintf('/dev/tests/%s/', $testType))) {
$isRequired = true;
break;
}
}
}
return $isRequired;
}
/**
* Check if there's residual data in DB after test execution.
*
* @param TestCase $test
* @return void
*/
private function checkResidualData(TestCase $test): void
{
$isolationProblem = [];
foreach ($this->dbTableState as $table => $isolationData) {
try {
$diff = $this->dataDiff($isolationData, $this->pullDbState($table));
if (!empty($diff)) {
$isolationProblem[$table] = $diff;
}
} catch (\Throwable $e) {
$test->getTestResultObject()->addFailure($test, new AssertionFailedError($e->getMessage()), 0);
}
}
if (!empty($isolationProblem)) {
$test->getTestResultObject()->addFailure(
$test,
new AssertionFailedError(
"There was a problem with isolation: " . var_export($isolationProblem, true)
),
0
);
}
}
/**
* Compare data difference for m-dimensional array
*
* @param array $dataBefore
* @param array $dataAfter
* @return array
*/
private function dataDiff(array $dataBefore, array $dataAfter): array
{
$diff = [];
if (count($dataBefore) !== count($dataAfter)) {
$diff = \array_slice($dataAfter, count($dataBefore));
}
return $diff;
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Api\Config\Reader;
/**
* Config file resolver for extension_attributes.xml files, which reads configs defined in tests.
*
* It is necessary because these configs are used during extension classes generation. And thus it is impossible
* to add customizations to the configs in concrete test, because respective extension class is already generated
* and loaded by the PHP. It is impossible to reload definition of the class, which is already loaded.
*/
class FileResolver extends \Magento\Framework\App\Config\FileResolver
{
/**
* {@inheritdoc}
*/
public function get($filename, $scope)
{
return $this->merge(parent::get($filename, $scope), $this->getIntegrationTestConfigFiles());
}
/**
* Merge arrays or \Magento\Framework\Config\FileIterator into an array
*
* @param mixed $array1
* @param mixed $array2,...
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
protected function merge($array1, $array2)
{
$arguments = func_get_args();
$arraysToMerge = [];
foreach ($arguments as $argument) {
$arraysToMerge[] = is_array($argument) ? $argument : $this->convertToArray($argument);
}
return call_user_func_array('array_merge', $arraysToMerge);
}
/**
* Return a list of test config files
*
* Looks for config files located at
* dev/tests/integration/testsuite/Magento/*\/etc/extension_attributes.xml
* dev/tests/integration/testsuite/Magento/Framework/*\/etc/extension_attributes.xml
*
* @return array
*/
protected function getIntegrationTestConfigFiles()
{
$filePatterns = [
'dev/tests/integration/testsuite/Magento/*/etc/extension_attributes.xml',
'dev/tests/integration/testsuite/Magento/Framework/*/etc/extension_attributes.xml'
];
$filesArray = [];
foreach ($filePatterns as $pattern) {
foreach (glob(BP . '/' . $pattern) as $file) {
$content = file_get_contents($file);
if ($content) {
$filesArray[$file] = $content;
}
}
}
return $filesArray;
}
/**
* Convert an argument to an array
*
* If it's not FileIterator instance, then empty array will be returned
*
* @param mixed $argument
* @return array
*/
protected function convertToArray($argument)
{
$resultArray = [];
if ($argument instanceof \Magento\Framework\Config\FileIterator) {
$resultArray = $argument->toArray();
}
return $resultArray;
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Application configuration object. Used to access configuration when application is initialized and installed.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\App;
use Magento\Framework\App\Config\ScopeCodeResolver;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\TestFramework\ObjectManager;
/**
* @inheritdoc
*/
class Config extends \Magento\Framework\App\Config
{
/**
* @var DataObject[]
*/
private $data;
/**
* @var ScopeCodeResolver
*/
private $scopeCodeResolver;
/**
* Initialize data object with all settings data
*
* @param array $data
* @param string $configType
* @return void
*/
private function setData(array $data, $configType)
{
$this->data[$configType] = new DataObject($data);
}
/**
* Retrieve Scope Code Resolver
*
* @return ScopeCodeResolver
*/
private function getScopeCodeResolver()
{
if (!$this->scopeCodeResolver) {
$this->scopeCodeResolver = ObjectManager::getInstance()->get(ScopeCodeResolver::class);
}
return $this->scopeCodeResolver;
}
/**
* Set config value in the corresponding config scope
*
* @param string $path
* @param mixed $value
* @param string $scope
* @param null|string $scopeCode
* @return void
*/
public function setValue(
$path,
$value,
$scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
$scopeCode = null
) {
$result = $this->get('system');
if ($scope === 'store') {
$scope = 'stores';
} elseif ($scope === 'website') {
$scope = 'websites';
}
if (empty($scopeCode)) {
$scopeCode = $this->getScopeCodeResolver()->resolve($scope, $scopeCode);
}
$keys = explode('/', $path);
if ($scope !== ScopeConfigInterface::SCOPE_TYPE_DEFAULT) {
$searchKeys = array_merge([$scope, $scopeCode], $keys);
} else {
$searchKeys = array_merge([$scope], $keys);
}
$this->updateResult($searchKeys, $result, $value);
$this->setData($result, 'system');
}
/**
* Recursively update results in global variable, which hold configs
*
* @param array $keys
* @param array $result
* @param mixed $value
* @return void
*/
private function updateResult(array $keys, & $result, $value)
{
$key = array_shift($keys);
if (empty($keys)) {
$result[$key] = $value;
} else {
$this->updateResult($keys, $result[$key], $value);
}
}
/**
* Flush all muted settings
*
* @return void
*/
public function clean()
{
$this->data = null;
$this->scopeCodeResolver = null;
parent::clean();
}
/**
* @inheritdoc
*/
public function get($configType, $path = null, $default = null)
{
$path = $path === null ? '' : $path;
if (!isset($this->data[$configType]) || $this->data[$configType]->getData($path) === null) {
return parent::get($configType, $path, $default);
}
return $this->data[$configType]->getData($path);
}
}
@@ -0,0 +1,17 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\App;
use Magento\TestFramework\App\ObjectManager\Environment\Developer;
class EnvironmentFactory extends \Magento\Framework\App\EnvironmentFactory
{
public function createEnvironment()
{
return new Developer($this);
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\App;
class Filesystem extends \Magento\Framework\Filesystem
{
/**
* Overridden paths
*
* @var string[]
*/
private $paths = [];
/**
* {@inheritdoc}
*/
protected function getDirPath($code)
{
return $this->getOverriddenPath($code, parent::getDirPath($code));
}
/**
* Overrides a path to directory for testing purposes
*
* @param string $code
* @param string $value
* @return void
*/
public function overridePath($code, $value)
{
$this->paths[$code] = str_replace('\\', '/', $value);
unset($this->readInstances[$code]);
unset($this->writeInstances[$code]);
}
/**
* Looks up an overridden directory path
*
* @param string $code
* @param string $original
* @return string
*/
private function getOverriddenPath($code, $original)
{
if (array_key_exists($code, $this->paths)) {
return $this->paths[$code];
}
return $original;
}
}
@@ -0,0 +1,77 @@
<?php
/**
* Application configuration object. Used to access configuration when application is installed.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\App;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\TestFramework\ObjectManager;
/**
* @inheritdoc
*/
class MutableScopeConfig implements MutableScopeConfigInterface
{
/**
* @var Config
*/
private $testAppConfig;
/**
* @inheritdoc
*/
public function isSetFlag($path, $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeCode = null)
{
return $this->getTestAppConfig()->isSetFlag($path, $scopeType, $scopeCode);
}
/**
* @inheritdoc
*/
public function getValue($path, $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeCode = null)
{
return $this->getTestAppConfig()->getValue($path, $scopeType, $scopeCode);
}
/**
* @inheritdoc
*/
public function setValue(
$path,
$value,
$scopeType = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
$scopeCode = null
) {
return $this->getTestAppConfig()->setValue($path, $value, $scopeType, $scopeCode);
}
/**
* Clean app config cache
*
* @param string|null $type
* @return void
*/
public function clean()
{
$this->getTestAppConfig()->clean();
}
/**
* Retrieve test app config instance
*
* @return \Magento\TestFramework\App\Config
*/
private function getTestAppConfig()
{
if (!$this->testAppConfig) {
$this->testAppConfig = ObjectManager::getInstance()->get(ScopeConfigInterface::class);
}
return $this->testAppConfig;
}
}
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\App\ObjectManager\Environment;
class Developer extends \Magento\Framework\App\ObjectManager\Environment\Developer
{
public function getDiConfig()
{
if (!$this->config) {
$this->config = new \Magento\TestFramework\ObjectManager\Config(
$this->envFactory->getRelations(),
$this->envFactory->getDefinitions()
);
}
return $this->config;
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\App;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\TestFramework\ObjectManager;
/**
* @inheritdoc
*/
class ReinitableConfig extends MutableScopeConfig implements ReinitableConfigInterface
{
/**
* @var Config
*/
private $testAppConfig;
/**
* {@inheritdoc}
*/
public function reinit()
{
$this->getTestScopeConfig()->clean();
return $this;
}
/**
* Retrieve Test Scope Config
*
* @return Config
*/
public function getTestScopeConfig()
{
if (!$this->testAppConfig) {
$this->testAppConfig = ObjectManager::getInstance()->get(Config::class);
}
return $this->testAppConfig;
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* App State class for integration tests framework
*/
namespace Magento\TestFramework\App;
class State extends \Magento\Framework\App\State
{
/**
* {@inheritdoc}
*/
public function getAreaCode()
{
return $this->_areaCode;
}
/**
* {@inheritdoc}
*/
public function setAreaCode($code)
{
$this->_areaCode = $code;
$this->_configScope->setCurrentScope($code);
}
/**
* {@inheritdoc}
*/
public function setMode($mode)
{
$this->_appMode = $mode;
}
}
@@ -0,0 +1,828 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\DeploymentConfig\Reader;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Autoload\AutoloaderInterface;
use Magento\Framework\Config\ConfigOptionsListConstants;
use Magento\Framework\Filesystem\Glob;
use Magento\Framework\Mail;
use Magento\TestFramework;
use Magento\TestFramework\Fixture\Data\ProcessorInterface;
use Psr\Log\LoggerInterface;
use DomainException;
/**
* Encapsulates application installation, initialization and uninstall.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyFields)
*/
class Application
{
/**
* Default application area.
*/
public const DEFAULT_APP_AREA = 'global';
/**
* DB vendor adapter instance.
*
* @var TestFramework\Db\AbstractDb
*/
protected $_db;
/**
* Shell command executor.
*
* @var \Magento\Framework\Shell
*/
protected $_shell;
/**
* Configuration file that contains installation parameters.
*
* @var string
*/
private $installConfigFile;
/**
* Configuration file that contains array of post-installation commands to run through bin/magento CLI tool.
*
* @var string|null
*/
private $postInstallSetupCommandsFile;
/**
* The loaded installation parameters.
*
* @var array
*/
protected $installConfig;
/**
* The loaded post-installation commands.
*
* @var array
*/
private $postInstallSetupCommands;
/**
* Application *.xml configuration files.
*
* @var array
*/
protected $_globalConfigDir;
/**
* Installation destination directory.
*
* @var string
*/
protected $installDir;
/**
* Installation destination directory with configuration files.
*
* @var string
*/
protected $_configDir;
/**
* Application initialization parameters.
*
* @var array
*/
protected $_initParams = [];
/**
* Mode to run application.
*
* @var string
*/
protected $_appMode;
/**
* Application area.
*
* @var null
*/
protected $_appArea = null;
/**
* Primary DI Config.
*
* @var array
*/
protected $_primaryConfigData = [];
/**
* Object manager factory.
*
* @var TestFramework\ObjectManagerFactory
*/
protected $_factory;
/**
* Directory list.
*
* @var DirectoryList
*/
protected $dirList;
/**
* Config file for integration tests.
*
* @var string
*/
private $globalConfigFile;
/**
* Defines whether load test extension attributes or not.
*
* @var bool
*/
private $loadTestExtensionAttributes;
/**
* @var bool
*/
protected $dumpDb = true;
/**
* @var bool
*/
protected $canLoadArea = true;
/**
* @var bool
*/
protected $canInstallSequence = true;
/**
* Constructor.
*
* @param \Magento\Framework\Shell $shell
* @param string $installDir
* @param string $installConfigFile
* @param string $globalConfigFile
* @param string $globalConfigDir
* @param string $appMode
* @param AutoloaderInterface $autoloadWrapper
* @param bool|null $loadTestExtensionAttributes
* @param string|null $postInstallSetupCommandsFile
*/
public function __construct(
\Magento\Framework\Shell $shell,
$installDir,
$installConfigFile,
$globalConfigFile,
$globalConfigDir,
$appMode,
AutoloaderInterface $autoloadWrapper,
$loadTestExtensionAttributes = false,
$postInstallSetupCommandsFile = null
) {
if (getcwd() != BP . '/dev/tests/integration') {
// phpcs:ignore Magento2.Functions.DiscouragedFunction
chdir(BP . '/dev/tests/integration');
}
$this->_shell = $shell;
$this->installConfigFile = $installConfigFile;
$this->postInstallSetupCommandsFile = $postInstallSetupCommandsFile;
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$this->_globalConfigDir = realpath($globalConfigDir);
$this->_appMode = $appMode;
$this->installDir = $installDir;
$this->loadTestExtensionAttributes = $loadTestExtensionAttributes;
$customDirs = $this->getCustomDirs();
$this->dirList = new DirectoryList(BP, $customDirs);
\Magento\Framework\Autoload\Populator::populateMappings(
$autoloadWrapper,
$this->dirList
);
$this->_initParams = [
\Magento\Framework\App\Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS => $customDirs,
\Magento\Framework\App\State::PARAM_MODE => $appMode
];
$driverPool = new \Magento\Framework\Filesystem\DriverPool();
$configFilePool = new \Magento\Framework\Config\File\ConfigFilePool();
$this->_factory = new TestFramework\ObjectManagerFactory($this->dirList, $driverPool, $configFilePool);
$this->_configDir = $this->dirList->getPath(DirectoryList::CONFIG);
$this->globalConfigFile = $globalConfigFile;
}
/**
* Retrieve the database adapter instance.
*
* @return TestFramework\Db\AbstractDb
*/
public function getDbInstance()
{
if (null === $this->_db) {
if ($this->isInstalled()) {
$configPool = new \Magento\Framework\Config\File\ConfigFilePool();
$driverPool = new \Magento\Framework\Filesystem\DriverPool();
$reader = new Reader($this->dirList, $driverPool, $configPool);
$deploymentConfig = new DeploymentConfig($reader, []);
$host = $deploymentConfig->get(
ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT .
'/' . ConfigOptionsListConstants::KEY_HOST
);
$user = $deploymentConfig->get(
ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT .
'/' . ConfigOptionsListConstants::KEY_USER
);
$password = $deploymentConfig->get(
ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT .
'/' . ConfigOptionsListConstants::KEY_PASSWORD
);
$dbName = $deploymentConfig->get(
ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT .
'/' . ConfigOptionsListConstants::KEY_NAME
);
} else {
$installConfig = $this->getInstallConfig();
$host = $installConfig['db-host'];
$user = $installConfig['db-user'];
$password = $installConfig['db-password'];
$dbName = $installConfig['db-name'];
}
$this->_db = new Db\Mysql(
$host,
$user,
$password,
$dbName,
$this->getTempDir(),
$this->_shell
);
}
return $this->_db;
}
/**
* Gets installation parameters.
*
* @return array
*/
protected function getInstallConfig()
{
if (null === $this->installConfig) {
// phpcs:ignore Magento2.Security.IncludeFile
$this->installConfig = include $this->installConfigFile;
$this->installConfig['use-secure'] = '0';
$this->installConfig['use-secure-admin'] = '0';
}
return $this->installConfig;
}
/**
* Gets post-installation commands.
*
* @return array
*/
protected function getPostInstallSetupCommands()
{
if (null === $this->postInstallSetupCommandsFile) {
$this->postInstallSetupCommands = [];
} elseif (null === $this->postInstallSetupCommands) {
// phpcs:ignore Magento2.Security.IncludeFile
$this->postInstallSetupCommands = include $this->postInstallSetupCommandsFile;
}
return $this->postInstallSetupCommands;
}
/**
* Gets deployment configuration path.
*
* @return string
*/
private function getLocalConfig()
{
return $this->_configDir . '/config.php';
}
/**
* Get path to temporary directory.
*
* @return string
*/
public function getTempDir()
{
return $this->installDir;
}
/**
* Retrieve application initialization parameters.
*
* @return array
*/
public function getInitParams()
{
return $this->_initParams;
}
/**
* Weather the application is installed or not.
*
* @return bool
*/
public function isInstalled()
{
// phpcs:ignore Magento2.Functions.DiscouragedFunction
return is_file($this->getLocalConfig());
}
/**
* Create logger instance and rewrite already exist one in ObjectManager.
*
* @return \Psr\Log\LoggerInterface
*/
private function initLogger()
{
$objectManager = Helper\Bootstrap::getObjectManager();
/** @var \Psr\Log\LoggerInterface $logger */
$logger = $objectManager->create(
TestFramework\ErrorLog\Logger::class,
[
'name' => 'integration-tests',
'handlers' => [
'system' => $objectManager->create(
\Magento\Framework\Logger\Handler\System::class,
[
'exceptionHandler' => $objectManager->create(
\Magento\Framework\Logger\Handler\Exception::class,
['filePath' => $this->installDir]
),
'filePath' => $this->installDir
]
),
'debug' => $objectManager->create(
\Magento\Framework\Logger\Handler\Debug::class,
['filePath' => $this->installDir]
),
]
]
);
$objectManager->removeSharedInstance(LoggerInterface::class, true);
$objectManager->addSharedInstance($logger, LoggerInterface::class, true);
$objectManager->removeSharedInstance(TestFramework\ErrorLog\Logger::class, true);
$objectManager->addSharedInstance($logger, TestFramework\ErrorLog\Logger::class, true);
return $logger;
}
/**
* Initialize application
*
* @param array $overriddenParams
* @return void
*/
public function initialize($overriddenParams = [])
{
$overriddenParams[\Magento\Framework\App\State::PARAM_MODE] = $this->_appMode;
$overriddenParams = $this->_customizeParams($overriddenParams);
$directories = isset($overriddenParams[\Magento\Framework\App\Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS])
? $overriddenParams[\Magento\Framework\App\Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS]
: [];
$directoryList = new DirectoryList(BP, $directories);
/** @var TestFramework\ObjectManager $objectManager */
$objectManager = Helper\Bootstrap::getObjectManager();
if (!$objectManager) {
$objectManager = $this->_factory->create($overriddenParams);
$objectManager->addSharedInstance(
$directoryList,
DirectoryList::class
);
$objectManager->addSharedInstance(
$directoryList,
\Magento\Framework\Filesystem\DirectoryList::class
);
} else {
$objectManager = $this->_factory->restore($objectManager, $directoryList, $overriddenParams);
}
/** @var TestFramework\App\Filesystem $filesystem */
$filesystem = $objectManager->get(TestFramework\App\Filesystem::class);
$objectManager->removeSharedInstance(\Magento\Framework\Filesystem::class);
$objectManager->addSharedInstance($filesystem, \Magento\Framework\Filesystem::class);
Helper\Bootstrap::setObjectManager($objectManager);
$this->initLogger();
$sequenceBuilder = $objectManager->get(TestFramework\Db\Sequence\Builder::class);
$objectManager->addSharedInstance($sequenceBuilder, \Magento\SalesSequence\Model\Builder::class);
$objectManagerConfiguration = [
'preferences' => [
\Magento\Framework\App\State::class => TestFramework\App\State::class,
Mail\TransportInterface::class => TestFramework\Mail\TransportInterfaceMock::class,
Mail\Template\TransportBuilder::class => TestFramework\Mail\Template\TransportBuilderMock::class,
ProcessorInterface::class => \Magento\TestFramework\Fixture\Data\CompositeProcessor::class,
]
];
if ($this->loadTestExtensionAttributes) {
$objectManagerConfiguration = array_merge(
$objectManagerConfiguration,
[
\Magento\Framework\Api\ExtensionAttribute\Config\Reader::class => [
'arguments' => [
'fileResolver' => [
'instance' => TestFramework\Api\Config\Reader\FileResolver::class
],
],
],
]
);
}
$objectManager->configure($objectManagerConfiguration);
/** Register event observer of Integration Framework */
/** @var \Magento\Framework\Event\Config\Data $eventConfigData */
$eventConfigData = $objectManager->get(\Magento\Framework\Event\Config\Data::class);
$eventConfigData->merge(
[
'core_app_init_current_store_after' => [
'integration_tests' => [
'instance' => TestFramework\Event\Magento::class,
'name' => 'integration_tests'
]
]
]
);
if ($this->canLoadArea) {
$this->loadArea(TestFramework\Application::DEFAULT_APP_AREA);
}
TestFramework\Helper\Bootstrap::getObjectManager()->configure(
$objectManager->get(\Magento\Framework\ObjectManager\DynamicConfigInterface::class)->getConfiguration()
);
\Magento\Framework\Phrase::setRenderer(
$objectManager->get(\Magento\Framework\Phrase\Renderer\Placeholder::class)
);
if ($this->canInstallSequence) {
/** @var TestFramework\Db\Sequence $sequence */
$sequence = $objectManager->get(\Magento\TestFramework\Db\Sequence::class);
$sequence->generateSequences();
}
$objectManager->create(\Magento\TestFramework\Config::class, ['configPath' => $this->globalConfigFile])
->rewriteAdditionalConfig();
}
/**
* Reset and initialize again an already installed application
*
* @param array $overriddenParams
* @return void
*/
public function reinitialize(array $overriddenParams = [])
{
$this->_resetApp();
$this->initialize($overriddenParams);
}
/**
* Run application normally, but with encapsulated initialization options
*
* @return void
*/
public function run()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\App\Http $app */
$app = $objectManager->get(\Magento\Framework\App\Http::class);
$response = $app->launch();
$response->sendResponse();
}
/**
* Create install dir for integration framework
*
* @return void
*/
public function createInstallDir()
{
$this->_ensureDirExists($this->installDir);
$this->_ensureDirExists($this->_configDir);
$this->copyAppConfigFiles();
}
/**
* Cleanup both the database and the file system
*
* @return void
*/
public function cleanup()
{
$this->createInstallDir();
/**
* @see \Magento\Setup\Mvc\Bootstrap\InitParamListener::BOOTSTRAP_PARAM
*/
$this->_shell->execute(
PHP_BINARY . ' -f %s setup:uninstall --no-interaction -vvv -n --magento-init-params=%s',
[BP . '/bin/magento', $this->getInitParamsQuery()]
);
}
/**
* Install an application
*
* @param bool $cleanup
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function install($cleanup)
{
$dirs = \Magento\Framework\App\Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS;
$this->_ensureDirExists($this->installDir);
$this->_ensureDirExists($this->_configDir);
$this->_ensureDirExists($this->_initParams[$dirs][DirectoryList::PUB][DirectoryList::PATH]);
$this->_ensureDirExists($this->_initParams[$dirs][DirectoryList::MEDIA][DirectoryList::PATH]);
$this->_ensureDirExists($this->_initParams[$dirs][DirectoryList::STATIC_VIEW][DirectoryList::PATH]);
$this->_ensureDirExists($this->_initParams[$dirs][DirectoryList::VAR_DIR][DirectoryList::PATH]);
$this->copyAppConfigFiles();
$this->copyGlobalConfigFile();
$installParams = $this->getInstallCliParams();
$installParams['--no-interaction'] = true;
// performance optimization: restore DB from last good dump to make installation on top of it (much faster)
// do not restore from the database if the cleanup option is set to ensure we have a clean DB to test on
$db = $this->getDbInstance();
if ($db->isDbDumpExists() && !$cleanup) {
$db->restoreFromDbDump();
}
// run install script
$this->_shell->execute(
PHP_BINARY . ' -f %s setup:install -vvv ' . implode(' ', array_keys($installParams)),
array_merge([BP . '/bin/magento'], array_values($installParams))
);
$this->runPostInstallCommands();
// enable only specified list of caches
$initParamsQuery = $this->getInitParamsQuery();
$this->_shell->execute(
PHP_BINARY . ' -f %s cache:disable -vvv --bootstrap=%s',
[BP . '/bin/magento', $initParamsQuery]
);
$this->_shell->execute(
PHP_BINARY . ' -f %s cache:enable -vvv %s %s %s %s --bootstrap=%s',
[
BP . '/bin/magento',
\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER,
\Magento\Framework\App\Cache\Type\Layout::TYPE_IDENTIFIER,
\Magento\Framework\App\Cache\Type\Translate::TYPE_IDENTIFIER,
\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER,
$initParamsQuery,
]
);
// right after a clean installation, store DB dump for future reuse in tests or running the test suite again
if (!$db->isDbDumpExists() && $this->dumpDb) {
$this->getDbInstance()->storeDbDump();
}
}
/**
* Run commands after installation configured in post-install-setup-command-config.php
*
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function runPostInstallCommands()
{
// run post-install setup commands
$postInstallSetupCommands = $this->getPostInstallSetupCommands();
foreach ($postInstallSetupCommands as $postInstallSetupCommand) {
if (!isset($postInstallSetupCommand['command'])) {
throw new DomainException('"command" must be present in post install setup command arrays');
}
$command = $postInstallSetupCommand['command'];
$argumentsAndOptions = $postInstallSetupCommand['config'];
$argumentsAndOptionsPlaceholders = [
'--no-interaction'
];
foreach (array_keys($argumentsAndOptions) as $key) {
$isArgument = is_numeric($key);
if ($isArgument) {
$argumentsAndOptionsPlaceholders[] = '%s';
} else {
$argumentsAndOptionsPlaceholders[] = "$key=%s";
}
}
$argumentsAndOptionsPlaceholders[] = "--magento-init-params=%s";
$argumentsAndOptions[] = $this->getInitParamsQuery();
$this->_shell->execute(
PHP_BINARY . ' -f %s %s -vvv ' . implode(' ', array_values($argumentsAndOptionsPlaceholders)),
// phpcs:ignore Magento2.Performance.ForeachArrayMerge
array_merge(
[BP . '/bin/magento'],
[$command],
array_values($argumentsAndOptions)
),
);
}
}
/**
* Copies configuration files from the main code base, so the installation could proceed in the tests directory
*
* @return void
*/
private function copyAppConfigFiles()
{
$globalConfigFiles = Glob::glob(
$this->_globalConfigDir . '/{di.xml,*/di.xml,db_schema.xml,vendor_path.php}',
Glob::GLOB_BRACE
);
foreach ($globalConfigFiles as $file) {
$targetFile = $this->_configDir . str_replace($this->_globalConfigDir, '', $file);
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$this->_ensureDirExists(dirname($targetFile));
if ($file !== $targetFile) {
// phpcs:ignore Magento2.Functions.DiscouragedFunction
copy($file, $targetFile);
}
}
}
/**
* Copies global configuration file from the tests folder (see TESTS_GLOBAL_CONFIG_FILE)
*
* @return void
*/
private function copyGlobalConfigFile()
{
$targetFile = $this->_configDir . '/config.local.php';
// phpcs:ignore Magento2.Functions.DiscouragedFunction
copy($this->globalConfigFile, $targetFile);
}
/**
* Gets a list of CLI params for installation
*
* @return array
*/
private function getInstallCliParams()
{
$params = $this->getInstallConfig();
/**
* Literal value is used instead of constant, because autoloader is not integrated with Magento Setup app
* @see \Magento\Setup\Mvc\Bootstrap\InitParamListener::BOOTSTRAP_PARAM
*/
$params['magento-init-params'] = $this->getInitParamsQuery();
$result = [];
foreach ($params as $key => $value) {
if (isset($value)) {
$result["--{$key}=%s"] = $value;
}
}
return $result;
}
/**
* Encodes init params into a query string
*
* @return string
*/
private function getInitParamsQuery()
{
return urldecode(http_build_query($this->_initParams));
}
/**
* Sub-routine for merging custom parameters with the ones defined in object state
*
* @param array $params
* @return array
*/
public function _customizeParams($params)
{
return array_replace_recursive($this->_initParams, $params);
}
/**
* Reset application global state
*/
protected function _resetApp()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->clearCache();
\Magento\Framework\Data\Form::setElementRenderer(null);
\Magento\Framework\Data\Form::setFieldsetRenderer(null);
\Magento\Framework\Data\Form::setFieldsetElementRenderer(null);
$this->_appArea = null;
}
/**
* Create a directory with write permissions or don't touch existing one
*
* @param string $dir
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _ensureDirExists($dir)
{
// phpcs:ignore Magento2.Functions.DiscouragedFunction
if (!file_exists($dir)) {
$old = umask(0);
// phpcs:ignore Magento2.Functions.DiscouragedFunction
mkdir($dir, 0777, true);
umask($old);
// phpcs:ignore Magento2.Functions.DiscouragedFunction
} elseif (!is_dir($dir)) {
throw new \Magento\Framework\Exception\LocalizedException(__("'%1' is not a directory.", $dir));
}
}
/**
* Ge current application area
*
* @return string
*/
public function getArea()
{
return $this->_appArea;
}
/**
* Load application area
*
* @param string $areaCode
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function loadArea($areaCode)
{
$this->_appArea = $areaCode;
$scope = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Config\Scope::class
);
$scope->setCurrentScope($areaCode);
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->configure(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\ObjectManager\ConfigLoader::class
)->load(
$areaCode
)
);
$app = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\App\AreaList::class);
$areasForPartialLoading = [
\Magento\Framework\App\Area::AREA_GLOBAL,
\Magento\Framework\App\Area::AREA_WEBAPI_REST,
\Magento\Framework\App\Area::AREA_WEBAPI_SOAP,
\Magento\Framework\App\Area::AREA_CRONTAB,
\Magento\Framework\App\Area::AREA_GRAPHQL
];
if (in_array($areaCode, $areasForPartialLoading, true)) {
$app->getArea($areaCode)->load(\Magento\Framework\App\Area::PART_CONFIG);
} else {
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea($areaCode);
}
}
/**
* Gets customized directory paths
*
* @return array
*/
protected function getCustomDirs()
{
$path = DirectoryList::PATH;
$var = "{$this->installDir}/var";
$generated = "{$this->installDir}/generated";
$customDirs = [
DirectoryList::CONFIG => [$path => "{$this->installDir}/etc"],
DirectoryList::VAR_DIR => [$path => $var],
DirectoryList::VAR_EXPORT => [$path => "{$var}/export"],
DirectoryList::MEDIA => [$path => "{$this->installDir}/pub/media"],
DirectoryList::STATIC_VIEW => [$path => "{$this->installDir}/pub/static"],
DirectoryList::TMP_MATERIALIZATION_DIR => [$path => "{$var}/view_preprocessed/pub/static"],
DirectoryList::GENERATED_CODE => [$path => "{$generated}/code"],
DirectoryList::CACHE => [$path => "{$var}/cache"],
DirectoryList::LOG => [$path => "{$var}/log"],
DirectoryList::SESSION => [$path => "{$var}/session"],
DirectoryList::TMP => [$path => "{$var}/tmp"],
DirectoryList::UPLOAD => [$path => "{$var}/upload"],
DirectoryList::PUB => [$path => "{$this->installDir}/pub"],
DirectoryList::VAR_IMPORT_EXPORT => [$path => "{$this->installDir}/var"],
];
return $customDirs;
}
}
@@ -0,0 +1,222 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
return [
'all' => [ // Note: These will be applied to all services
'_objectManager' => null,
'objectManager' => null,
'_httpRequest' => null, // TODO ? I think this one is okay
'pluginList' => null, // Interceptors can change their pluginList??
'_classReader' => null,
'_eavConfig' => null,
'eavConfig' => null,
'_eavEntityType' => null,
'_moduleReader' => null,
'attributeLoader' => null,
'storeRepository' => null,
'localeResolver' => null,
'_localeResolver' => null,
],
'parents' => [ // Note: these are parent classes and will match their children as well.
Magento\Framework\DataObject::class => ['_underscoreCache' => null],
Magento\Eav\Model\Entity\AbstractEntity::class => [
'_attributesByTable' => null,
'_attributesByCode' => null,
'_staticAttributes' => null,
],
Magento\Framework\Model\ResourceModel\Db\AbstractDb::class => ['_tables' => null],
Magento\Framework\App\ResourceConnection::class => [
'config' => null, // $_connectionNames changes
'connections' => null,
],
/* All Proxy classes use NoninterceptableInterface. We filter _subject on them because for the Proxies that
* are loaded, we compare the actual loaded objects. */
Magento\Framework\ObjectManager\NoninterceptableInterface::class => [
'_subject' => null,
],
Magento\Framework\Logger\Handler\Base::class => [ // TODO: remove this after ACPT-1034 is fixed
'stream' => null,
],
],
'services' => [ // Note: These apply only to the service names that match.
Magento\Framework\ObjectManager\ConfigInterface::class => ['_mergedArguments' => null],
Magento\Framework\ObjectManager\DefinitionInterface::class => ['_definitions' => null],
Magento\Framework\App\Cache\Type\FrontendPool::class => ['_instances' => null],
Magento\Framework\GraphQl\Schema\Type\TypeRegistry::class => ['types' => null],
Magento\Framework\Filesystem::class => ['readInstances' => null, 'writeInstances' => null],
Magento\Framework\EntityManager\TypeResolver::class => [
'typeMapping' => null
],
Magento\Framework\App\View\Deployment\Version::class => [
'cachedValue' => null // deployment version of static files
],
Magento\Framework\View\Asset\Minification::class => ['configCache' => null], // TODO: depends on mode
Magento\Eav\Model\Config::class => [ // TODO: is this risky?
'attributeProto' => null,
'attributesPerSet' => null,
'attributes' => null,
'_objects' => null,
'_references' => null,
],
Magento\Framework\Api\ExtensionAttributesFactory::class => ['classInterfaceMap' => null],
Magento\Catalog\Model\ResourceModel\Category::class => ['_isActiveAttributeId' => null],
Magento\Eav\Model\ResourceModel\Entity\Type::class => ['additionalAttributeTables' => null],
Magento\Framework\Reflection\MethodsMap::class => ['serviceInterfaceMethodsMap' => null],
Magento\Framework\EntityManager\Sequence\SequenceRegistry::class => ['registry' => null],
Magento\Framework\EntityManager\MetadataPool::class => ['registry' => null],
Magento\Framework\App\Config\ScopeCodeResolver::class => ['resolvedScopeCodes' => null],
Magento\Framework\Cache\InvalidateLogger::class => ['request' => null],
Magento\Framework\View\Design\FileResolution\Fallback\Resolver\Simple::class => ['rulePool' => null],
Magento\Framework\View\Template\Html\Minifier::class => ['filesystem' => null],
Magento\Store\Model\Config\Processor\Fallback::class => ['scopes' => null],
'viewFileFallbackResolver' => ['rulePool' => null],
Magento\Framework\View\Asset\Source::class => ['filesystem' => null],
Magento\Store\Model\StoreResolver::class => ['request' => null],
Magento\Framework\Url\Decoder::class => ['urlBuilder' => null],
Magento\Framework\HTTP\PhpEnvironment\RemoteAddress::class => ['request' => null],
Magento\Framework\App\Helper\Context::class => ['_urlBuilder' => null],
Magento\MediaStorage\Helper\File\Storage\Database::class => [
'_filesystem' => null,
'_request' => null,
'_urlBuilder' => null,
],
Magento\Framework\Event\Config::class => ['_dataContainer' => null],
Magento\TestFramework\Store\StoreManager::class => ['decoratedStoreManager' => null],
Magento\Eav\Model\ResourceModel\Entity\Attribute::class => ['_eavEntityType' => null],
Magento\Eav\Model\Entity\AttributeLoader::class => ['defaultAttributes' => null, 'config' => null],
Magento\Framework\Validator\Factory::class => ['moduleReader' => null],
Magento\PageCache\Model\Config::class => ['reader' => null],
Magento\Config\Model\Config\Compiler\IncludeElement::class => ['moduleReader' => null],
Magento\Customer\Model\Customer::class => ['_config' => null],
Magento\Framework\Model\Context::class => ['_cacheManager' => null, '_appState' => null],
Magento\Framework\App\Cache\TypeList::class => ['_cache' => null],
Magento\GraphQlCache\Model\CacheId\CacheIdCalculator::class => ['contextFactory' => null],
Magento\Store\Model\Config\Placeholder::class => ['request' => null],
Magento\Framework\Config\Scope::class => ['_areaList' => null], // These were added because we switched to ...
Magento\TestFramework\App\State::class => ['_areaCode' => null], // .
Magento\Framework\Event\Invoker\InvokerDefault::class => ['_appState' => null], // .
Magento\Developer\Model\Logger\Handler\Debug::class => ['state' => null], // .
Magento\Framework\View\Design\FileResolution\Fallback\TemplateFile::class => // .
['appState' => null], // ... using Magento\Framework\App\Http for the requests
Magento\Store\App\Config\Source\RuntimeConfigSource::class => ['connection' => null],
Magento\Framework\Mview\View\Changelog::class => ['connection' => null],
Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class => ['_conn' => null],
Magento\Framework\App\Cache\Frontend\Factory::class => ['_filesystem' => null],
Magento\Framework\App\DeploymentConfig\Writer::class => ['filesystem' => null],
Magento\Search\Model\SearchEngine::class => ['adapter' => null],
// TODO: Do we need resetState for the connection?
Magento\Elasticsearch\SearchAdapter\ConnectionManager::class => ['client' => null],
// TODO: Do we need resetState for the connection?
Magento\Webapi\Model\Authorization\TokenUserContext::class => ['request' => null],
Magento\Framework\Json\Helper\Data::class => ['_request' => null],
Magento\Directory\Helper\Data::class => ['_request' => null],
Magento\Paypal\Plugin\TransparentSessionChecker::class => ['request' => null],
Magento\Backend\App\Area\FrontNameResolver::class => ['request' => null],
Magento\Backend\Helper\Data::class => ['_request' => null],
Magento\Framework\Url\Helper\Data::class => ['_request' => null],
Magento\Customer\Helper\View::class => ['_request' => null],
Magento\GraphQl\Model\Backpressure\BackpressureContextFactory::class => ['request' => null],
Magento\Search\Helper\Data::class => ['request' => null],
Magento\Search\Model\QueryFactory::class => ['request' => null],
Magento\Catalog\Helper\Product\Flat\Indexer::class => ['_request' => null],
Magento\Catalog\Model\Product\Gallery\ReadHandler\Interceptor::class => ['attribute' => null],
Magento\Eav\Model\Entity\Attribute\Source\Table::class => ['_attribute' => null],
Magento\Catalog\Model\Product\Gallery\ReadHandler::class => ['attribute' => null],
Magento\Framework\Pricing\Adjustment\Pool::class => ['adjustmentInstances' => null],
// TODO: Check to make sure this doesn't need reset.
// It looks okay on quick debug, but after deep debug,
// we might find something that needs reset. Or
// we can just reset it to be safe.
Magento\Framework\Pricing\Adjustment\Collection::class => ['adjustmentInstances' => null],
// TODO: Check to make sure this doesn't need reset.
// It looks okay on quick debug, but after deep debug, we might find something that needs reset.
// Or we can just reset it to be safe.
Magento\Catalog\Model\ResourceModel\Category\Tree::class => ['_conn' => null],
Magento\UrlRewrite\Model\Storage\DbStorage::class => ['connection' => null],
Magento\UrlRewrite\Model\Storage\DbStorage\Interceptor::class => ['connection' => null],
Magento\CatalogUrlRewrite\Model\Storage\DbStorage::class => ['connection' => null],
Magento\CatalogUrlRewrite\Model\Storage\DbStorage\Interceptor::class => ['connection' => null],
Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection\Interceptor::class => ['_conn' => null],
Magento\Catalog\Model\ResourceModel\Product\Collection::class => ['_conn' => null],
Magento\Catalog\Model\ResourceModel\Category\Collection::class => ['_conn' => null],
Magento\Catalog\Model\Product\Attribute\Backend\Tierprice\Interceptor::class =>
['metadataPool' => null, '_attribute' => null],
Magento\Framework\View\Design\Fallback\Rule\Theme::class => [
'directoryList' => null, // FIXME: This should be using a Dependency Injected Proxy instead
],
Magento\Framework\View\Asset\PreProcessor\AlternativeSource::class => [
'alternativesSorted' => null, // Note: just lazy loaded the sorting of alternatives
],
Magento\Directory\Model\Country::class => [
'_origData' => null, // TODO: Do these need to be added to resetState?
'storedData' => null, // Should this class even be reused at all?
'_data' => null,
],
Magento\Directory\Model\Region::class => [
'_origData' => null, // TODO: Do these need to be added to resetState?
'storedData' => null, // Should this class even be reused at all?
'_data' => null,
],
Magento\Framework\View\Layout\Argument\Parser::class => [
// FIXME: Needs to convert to proper dependency injection using constructor and factory
'converter' => null,
],
Magento\Framework\Communication\Config\Reader\XmlReader\Converter::class => [
// FIXME: Needs to convert to proper dependency injection using constructor and factory
'configParser' => null,
],
Magento\Webapi\Model\Config::class => [
'services' => null, // 'services' is lazy-loaded which is okay,
//but we need to verify that it is properly reset after poison pill
],
Magento\WebapiAsync\Model\Config::class => [
'asyncServices' => null, // 'asyncServices' is lazy-loaded which is okay,
// but we need to verify that it is properly reset after poison pill
],
Magento\Framework\MessageQueue\Publisher\Config\PublisherConnection::class => [
'name' => null, // TODO: Confirm this doesn't change outside of deployment,
// TODO: or if it does, that it resets properly from poison pill
'exchange' => null,
'isDisabled' => null,
],
Magento\Framework\MessageQueue\Publisher\Config\PublisherConfigItem::class => [
'topic' => null, // TODO: Confirm this doesn't change outside of deployment,
// TODO: or if it does, that it resets properly from poison pill
'isDisabled' => null,
],
Magento\Framework\View\File\Collector\Decorator\ModuleDependency::class => [
'orderedModules' => null, // TODO: Confirm this doesn't change outside of deployment
],
Magento\Framework\View\Page\Config::class => [
'builder' => null, // I think this is okay
],
Magento\TestFramework\View\Layout\Interceptor::class => [
'builder' => null,
],
Magento\Theme\Model\ResourceModel\Theme\Collection\Interceptor::class => [
'_itemObjectClass' => null, // FIXME: this looks like it needs to be fixed
],
Magento\Customer\Model\Metadata\AttributeMetadataCache::class => [
'isAttributeCacheEnabled' => null, // If cache configuration only changes during deployment, this is okay
],
Magento\Eav\Model\ResourceModel\Entity\Attribute\Set::class => [
'serializer' => null, // Note: Should use DI instead, but this isn't a big deal
],
Magento\Framework\Escaper::class => [
'escaper' => null, // Note: just lazy loading without a Proxy. Should use DI instead, but not big deal
],
Magento\Framework\App\State\Interceptor::class => [
'_areaCode' => null, // Note: _areaCode gets set after construction.
],
Magento\Framework\Cache\Frontend\Adapter\Zend::class => [
'parentFrontends' => null, // Note: This is to prevent closing parent thread's connection.
],
Magento\Framework\Session\SaveHandler\Redis::class => [
'connection' => null, // Note: This is to prevent closing parent thread's connection.
],
],
];
@@ -0,0 +1,551 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
/* These classes are skipped completely during comparison. */
return [
'*' => [
// phpcs:disable Generic.Files.LineLength.TooLong
// list of the latest failures started
Magento\Framework\ObjectManager\Resetter\WeakMapSorter::class => null, // caches sort values for classes
Magento\Framework\Reflection\MethodsMap::class => null, // caches reflection
Magento\Framework\Model\ResourceModel\Db\VersionControl\Metadata::class => null, // DB table info per class
Magento\Framework\Event\Config\Data::class => null, // TODO make sure this gets reloaded
Magento\Framework\App\AreaList::class => null, // TODO make sure this gets reloaded
Magento\Framework\Module\Dir\Reader::class => null, // config xml file iterators
Magento\Framework\App\Language\Dictionary::class => null, // dictionary paths
Magento\Framework\Config\Scope::class => null, // scope changes during test
Magento\Framework\App\ResourceConnection\Config::class => null, // configuration for connections
Magento\Framework\Module\ModuleList::class => null, // This one is needed to pass on Jenkins build
Magento\Framework\Filter\FilterManager::class => null,
Magento\Framework\View\Asset\PreProcessor\Helper\Sort::class => null,
Magento\Framework\Validator\EmailAddress::class => null, // FIXME!!!!
Magento\Framework\Url\QueryParamsResolver::class => null, // FIXME!!!!
// Magento\SalesRule\Model\DeltaPriceRound::class => null,
// Magento\SalesRule\Helper\CartFixedDiscount::class => null,
// Magento\SalesRule\Api\Data\RuleInterfaceFactory::class => null,
// Magento\SalesRule\Api\Data\ConditionInterfaceFactory::class => null,
// Magento\SalesRule\Api\Data\RuleLabelInterfaceFactory::class => null,
// Magento\SalesRule\Model\Converter\ToDataModel::class => null,
// Magento\SalesRule\Model\Converter\ToModel::class => null,
// Magento\SalesRule\Api\Data\RuleSearchResultInterfaceFactory::class => null,
// Magento\SalesRule\Model\RuleRepository::class => null,
// Magento\SalesRule\Model\RuleFactory::class => null,
Magento\SalesSequence\Model\MetaFactory::class => null,
Magento\SalesSequence\Model\ProfileFactory::class => null,
Magento\SalesSequence\Model\ResourceModel\Profile::class => null,
Magento\SalesSequence\Model\ResourceModel\Meta::class => null,
Magento\SalesSequence\Model\SequenceFactory::class => null,
Magento\SalesSequence\Model\Manager::class => null,
// Magento\Quote\Model\ResourceModel\Collection\Interceptor::class => null,
// Magento\Quote\Model\ResourceModel\Quote\Collection\Interceptor::class => null,
// Magento\Quote\Api\Data\ProductOptionInterfaceFactory::class => null,
Magento\Quote\Model\Quote\Item\Interceptor::class => null, // FIXME
Magento\Quote\Model\Quote\Address\Interceptor::class => null, // FIXME
Magento\Quote\Model\ResourceModel\Quote::class => null, // FIXME
// Magento\Quote\Model\QuoteIdToMaskedQuoteId::class => null,
// Magento\Quote\Model\Quote\Address\Total\Collector::class => null,
// Magento\Quote\Model\Quote\TotalsCollectorList::class => null,
// Magento\Quote\Model\Quote\TotalsCollector::class => null,
Magento\Quote\Model\Quote::class => null, // FIXME
// Magento\Quote\Model\Quote\ProductOptionFactory::class => null,
// Magento\Quote\Api\Data\ProductOptionExtensionFactory::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableRowSizeEstimator::class => null,
// Magento\Catalog\Model\Indexer\Price\BatchSizeManagement::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\DefaultPrice::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRelationsCalculator::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductRowSizeEstimator::class => null,
// Magento\Catalog\Model\Indexer\Price\CompositeProductBatchSizeManagement::class => null,
// Magento\Catalog\Model\Indexer\Product\Price\TableMaintainer::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\IndexTableStructureFactory::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Attribute\Backend\Tierprice::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\TierPrice::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\CompositeProductBatchSizeAdjuster::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Indexer\Price\BatchSizeCalculator::class => null,
// Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection::class => null,
// Magento\Catalog\Model\Product\Attribute\Repository::class => null,
Magento\Catalog\Model\ResourceModel\Product::class => null,
// Magento\Catalog\Model\ProductRepository::class => null,
// Magento\Catalog\Model\Product\Type::class => null,
// Magento\Catalog\Model\Product\Link::class => null,
// Magento\Customer\Model\Indexer\AttributeProvider::class => null,
Magento\Customer\Model\ResourceModel\Customer::class => null,
Magento\Customer\Model\ResourceModel\Customer\Interceptor::class => null,
// Magento\Customer\Model\ResourceModel\CustomerRepository::class => null,
// Magento\Customer\Model\Session\Validators\CutoffValidator::class => null,
// Magento\Customer\Model\Customer::class => null,
// Magento\Customer\Model\Session\SessionCleaner::class => null,
// Magento\Customer\Model\ResourceModel\AddressRepository::class => null,
// Magento\Customer\Model\CustomerRegistry::class => null,
// Magento\Customer\Model\ResourceModel\Address\Relation::class => null,
// Magento\Customer\Model\ResourceModel\Address::class => null,
// Magento\Customer\Model\AttributeMetadataConverter::class => null,
Magento\Customer\Model\Metadata\CustomerMetadata::class => null, // TODO?
// Magento\Customer\Model\Metadata\AttributeMetadataCache::class => null,
// Magento\Customer\Model\Metadata\CustomerCachedMetadata::class => null,
// Magento\Customer\Model\Config\Share::class => null,
// Magento\Customer\Model\Session\Proxy::class => null,
// Magento\Customer\Model\Delegation\Storage::class => null,
// Magento\Customer\Model\ResourceModel\GroupRepository::class => null,
// Magento\Customer\Helper\View::class => null,
// Magento\Customer\Model\Authorization\CustomerSessionUserContext::class => null,
// Magento\Customer\Model\Authentication::class => null,
// Magento\Customer\Model\Session::class => null,
// Magento\Customer\Model\AddressRegistry::class => null,
// Magento\Customer\Model\AttributeMetadataDataProvider::class => null,
// Magento\Customer\Model\AccountConfirmation::class => null,
// Magento\Customer\Model\AccountManagement::class => null,
// Magento\Customer\Model\Plugin\CustomerFlushFormKey::class => null,
Magento\Customer\Observer\LogLastLoginAtObserver::class => null,
Magento\Customer\Model\Visitor\Proxy::class => null,
Magento\Customer\Api\CustomerRepositoryInterface\Proxy::class => null,
Magento\Customer\Model\ResourceModel\Attribute::class => null,
Magento\Customer\Model\Address\Config::class => null,
Magento\Indexer\Model\Indexer::class => null,
Magento\Indexer\Model\Indexer\DependencyDecorator::class => null,
Magento\Indexer\Model\Indexer\DeferredCacheContext::class => null,
Magento\Indexer\Model\Indexer\DeferredCacheCleaner::class => null,
Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ExtractDataFromCategoryTree::class => null,
Magento\Eav\Model\ResourceModel\Entity\Attribute\Set::class => null,
Magento\Eav\Model\Entity\Attribute\Set::class => null,
Magento\Eav\Model\Entity\VersionControl\Metadata::class => null,
Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute::class => null,
Magento\Store\Model\GroupRepository::class => null,
Magento\Bundle\Model\CartItemProcessor::class => null,
Magento\ConfigurableProduct\Model\Quote\Item\CartItemProcessor::class => null,
Magento\ConfigurableProduct\Model\ResourceModel\Product\Indexer\Price\OptionsSelectBuilder::class => null,
Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute::class => null,
Magento\Payment\Gateway\Config\ConfigFactory::class => null,
Magento\Payment\Gateway\Data\Quote\AddressAdapterFactory::class => null,
Magento\Catalog\Model\ResourceModel\Category::class => null,
Magento\CatalogGraphQl\Model\Resolver\Products\SearchCriteria\CollectionProcessor\FilterProcessor\CategoryFilter::class => null,
Magento\Tax\Model\Quote\ToOrderConverter::class => null,
Magento\Store\Model\WebsiteManagement::class => null,
Magento\CatalogRule\Model\ResourceModel\Rule\Product\Price::class => null,
Magento\CatalogRule\Model\Indexer\ProductPriceIndexModifier::class => null,
Magento\InventoryConfigurableProduct\Pricing\Price\Indexer\BaseStockStatusSelectProcessor::class => null,
Magento\InventoryConfigurableProduct\Pricing\Price\Indexer\OptionsIndexer::class => null,
Magento\InventoryCatalog\Plugin\CatalogInventory\Model\Indexer\ModifySelectInProductPriceIndexFilter::class => null,
Magento\Indexer\Model\Indexer\DeferCacheCleaning::class => null,
Magento\LoginAsCustomerAssistance\Model\IsAssistanceEnabled::class => null,
Magento\LoginAsCustomerAssistance\Model\SetAssistance::class => null,
Magento\LoginAsCustomerAssistance\Plugin\CustomerPlugin::class => null,
Magento\Config\Model\Config\Processor\EnvironmentPlaceholder::class => null,
Magento\GraphQlNewRelic\Plugin\ReportError::class => null,
Magento\CatalogInventory\Model\StockRegistryProvider::class => null,
Magento\CatalogInventory\Model\StockRegistry::class => null,
Magento\CatalogInventory\Model\Indexer\ProductPriceIndexFilter::class => null,
Magento\Tax\Model\Calculation::class => null,
Magento\Tax\Model\TaxCalculation::class => null,
Magento\SalesRule\Model\RulesApplier::class => null,
Magento\OfflineShipping\Model\SalesRule\Calculator::class => null,
Magento\OfflineShipping\Model\Quote\Address\FreeShipping::class => null,
Magento\SalesRule\Model\Validator::class => null,
Magento\User\Helper\Data::class => null,
Magento\Authorization\Model\RoleFactory::class => null,
Magento\User\Model\UserValidationRules::class => null,
Magento\User\Model\Backend\Config\ObserverConfig::class => null,
Magento\User\Model\ResourceModel\User::class => null,
Magento\User\Model\Notificator::class => null,
Magento\TestModuleCatalogInventoryCache\Plugin\PreventCachingPreloadedStockDataInToStockRegistry::class => null,
Magento\Catalog\Model\CustomOptions\CustomOptionProcessor::class => null,
'orderMetadata' => null,
Magento\Payment\Api\Data\PaymentAdditionalInfoInterfaceFactory::class => null,
Magento\InventoryInStorePickup\Model\ExtractPickupLocationAddressData::class => null,
Magento\InventoryInStorePickupQuote\Model\ExtractQuoteAddressShippingAddressData::class => null,
Magento\InventoryInStorePickupQuote\Model\GetShippingAddressData::class => null,
Magento\InventoryInStorePickupQuote\Model\IsPickupLocationShippingAddress::class => null,
Magento\InventoryInStorePickupQuote\Model\ToQuoteAddress::class => null,
Magento\InventoryInStorePickupQuote\Model\GetWebsiteCodeByStoreId::class => null,
Magento\InventoryInStorePickupQuote\Plugin\Quote\ReplaceShippingAddressForShippingAddressManagement::class => null,
Magento\NegotiableQuote\Model\Plugin\Quote\Model\ShippingAssignmentPersisterPlugin::class => null,
Magento\PurchaseOrder\Plugin\Quote\Model\QuoteRepositoryPlugin::class => null,
Magento\Catalog\Model\Config::class => null,
Magento\Downloadable\Model\Url\DomainValidator::class => null,
Magento\Staging\Model\VersionManager::class => null,
Magento\Staging\Model\Url\BaseUrlModifier::class => null,
Magento\Staging\Model\Event\Manager::class => null,
Magento\CatalogStaging\Plugin\Catalog\Model\Indexer\AbstractFlatState::class => null,
Magento\Directory\Helper\Data::class => null,
Magento\Store\Model\Address\Renderer::class => null,
Magento\QuoteGraphQl\Plugin\ProductAttributesExtender::class => null,
Magento\Paypal\Plugin\TransparentSessionChecker::class => null,
Magento\Backend\App\Area\FrontNameResolver::class => null,
Magento\Backend\Helper\Data::class => null,
Magento\GraphQl\Plugin\DisableSession::class => null,
Magento\Tax\Model\TaxClass\Repository::class => null,
Magento\JwtUserToken\Model\ResourceModel\FastStorageRevokedWrapper::class => null,
Magento\Webapi\Model\Authorization\TokenUserContext::class => null,
Magento\Authorization\Model\CompositeUserContext::class => null,
Magento\Webapi\Model\WebapiRoleLocator::class => null,
'CustomerAddressSnapshot' => null,
'EavVersionControlSnapshot' => null,
Magento\CustomerGraphQl\Model\Customer\ValidateCustomerData\ValidateEmail::class => null,
Magento\CustomerGraphQl\Model\Customer\ValidateCustomerData::class => null,
Magento\Catalog\Helper\Data::class => null,
Magento\Eav\Model\AttributeDataFactory::class => null,
Magento\Checkout\Model\Session::class => null,
Magento\JwtUserToken\Model\ConfigurableJwtSettingsProvider::class => null,
Magento\JwtUserToken\Model\Reader::class => null,
Magento\Bundle\Pricing\Price\TaxPrice::class => null,
Magento\Customer\Observer\AfterAddressSaveObserver::class => null,
Magento\LoginAsCustomer\Model\GetLoggedAsCustomerAdminId::class => null,
Magento\CustomerGraphQl\Plugin\ClearCustomerSessionAfterRequest::class => null,
Laminas\Uri\Uri::class => null,
PhpAmqpLib\Connection\AMQPSSLConnection::class => null,
Magento\TestFramework\Interception\PluginList::class => null,
// memory leak, wrong sql, potential issues
Magento\Theme\Model\View\Design::class => null,
Magento\RemoteStorage\Model\Config::class => null,
Magento\Store\Model\Config\Processor\Fallback::class => null,
Magento\Framework\Lock\LockBackendFactory::class => null,
'customRemoteFilesystem' => null,
'systemConfigQueryLocker' => null,
Magento\Config\App\Config\Source\RuntimeConfigSource::class => null,
'scopesConfigInitialDataProvider' => null,
Magento\Developer\Model\Logger\Handler\Debug::class => null,
Magento\Developer\Model\Logger\Handler\Syslog::class => null,
Magento\Store\App\Config\Source\RuntimeConfigSource::class => null,
Magento\Store\App\Config\Type\Scopes::class => null,
Magento\TestFramework\App\Config::class => null,
Magento\TestFramework\Request::class => null,
Magento\TestFramework\ErrorLog\Logger::class => null,
Magento\TestFramework\Db\Adapter\Mysql\Interceptor::class => null,
Magento\TestFramework\Mail\Template\TransportBuilderMock::class => null,
Magento\TestFramework\Api\Config\Reader\FileResolver::class => null,
'translationConfigSourceAggregated' => null,
Magento\Theme\Model\View\Design\Proxy::class => null,
Magento\Translation\Model\Source\InitialTranslationSource\Proxy::class => null,
Magento\Translation\App\Config\Type\Translation::class => null,
Magento\Backend\App\Request\PathInfoProcessor\Proxy::class => null,
Magento\MediaStorage\Helper\File\Storage\Database::class => null,
Magento\Store\Model\StoreManager::class => null,
Magento\Store\Model\StoreManager\Interceptor::class => null,
Magento\TestFramework\Response::class => null,
Magento\Store\Model\WebsiteRepository::class => null,
Magento\Store\Model\StoreRepository::class => null,
Magento\Store\Model\System\Store::class => null,
Magento\AwsS3\Driver\CredentialsCache::class => null,
Magento\Eav\Model\Config::class => null,
'AssetPreProcessorPool' => null,
Magento\GraphQl\Model\Query\ContextFactory::class => null,
'viewFileMinifiedFallbackResolver' => null,
Magento\RemoteStorage\Driver\DriverPool::class => null,
Magento\TestFramework\App\State::class => null,
Magento\Framework\TestFramework\ApplicationStateComparator\SkipListAndFilterList::class => null, // Yes, our test uses mutable state itself :-)
Magento\Framework\DB\Adapter\Pdo\Mysql\Interceptor::class => null,
Magento\Framework\App\ObjectManager\ConfigLoader\Compiled::class => null,
Magento\Framework\Interception\PluginList\PluginList::class => null,
Magento\InventorySales\Model\IsProductSalableForRequestedQtyCondition\IsProductSalableForRequestedQtyConditionChain::class => null,
Magento\InventorySales\Model\AreProductsSalableForRequestedQty::class => null,
Magento\Config\App\Config\Type\System::class => null,
Magento\CatalogRule\Observer\RulePricesStorage::class => null,
Magento\CatalogRule\Observer\PrepareCatalogProductCollectionPricesObserver::class => null,
Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuoteItemQtyList::class => null,
Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option::class => null,
Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem::class => null,
Magento\CatalogRule\Observer\ProcessFrontFinalPriceObserver::class => null,
Magento\SalesRule\Model\Coupon\CodeLimitManager::class => null,
Magento\SalesRule\Observer\CouponCodeValidation::class => null,
Magento\CatalogInventory\Helper\Stock::class => null,
Magento\Downloadable\Model\Product\Type::class => null,
Magento\Bundle\Model\Product\Type::class => null,
Magento\CatalogInventory\Observer\AddInventoryDataObserver::class => null,
Magento\Downloadable\Model\Quote\Item\CartItemProcessor::class => null,
Magento\Staging\Model\Update\VersionHistory::class => null,
Magento\Staging\Model\UpdateRepository::class => null,
Magento\GraphQlCache\Model\Plugin\Auth\TokenIssuer::class => null,
Magento\GraphQlCache\Model\Plugin\Auth\TokenExtractor::class => null,
Magento\Quote\Model\Quote\Relation::class => null,
Magento\Quote\Model\QueryResolver::class => null,
'QuoteRelationsComposite' => null,
Magento\StoreGraphQl\Plugin\LocalizeEmail::class => null,
Magento\Framework\MessageQueue\DefaultValueProvider::class => null, // TODO: find out why its failing
// phpcs:enable Generic.Files.LineLength.TooLong
Magento\Framework\Lock\Proxy::class => null,
Magento\TestFramework\ObjectManager\Config::class => null,
Magento\Framework\Escaper::class => null,
Magento\Framework\Css\PreProcessor\Adapter\CssInliner::class => null, // FIXME
],
'*-fromConstructed' => [
// phpcs:disable Generic.Files.LineLength.TooLong
Magento\Customer\Model\Cache\GroupExcludedWebsiteCache::class => null,
Magento\Sales\Model\ResourceModel\Grid::class => null,
Magento\Sales\Model\ResourceModel\GridPool::class => null,
Magento\Sales\Api\Data\OrderExtension::class => null,
Magento\Sales\Api\Data\OrderItemExtension::class => null,
Magento\Sales\Observer\GridSyncInsertObserver\Interceptor::class => null,
Magento\Staging\Model\UpdateRepositoryCache::class => null,
Magento\PageBuilder\Model\Filter\Template::class => null,
Magento\PageBuilder\Plugin\Filter\TemplatePlugin::class => null,
Magento\Customer\Api\Data\CustomerExtension::class => null,
Magento\Framework\TestFramework\ApplicationStateComparator\ObjectManager::class => null,
Magento\RemoteStorage\Filesystem::class => null,
Magento\Framework\App\Cache\Frontend\Factory::class => null,
Magento\Framework\ObjectManager\Definition\Runtime::class => null,
Magento\Framework\Cache\LockGuardedCacheLoader::class => null,
Magento\Framework\View\Asset\PreProcessor\Pool::class => null,
Magento\Framework\App\Area::class => null,
Magento\Store\Model\Store\Interceptor::class => null,
Magento\Framework\TestFramework\ApplicationStateComparator\Comparator::class => null, // Yes, our test uses mutable state itself :-)
Magento\Framework\GraphQl\Query\QueryParser::class => null, // reloads as a ReloadProcessor
Magento\Framework\App\Http\Context\Interceptor::class => null,
Magento\Framework\HTTP\LaminasClient::class => null,
Magento\TestFramework\App\State\Interceptor::class => null,
Magento\TestFramework\App\MutableScopeConfig::class => null,
Magento\TestFramework\Store\StoreManager::class => null,
Magento\TestFramework\Workaround\Override\Config\RelationsCollector::class => null,
Magento\Framework\Session\SaveHandler::class => null,
Magento\Customer\Model\Group\Interceptor::class => null,
Magento\Store\Model\Group\Interceptor::class => null,
Magento\Directory\Model\Currency\Interceptor::class => null,
Magento\Catalog\Model\Category\AttributeRepository::class => null, // Note: has reloadState
Magento\Catalog\Model\ResourceModel\Category\Interceptor::class => null,
Magento\Catalog\Model\Attribute\Backend\DefaultBackend\Interceptor::class => null,
Magento\GraphQlCache\Model\Resolver\IdentityPool::class => null,
Magento\Inventory\Model\Stock::class => null,
Magento\InventorySales\Model\SalesChannel::class => null,
Magento\InventoryApi\Api\Data\StockExtension::class => null,
Magento\Elasticsearch\Model\Adapter\FieldMapper\FieldMapperResolver::class => null,
Magento\Catalog\Model\ResourceModel\Eav\Attribute\Interceptor::class => null,
Magento\Catalog\Model\Category\Attribute\Backend\Image\Interceptor::class => null,
Magento\Catalog\Model\Attribute\Backend\Startdate\Interceptor::class => null,
Magento\Eav\Model\Entity\Attribute\Backend\Datetime\Interceptor::class => null,
Magento\Catalog\Model\Category\Attribute\Backend\Sortby\Interceptor::class => null,
Magento\Catalog\Model\Category\Attribute\Backend\LayoutUpdate\Interceptor::class => null,
Magento\Catalog\Model\Attribute\Backend\Customlayoutupdate\Interceptor::class => null,
Magento\Eav\Model\Entity\Attribute\Backend\Time\Created\Interceptor::class => null,
Magento\Eav\Model\Entity\AttributeBackendTime\Updated\Interceptor::class => null,
Magento\Eav\Model\Entity\Attribute\Backend\Increment\Interceptor::class => null,
Magento\Eav\Model\Entity\Interceptor::class => null,
Magento\Framework\View\Asset\RepositoryMap::class => null,
Magento\Framework\Url\RouteParamsResolver\Interceptor::class => null,
Magento\Theme\Model\Theme::class => null,
Magento\Catalog\Model\ResourceModel\Category\Collection\Interceptor::class => null,
Magento\Catalog\Model\Category\Interceptor::class => null,
Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\CategoryTree\Wrapper\NodeWrapper::class => null,
Magento\Framework\Api\AttributeValue::class => null,
Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class => null,
Magento\Catalog\Model\ResourceModel\Product\Interceptor::class => null,
Magento\Catalog\Model\ResourceModel\Product\Collection\Interceptor::class => null,
Magento\Framework\Api\Search\SearchCriteria::class => null,
Magento\Framework\Api\SortOrder::class => null,
Magento\Framework\Api\Search\SearchResult::class => null,
Magento\Eav\Model\Entity\Attribute\Backend\Time\Updated\Interceptor::class => null,
Magento\CatalogInventory\Model\Stock\Item\Interceptor::class => null,
Magento\Framework\View\Asset\File::class => null,
Magento\Customer\Model\Attribute\Interceptor::class => null,
Magento\Framework\GraphQl\Schema\SchemaGenerator::class => null,
Magento\Framework\App\PageCache\Version::class => null,
Magento\Framework\App\PageCache\Identifier::class => null,
Magento\Framework\App\PageCache\Kernel::class => null,
Magento\Translation\Model\Source\InitialTranslationSource::class => null,
Magento\Framework\GraphQl\Schema\Type\Output\OutputMapper::class => null,
Magento\Framework\GraphQl\Schema\Type\Input\InputMapper::class => null,
Magento\Framework\Filesystem\DriverPool::class => null,
Magento\Framework\Filesystem\Directory\WriteFactory::class => null,
Magento\Catalog\Model\Product\Media\Config::class => null,
Magento\Catalog\Model\Product\Type\Interceptor::class =>
null, // Note: We may need to check to see if this needs to be reset when config changes
Magento\ConfigurableProduct\Model\Product\Type\Configurable\Interceptor::class => null,
Magento\Catalog\Model\Product\Type\Simple\Interceptor::class => null,
Magento\Eav\Api\Data\AttributeExtension::class =>
null, // FIXME: This needs to be fixed. is_pagebuilder_enabled 0 => null // Bug is in Pagebuilder?
Magento\TestFramework\Event\Magento::class => null,
Magento\Store\Model\Website\Interceptor::class => null, // reset by poison pill
Magento\Eav\Model\Entity\Type::class => null, // attribute types should be destroyed by poison pill
Magento\Eav\Model\Entity\Attribute\Backend\DefaultBackend\Interceptor::class =>
null, // attribute types should be destroyed by poison pill
Magento\TestFramework\Mail\Template\TransportBuilderMock\Interceptor::class => null, // only for testing
Magento\Framework\ForeignKey\ObjectRelationProcessor\EnvironmentConfig::class =>
null, // OK; shouldn't change outside of deployment
Magento\Customer\Model\ResourceModel\Attribute\Collection\Interceptor::class =>
null, // Note: We don't _resetState these attributes on purpose. Gets reset by Magento\ApplicationServer\Eav\Model\Config\ClearWithoutCleaningCache
Magento\Customer\Model\ResourceModel\Address\Attribute\Collection\Interceptor::class =>
null, // Note: We don't _resetState these attributes on purpose. Gets reset by Magento\ApplicationServer\Eav\Model\Config\ClearWithoutCleaningCache
Magento\Config\Model\Config\Structure\Data::class => null, // should be cleaned after poison pill
Magento\Customer\Model\ResourceModel\Address\Interceptor::class =>
null, // customer_address_entity table info
Magento\SalesRule\Model\ResourceModel\Rule::class => null,
Magento\SalesRule\Model\Plugin\QuoteConfigProductAttributes::class => null,
//Create Empty Cart
Magento\Quote\Model\ResourceModel\Quote\QuoteIdMask::class => null,
Magento\Quote\Model\Cart\CustomerCartResolver::class => null,
Magento\QuoteGraphQl\Model\Cart\CreateEmptyCartForGuest::class => null,
Magento\Quote\Model\MaskedQuoteIdToQuoteId::class => null,
Magento\Quote\Model\Quote\Address\Total\Shipping::class => null, // FIXME
Magento\SalesRule\Model\Quote\Discount::class => null,
Magento\Weee\Model\Total\Quote\Weee::class => null,
Magento\Quote\Model\Quote\Interceptor::class => null, // FIXME
Magento\Quote\Model\ResourceModel\Quote\Address::class => null,
Magento\Quote\Model\Quote\Address::class => null, // FIXME
Magento\Quote\Model\ShippingMethodManagement::class => null,
Magento\Quote\Model\ResourceModel\Quote\Item\Collection\Interceptor::class => null,
Magento\Quote\Model\Quote\Address\Total::class => null, // FIXME
Laminas\Validator\ValidatorChain::class => null,
Magento\ResourceConnections\App\DeploymentConfig::class => null,
Magento\Staging\Model\StagingList::class => null,
Magento\Staging\Model\ResourceModel\Update::class => null,
Magento\AdobeCommerceEventsClient\Event\EventList::class => null,
Magento\AdobeCommerceEventsClient\Event\Filter\EventFieldsFilter::class => null,
Magento\AdobeCommerceEventsClient\Event\EventStorageWriter::class => null,
Magento\TestModuleAdobeCommerceEvents\Plugin\Framework\ManagerInterfacePlugin::class => null,
Magento\Catalog\Model\Product\Interceptor::class => null,
Magento\Catalog\Model\Product\Attribute\Backend\Price\Interceptor::class => null,
Magento\Catalog\Model\Product\Attribute\Backend\Tierprice\Interceptor::class => null,
Magento\Catalog\Model\Product\Attribute\Backend\Boolean\Interceptor::class => null,
Magento\Catalog\Model\Product\Attribute\Backend\LayoutUpdate\Interceptor::class => null,
Magento\Catalog\Model\Product\Attribute\Backend\Stock\Interceptor::class => null,
Magento\Catalog\Model\Product\Attribute\Backend\Weight\Interceptor::class => null,
Magento\Catalog\Model\ResourceModel\Product\CategoryLink::class => null,
Magento\Catalog\Model\Category\Link\ReadHandler::class => null,
Laminas\Validator\Uri::class => null,
Magento\Quote\Model\ResourceModel\Quote\Item::class => null,
Magento\Quote\Model\Quote\Item::class => null,
Magento\Quote\Model\ResourceModel\Quote\Item\Option::class => null,
Magento\Quote\Model\Quote\Item\Option::class => null,
Magento\User\Model\User\Interceptor::class => null,
Magento\Quote\Model\ShippingAssignment::class => null,
Magento\Quote\Model\Shipping::class => null,
Magento\NegotiableQuote\Model\NegotiableQuote\Interceptor::class => null,
Magento\Quote\Api\Data\CartExtension::class => null, // FIXME
Magento\Catalog\Api\Data\ProductExtension::class => null,
Magento\Quote\Api\Data\AddressExtension::class => null,
Magento\CatalogRule\Observer\ProcessFrontFinalPriceObserver\Interceptor::class => null,
Magento\Catalog\Model\Product\Type\Virtual\Interceptor::class => null,
Magento\Catalog\Model\Product\Link\Interceptor::class => null,
Magento\Bundle\Model\Product\Type\Interceptor::class => null,
Magento\Bundle\Model\Product\LinksList::class => null,
Magento\Bundle\Model\Product\OptionList::class => null,
Magento\Bundle\Model\Option\SaveAction::class => null,
Magento\Bundle\Model\OptionRepository::class => null,
Magento\CatalogInventory\Model\AddStockStatusToCollection::class => null,
Magento\Bundle\Model\ResourceModel\Option\Collection\Interceptor::class => null,
Magento\Bundle\Model\Link::class => null,
Magento\Bundle\Model\Option::class => null,
Magento\Bundle\Model\BundleOption::class => null,
Magento\Quote\Api\Data\ProductOptionExtension::class => null,
Magento\Quote\Model\Quote\ProductOption::class => null,
Magento\Catalog\Model\CategoryLink::class => null,
Magento\ConfigurableProduct\Model\Product\Type\Configurable\OptionValue::class => null,
Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection\Interceptor::class => null,
Magento\ConfigurableProduct\Model\Quote\Item\ConfigurableItemOptionValue::class => null,
Magento\Downloadable\Model\Product\Type\Interceptor::class => null,
Magento\Downloadable\Model\LinkRepository::class => null,
Magento\Downloadable\Model\SampleRepository::class => null,
Magento\Downloadable\Model\Link::class => null,
Magento\Downloadable\Model\ResourceModel\Sample\Collection\Interceptor::class => null,
Magento\Downloadable\Model\Sample::class => null,
Magento\Downloadable\Model\DownloadableOption::class => null,
Magento\Payment\Model\MethodList::class => null,
Magento\Quote\Model\PaymentMethodManagement::class => null,
Magento\Quote\Model\ResourceModel\Quote\Address\Rate::class => null,
Magento\Framework\ObjectManager\TMap::class => null,
Magento\Payment\Gateway\Config\ValueHandlerPool::class => null,
Magento\Payment\Model\Method\Adapter::class => null,
Magento\Tax\Model\Quote\GrandTotalDetailsPlugin::class => null,
Magento\Quote\Model\BillingAddressManagement::class => null,
Magento\QuoteGraphQl\Model\Cart\AssignBillingAddressToCart::class => null,
Magento\NegotiableQuote\Plugin\Quote\Api\JoinNegotiableQuoteTotalsPlugin::class => null,
Magento\Captcha\Helper\Data::class => null,
Magento\Checkout\Model\CaptchaRateLimiter::class => null,
Magento\Captcha\Model\DefaultModel::class => null,
Magento\Quote\Model\ResourceModel\Quote\Payment::class => null,
Magento\Company\Plugin\Framework\Model\ActionValidator\RemoveActionPlugin::class => null,
Magento\Sales\Model\Order\ItemRepository\Interceptor::class => null,
Magento\Sales\Model\ResourceModel\Order\Interceptor::class => null,
Magento\Sales\Model\Order\Address\Validator::class => null,
Magento\Quote\Model\SubmitQuoteValidator::class => null,
Magento\Catalog\Model\Indexer\Product\Price\DimensionModeConfiguration::class => null,
Magento\Catalog\Model\Indexer\Product\Price\PriceTableResolver::class => null,
Magento\Sales\Model\Order\Config::class => null,
Magento\Sales\Model\Order\Interceptor::class => null,
Magento\Sales\Model\ResourceModel\Order\Address::class => null,
Magento\Sales\Model\Order\Address::class => null,
Magento\Sales\Model\Order\CreditmemoFactory::class => null,
Magento\Sales\Model\Order\Payment\Interceptor::class => null,
Magento\Sales\Model\ResourceModel\Order\Item::class => null,
Magento\Sales\Model\Order\Item\Interceptor::class => null,
Magento\OfflinePayments\Model\Checkmo::class => null,
Magento\Sales\Model\ResourceModel\Order\Status\Collection\Interceptor::class => null,
Magento\Paypal\Model\Pro::class => null,
Magento\Paypal\Model\Api\Nvp::class => null,
Magento\Sales\Model\ResourceModel\Order\Invoice\Collection\Interceptor::class => null,
Magento\CatalogSearch\Model\ResourceModel\EngineProvider::class => null,
Magento\Catalog\Model\Indexer\Product\Price\DimensionCollectionFactory::class => null,
Magento\Indexer\Model\Mview\View\State\Interceptor::class => null,
Magento\Framework\Mview\View::class => null,
Magento\Framework\Amqp\ConfigPool::class => null,
Magento\Framework\Amqp\ExchangeFactory::class => null,
Magento\Framework\MessageQueue\MessageEncoder::class => null,
Magento\Framework\MessageQueue\MessageValidator::class => null,
Magento\Framework\MessageQueue\Bulk\Publisher::class => null,
Magento\Framework\MessageQueue\Bulk\Rpc\Publisher::class => null,
Magento\InventorySales\Plugin\InventoryReservationsApi\PreventAppendReservationOnNotManageItemsInStockPlugin::class => null,
Magento\Framework\MessageQueue\ExchangeRepository::class => null,
Magento\Framework\MessageQueue\Publisher::class => null,
Magento\Framework\MessageQueue\Rpc\Publisher::class => null,
Magento\Framework\MessageQueue\PublisherPool::class => null,
Magento\InventoryIndexer\Plugin\InventorySales\EnqueueAfterPlaceReservationsForSalesEvent::class => null,
Magento\Framework\Amqp\Config::class => null,
Magento\Framework\Amqp\Exchange::class => null,
PhpAmqpLib\Connection\AMQPStreamConnection::class => null,
Magento\CatalogInventory\Model\Indexer\Stock\CacheCleaner::class => null,
Magento\InventoryCatalogSearch\Plugin\CatalogSearch\Model\Indexer\ChildProductFilterByInventoryStockPlugin::class => null,
Magento\InventoryElasticsearch\Plugin\CatalogSearch\Model\Indexer\Fulltext\Action\DataProvider\StockedProductFilterByInventoryStock::class => null,
Magento\Widget\Model\ResourceModel\Layout\Update::class => null,
Magento\Widget\Model\ResourceModel\Layout\Plugin::class => null,
Magento\Sales\Model\Order\Address\Interceptor::class => null,
Magento\OfflinePayments\Model\Checkmo\Interceptor::class => null,
Magento\NegotiableQuote\Model\Restriction\Admin::class => null,
Magento\AsynchronousOperations\Model\BulkManagement::class => null,
Magento\SalesRule\Model\Service\CouponUsagePublisher::class => null,
Magento\Paypal\Model\Api\Nvp\Interceptor::class => null,
Magento\PurchaseOrder\Model\PurchaseOrder\LogManagement::class => null,
Magento\Customer\Model\Metadata\AddressMetadata::class => null,
Magento\Customer\Model\Metadata\AddressCachedMetadata::class => null,
Magento\Framework\DB\Select\RendererProxy::class => null,
Magento\Framework\DB\SelectFactory::class => null,
Magento\Quote\Api\Data\CartItemExtension::class => null,
Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option\Interceptor::class => null,
Magento\OfflineShipping\Model\Carrier\Flatrate::class => null,
Magento\Quote\Model\Quote\Payment::class => null,
Magento\Sales\Model\Order\Address\Renderer::class => null,
Magento\Sales\Model\Order\Status::class => null,
Magento\CatalogInventory\Model\Indexer\Stock\Action\Rows::class => null,
Magento\CatalogInventory\Model\ResourceModel\Indexer\Stock\DefaultStock::class => null,
Magento\ConfigurableProduct\Model\ResourceModel\Indexer\Stock\Configurable::class => null,
Magento\Bundle\Model\ResourceModel\Indexer\Stock::class => null,
Magento\GroupedProduct\Model\ResourceModel\Indexer\Stock\Grouped::class => null,
Magento\Elasticsearch\Model\Adapter\BatchDataMapper\DataMapperResolver::class => null,
Magento\Elasticsearch\Model\Adapter\Elasticsearch::class => null,
Magento\Elasticsearch7\Model\Client\Elasticsearch::class => null,
Magento\Tax\Model\TaxClass\Source\Product::class => null,
Magento\Framework\View\TemplateEnginePool::class => null,
Magento\Framework\View\Element\Template\File\Resolver::class => null,
Magento\Framework\View\Element\Template\File\Validator::class => null,
Magento\Framework\View\Element\Template\Context::class => null,
'validator' => null,
'inlineTranslation' => null,
Magento\Customer\Block\Address\Renderer\DefaultRenderer::class => null,
Magento\Framework\View\Layout\ReaderPool::class => null,
Magento\Framework\View\Layout\Reader\Block::class => null,
Magento\Framework\View\Layout\Reader\UiComponent::class => null,
Magento\PageCache\Observer\ProcessLayoutRenderElement::class => null,
Magento\Staging\Model\Update::class => null,
Magento\Staging\Model\Update\Flag::class => null,
Magento\Catalog\Model\Category\Attribute\Source\Sortby::class => null,
Magento\Config\App\Config\Source\EnvironmentConfigSource::class => null,
Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\Binding::class => null,
Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\Binding\Iterator::class => null,
Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem::class => null,
Magento\Framework\MessageQueue\Topology\Config\QueueConfigItem::class => null,
Magento\Framework\MessageQueue\Topology\Config\QueueConfigItem\DataMapper::class => null,
// phpcs:enable Generic.Files.LineLength.TooLong
],
'' => [
],
];
@@ -0,0 +1,47 @@
<?php
/**
* Default application path for backend area
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Backend\App;
use Magento\Framework\App\Config\ScopeConfigInterface;
/**
* Backend config accessor.
*/
class Config extends \Magento\Backend\App\Config
{
/**
* @var \Magento\TestFramework\App\MutableScopeConfig
*/
private $mutableScopeConfig;
/**
* Config constructor.
* @param \Magento\TestFramework\App\Config $appConfig
* @param \Magento\TestFramework\App\MutableScopeConfig $mutableScopeConfig
*/
public function __construct(
\Magento\TestFramework\App\Config $appConfig,
\Magento\TestFramework\App\MutableScopeConfig $mutableScopeConfig
) {
parent::__construct($appConfig);
$this->mutableScopeConfig = $mutableScopeConfig;
}
/**
* @inheritdoc
*/
public function setValue(
$path,
$value,
$scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
$scopeCode = null
) {
$this->mutableScopeConfig->setValue($path, $value, $scope, $scopeCode);
}
}
@@ -0,0 +1,133 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework;
/**
* Bootstrap for the integration testing environment
*/
class Bootstrap
{
/**#@+
* Predefined admin user credentials
*/
public const ADMIN_NAME = 'user';
public const ADMIN_PASSWORD = 'password1';
public const ADMIN_EMAIL = 'admin@example.com';
public const ADMIN_FIRSTNAME = 'firstname';
public const ADMIN_LASTNAME = 'lastname';
/**#@- */
/**
* Predefined admin user role name
*/
public const ADMIN_ROLE_NAME = 'Administrators';
public const ADMIN_ROLE_ID = 1;
/**
* @var \Magento\TestFramework\Bootstrap\Settings
*/
private $_settings;
/**
* @var \Magento\TestFramework\Application
*/
private $_application;
/**
* @var \Magento\TestFramework\Bootstrap\Environment
*/
private $_envBootstrap;
/**
* @var \Magento\TestFramework\Bootstrap\DocBlock
*/
private $_docBlockBootstrap;
/**
* @var \Magento\TestFramework\Bootstrap\Profiler
*/
private $_profilerBootstrap;
/**
* @var \Magento\Framework\Shell
*/
private $_shell;
/**
* @var \Magento\TestFramework\Bootstrap\MemoryFactory
*/
private $memoryFactory;
/**
* Constructor
*
* @param \Magento\TestFramework\Bootstrap\Settings $settings
* @param \Magento\TestFramework\Bootstrap\Environment $envBootstrap
* @param \Magento\TestFramework\Bootstrap\DocBlock $docBlockBootstrap
* @param \Magento\TestFramework\Bootstrap\Profiler $profilerBootstrap
* @param \Magento\Framework\Shell $shell
* @param Application $application
* @param Bootstrap\MemoryFactory $memoryFactory
* @internal param string $tmpDir
*/
public function __construct(
\Magento\TestFramework\Bootstrap\Settings $settings,
\Magento\TestFramework\Bootstrap\Environment $envBootstrap,
\Magento\TestFramework\Bootstrap\DocBlock $docBlockBootstrap,
\Magento\TestFramework\Bootstrap\Profiler $profilerBootstrap,
\Magento\Framework\Shell $shell,
\Magento\TestFramework\Application $application,
\Magento\TestFramework\Bootstrap\MemoryFactory $memoryFactory
) {
$this->_settings = $settings;
$this->_envBootstrap = $envBootstrap;
$this->_docBlockBootstrap = $docBlockBootstrap;
$this->_profilerBootstrap = $profilerBootstrap;
$this->_shell = $shell;
$this->_application = $application;
$this->memoryFactory = $memoryFactory;
}
/**
* Retrieve the application instance
*
* @return Application
*/
public function getApplication()
{
return $this->_application;
}
/**
* Perform bootstrap actions required to completely setup the testing environment
*/
public function runBootstrap()
{
$this->_envBootstrap->emulateHttpRequest($_SERVER);
$this->_envBootstrap->emulateSession($_SESSION);
$profilerOutputFile = $this->_settings->getAsFile('TESTS_PROFILER_FILE');
if ($profilerOutputFile) {
$this->_profilerBootstrap->registerFileProfiler($profilerOutputFile);
}
$profilerBambooOutputFile = $this->_settings->getAsFile('TESTS_BAMBOO_PROFILER_FILE');
$profilerBambooMetricsFile = $this->_settings->getAsFile('TESTS_BAMBOO_PROFILER_METRICS_FILE');
if ($profilerBambooOutputFile && $profilerBambooMetricsFile) {
$this->_profilerBootstrap->registerBambooProfiler($profilerBambooOutputFile, $profilerBambooMetricsFile);
}
$memoryBootstrap = $this->memoryFactory->create(
$this->_settings->get('TESTS_MEM_USAGE_LIMIT', 0),
$this->_settings->get('TESTS_MEM_LEAK_LIMIT', 0)
);
$memoryBootstrap->activateStatsDisplaying();
$memoryBootstrap->activateLimitValidation();
$this->_docBlockBootstrap->registerAnnotations($this->_application);
}
}
@@ -0,0 +1,82 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Bootstrap;
use Magento\TestFramework\Application;
/**
* Bootstrap of the custom DocBlock annotations
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class DocBlock
{
/**
* @var string
*/
protected $_fixturesBaseDir;
/**
* @param string $fixturesBaseDir
*/
public function __construct($fixturesBaseDir)
{
$this->_fixturesBaseDir = $fixturesBaseDir;
}
/**
* Activate custom DocBlock annotations along with more-or-less permanent workarounds
*
* @param Application $application
*/
public function registerAnnotations(Application $application)
{
$eventManager = new \Magento\TestFramework\EventManager($this->_getSubscribers($application));
\Magento\TestFramework\Event\PhpUnit::setDefaultEventManager($eventManager);
\Magento\TestFramework\Event\Magento::setDefaultEventManager($eventManager);
}
/**
* Get list of subscribers.
*
* Note: order of registering (and applying) annotations is important.
* To allow config fixtures to deal with fixture stores, data fixtures should be processed first.
* ConfigFixture applied twice because data fixtures could clean config and clean custom settings
*
* @param Application $application
* @return array
*/
protected function _getSubscribers(Application $application)
{
return [
new \Magento\TestFramework\Workaround\Segfault(),
new \Magento\TestFramework\Workaround\Cleanup\TestCaseProperties(),
new \Magento\TestFramework\Workaround\Cleanup\StaticProperties(),
new \Magento\TestFramework\Isolation\FlushDataFixtureStorage(),
new \Magento\TestFramework\Isolation\WorkingDirectory(),
new \Magento\TestFramework\Isolation\DeploymentConfig(),
new \Magento\TestFramework\Workaround\Override\Fixture\Resolver\TestSetter(),
new \Magento\TestFramework\Annotation\AppIsolation($application),
new \Magento\TestFramework\Annotation\IndexerDimensionMode(),
new \Magento\TestFramework\Isolation\AppConfig(),
new \Magento\TestFramework\Annotation\ConfigFixture(),
new \Magento\TestFramework\Annotation\DataFixtureBeforeTransaction(),
new \Magento\TestFramework\Event\Transaction(
new \Magento\TestFramework\EventManager(
[
new \Magento\TestFramework\Annotation\DbIsolation(),
new \Magento\TestFramework\Annotation\DataFixture(),
]
)
),
new \Magento\TestFramework\Annotation\ComponentRegistrarFixture($this->_fixturesBaseDir),
new \Magento\TestFramework\Annotation\AppArea($application),
new \Magento\TestFramework\Annotation\Cache(),
new \Magento\TestFramework\Annotation\AdminConfigFixture(),
new \Magento\TestFramework\Annotation\ConfigFixture(),
];
}
}
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Bootstrap of the HTTP environment
*/
namespace Magento\TestFramework\Bootstrap;
class Environment
{
/**
* Emulate properties typical to an HTTP request
*
* @param array $serverVariables
*/
public function emulateHttpRequest(array &$serverVariables)
{
// emulate HTTP request
$serverVariables['HTTP_HOST'] = 'localhost';
// emulate entry point to ensure that tests generate invariant URLs
$serverVariables['SCRIPT_FILENAME'] = 'index.php';
}
/**
* Emulate already started PHP session
*
* @param array|null $sessionVariables
*/
public function emulateSession(&$sessionVariables)
{
// prevent session_start, because it may rely on cookies
$sessionVariables = [];
// application relies on a non-empty session ID
session_id(uniqid());
}
}
@@ -0,0 +1,68 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Bootstrap of the memory monitoring
*/
namespace Magento\TestFramework\Bootstrap;
class Memory
{
/**
* Policy to perform requested actions on shutdown
*/
const POLICY_SHUTDOWN = 'register_shutdown_function';
/**
* @var \Magento\TestFramework\MemoryLimit
*/
private $_memoryLimit;
/**
* @var callable
*/
private $_activationPolicy;
/**
* @param \Magento\TestFramework\MemoryLimit $memoryLimit
* @param callable|string $activationPolicy
* @throws \InvalidArgumentException
*/
public function __construct(
\Magento\TestFramework\MemoryLimit $memoryLimit,
$activationPolicy = self::POLICY_SHUTDOWN
) {
if (!is_callable($activationPolicy)) {
throw new \InvalidArgumentException('Activation policy is expected to be a callable.');
}
$this->_memoryLimit = $memoryLimit;
$this->_activationPolicy = $activationPolicy;
}
/**
* Display memory usage statistics
*/
public function displayStats()
{
echo $this->_memoryLimit->printHeader() . $this->_memoryLimit->printStats() . PHP_EOL;
}
/**
* Activate displaying of the memory usage statistics
*/
public function activateStatsDisplaying()
{
call_user_func($this->_activationPolicy, [$this, 'displayStats']);
}
/**
* Activate validation of the memory usage/leak limitations
*/
public function activateLimitValidation()
{
call_user_func($this->_activationPolicy, [$this->_memoryLimit, 'validateUsage']);
}
}
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Bootstrap;
class MemoryFactory
{
/**
* @var \Magento\Framework\Shell
*/
private $shell;
/**
* @param \Magento\Framework\Shell $shell
*/
public function __construct(\Magento\Framework\Shell $shell)
{
$this->shell = $shell;
}
/**
* @param string $memUsageLimit
* @param string $memLeakLimit
* @return Memory
*/
public function create($memUsageLimit, $memLeakLimit)
{
return new \Magento\TestFramework\Bootstrap\Memory(
new \Magento\TestFramework\MemoryLimit(
$memUsageLimit,
$memLeakLimit,
new \Magento\TestFramework\Helper\Memory($this->shell)
)
);
}
}
@@ -0,0 +1,77 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Bootstrap of the application profiler
*/
namespace Magento\TestFramework\Bootstrap;
class Profiler
{
/**
* Profiler driver instance
*
* @var \Magento\Framework\Profiler\Driver\Standard
*/
protected $_driver;
/**
* Whether a profiler driver has been already registered or not
*
* @var bool
*/
protected $_isDriverRegistered = false;
/**
* Constructor
*
* @param \Magento\Framework\Profiler\Driver\Standard $driver
*/
public function __construct(\Magento\Framework\Profiler\Driver\Standard $driver)
{
$this->_driver = $driver;
}
/**
* Register profiler driver to involve it into the results processing
*/
protected function _registerDriver()
{
if (!$this->_isDriverRegistered) {
$this->_isDriverRegistered = true;
\Magento\Framework\Profiler::add($this->_driver);
}
}
/**
* Register file-based profiling
*
* @param string $profilerOutputFile
*/
public function registerFileProfiler($profilerOutputFile)
{
$this->_registerDriver();
$this->_driver->registerOutput(
new \Magento\Framework\Profiler\Driver\Standard\Output\Csvfile(['filePath' => $profilerOutputFile])
);
}
/**
* Register profiler with Bamboo-friendly output format
*
* @param string $profilerOutputFile
* @param string $profilerMetricsFile
*/
public function registerBambooProfiler($profilerOutputFile, $profilerMetricsFile)
{
$this->_registerDriver();
$this->_driver->registerOutput(
new \Magento\TestFramework\Profiler\OutputBamboo(
['filePath' => $profilerOutputFile, 'metrics' => require $profilerMetricsFile]
)
);
}
}
@@ -0,0 +1,152 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Bootstrap;
use Magento\Framework\Filesystem\Glob;
/**
* Convenient access to the bootstrap settings
*/
class Settings
{
/**
* Base directory to be used to resolve relative paths
*
* @var string
*/
private $_baseDir;
/**
* Key-value pairs of the settings
*
* @var array
*/
private $_settings = [];
/**
* Constructor
*
* @param string $baseDir
* @param array $settings
* @throws \InvalidArgumentException
*/
public function __construct($baseDir, array $settings)
{
if (!is_dir($baseDir)) {
throw new \InvalidArgumentException("Base path '{$baseDir}' has to be an existing directory.");
}
$this->_baseDir = realpath($baseDir);
$this->_settings = $settings;
}
/**
* Retrieve a setting value as is
*
* @param string $settingName
* @param mixed $defaultValue
* @return mixed
*/
public function get($settingName, $defaultValue = null)
{
return array_key_exists($settingName, $this->_settings) ? $this->_settings[$settingName] : $defaultValue;
}
/**
* Interpret a setting value as a switch and return TRUE when it equals to the string "enabled" or FALSE otherwise
*
* @param string $settingName
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function getAsBoolean($settingName)
{
return $this->get($settingName) === 'enabled';
}
/**
* Interpret a setting value as a relative file name and return absolute path to it
*
* @param string $settingName
* @param string $defaultValue
* @return string
*/
public function getAsFile($settingName, $defaultValue = '')
{
$result = $this->get($settingName, $defaultValue);
if ($result !== '') {
$result = $this->_resolvePath($result);
}
return $result;
}
/**
* Interpret a setting value as a file optionally falling back to the '.dist' file and return absolute path to it
*
* @param string $settingName
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getAsConfigFile($settingName)
{
$result = $this->getAsFile($settingName);
if ($result !== '') {
if (!is_file($result) && substr($result, -5) != '.dist') {
$result .= '.dist';
}
if (is_file($result)) {
return $result;
}
}
throw new \Magento\Framework\Exception\LocalizedException(
__("Setting '%1' specifies the non-existing file '%2'.", $settingName, $result)
);
}
/**
* Interpret a setting value as a semicolon-separated relative glob pattern(s) and return matched absolute paths
*
* @param string $settingName
* @return array
*/
public function getAsMatchingPaths($settingName)
{
$settingValue = $this->get($settingName, '');
if ($settingValue !== '') {
return $this->_resolvePathPattern($settingValue);
}
return [];
}
/**
* Return an absolute path by a relative one without checking its validity
*
* @param string $relativePath
* @return string
*/
protected function _resolvePath($relativePath)
{
return $this->_baseDir . '/' . $relativePath;
}
/**
* Resolve semicolon-separated relative glob pattern(s) to matched absolute paths
*
* @param string $pattern
* @return array
*/
protected function _resolvePathPattern($pattern)
{
$result = [];
$allPatterns = preg_split('/\s*;\s*/', trim($pattern), -1, PREG_SPLIT_NO_EMPTY);
foreach ($allPatterns as $onePattern) {
$onePattern = $this->_resolvePath($onePattern);
$files = Glob::glob($onePattern, Glob::GLOB_BRACE);
$result = array_merge($result, $files);
}
return $result;
}
}
@@ -0,0 +1,90 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Bundle\Model;
use Magento\Bundle\Api\Data\LinkInterfaceFactory;
use Magento\Bundle\Api\Data\OptionInterfaceFactory;
use Magento\Bundle\Model\Product\Price;
use Magento\Catalog\Api\Data\ProductExtensionFactory;
use Magento\Catalog\Api\Data\ProductInterface;
/**
* Prepare bundle product links
*/
class PrepareBundleLinks
{
/** @var LinkInterfaceFactory */
private $linkFactory;
/** @var OptionInterfaceFactory */
private $optionLinkFactory;
/** @var ProductExtensionFactory */
private $extensionAttributesFactory;
/**
* @param LinkInterfaceFactory $linkFactory
* @param OptionInterfaceFactory $optionLinkFactory
* @param ProductExtensionFactory $extensionAttributesFactory
*/
public function __construct(
LinkInterfaceFactory $linkFactory,
OptionInterfaceFactory $optionLinkFactory,
ProductExtensionFactory $extensionAttributesFactory
) {
$this->linkFactory = $linkFactory;
$this->optionLinkFactory = $optionLinkFactory;
$this->extensionAttributesFactory = $extensionAttributesFactory;
}
/**
* Prepare bundle product links
*
* @param ProductInterface $product
* @param array $bundleOptionsData
* @param array $bundleSelectionsData
* @return ProductInterface
*/
public function execute(
ProductInterface $product,
array $bundleOptionsData,
array $bundleSelectionsData
): ProductInterface {
$product->setBundleOptionsData($bundleOptionsData)
->setBundleSelectionsData($bundleSelectionsData);
$options = [];
foreach ($product->getBundleOptionsData() as $key => $optionData) {
$option = $this->optionLinkFactory->create(['data' => $optionData]);
$option->setSku($product->getSku());
$optionId = $optionData['option_id'] ?? null;
$option->setOptionId($optionId);
$links = [];
$bundleLinks = $product->getBundleSelectionsData();
foreach ($bundleLinks[$key] as $linkData) {
$link = $this->linkFactory->create(['data' => $linkData]);
$link->setQty($linkData['selection_qty']);
$priceType = $price = null;
if ((int)$product->getPriceType() === Price::PRICE_TYPE_FIXED) {
$priceType = $linkData['selection_price_type'] ?? null;
$price = $linkData['selection_price_value'] ?? null;
}
$link->setPriceType($priceType);
$link->setPrice($price);
$links[] = $link;
}
$option->setProductLinks($links);
$options[] = $option;
}
/** @var ProductExtensionFactory $extensionAttributesFactory */
$extensionAttributes = $product->getExtensionAttributes() ?? $this->extensionAttributesFactory->create();
$extensionAttributes->setBundleProductOptions($options);
$product->setExtensionAttributes($extensionAttributes);
return $product;
}
}
@@ -0,0 +1,211 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Block\Product\View\Options;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Config\Source\ProductPriceOptionsInterface;
use Magento\Catalog\Model\Product\Option;
/**
* Data provider with product custom options from date group(date, date & time, time).
*/
class DateGroupDataProvider
{
/**
* Return options data.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
* @return array
*/
public function getData(): array
{
return [
'type_date_required' => [
[
Option::KEY_TITLE => 'Test option date title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-date-title-1',
],
[
'block_with_required_class' => '<div class="field date required"',
'title' => '<span>Test option date title 1</span>',
'price' => 'data-price-amount="10"',
],
],
'type_date_not_required' => [
[
Option::KEY_TITLE => 'Test option date title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-date-title-2',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option date title 2</span>',
'price' => 'data-price-amount="10"',
],
],
'type_date_fixed_price' => [
[
Option::KEY_TITLE => 'Test option date title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-date-title-3',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option date title 3</span>',
'price' => 'data-price-amount="50"',
],
],
'type_date_percent_price' => [
[
Option::KEY_TITLE => 'Test option date title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_SKU => 'test-option-date-title-4',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option date title 4</span>',
'price' => 'data-price-amount="5"',
],
],
'type_date_and_time_required' => [
[
Option::KEY_TITLE => 'Test option date and time title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-date-and-time-title-1',
],
[
'block_with_required_class' => '<div class="field date required"',
'title' => '<span>Test option date and time title 1</span>',
'price' => 'data-price-amount="10"',
],
],
'type_date_and_time_not_required' => [
[
Option::KEY_TITLE => 'Test option date and time title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-date-and-time-title-2',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option date and time title 2</span>',
'price' => 'data-price-amount="10"',
],
],
'type_date_and_time_fixed_price' => [
[
Option::KEY_TITLE => 'Test option date and time title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-date-and-time-title-3',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option date and time title 3</span>',
'price' => 'data-price-amount="50"',
],
],
'type_date_and_time_percent_price' => [
[
Option::KEY_TITLE => 'Test option date and time title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_SKU => 'test-option-date-and-time-title-4',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option date and time title 4</span>',
'price' => 'data-price-amount="5"',
],
],
'type_time_required' => [
[
Option::KEY_TITLE => 'Test option time title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_TIME,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-time-title-1',
],
[
'block_with_required_class' => '<div class="field date required"',
'title' => '<span>Test option time title 1</span>',
'price' => 'data-price-amount="10"',
],
],
'type_time_not_required' => [
[
Option::KEY_TITLE => 'Test option time title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_TIME,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-time-title-2',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option time title 2</span>',
'price' => 'data-price-amount="10"',
],
],
'type_time_fixed_price' => [
[
Option::KEY_TITLE => 'Test option time title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_TIME,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-time-title-3',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option time title 3</span>',
'price' => 'data-price-amount="50"',
],
],
'type_time_percent_price' => [
[
Option::KEY_TITLE => 'Test option time title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_TIME,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_SKU => 'test-option-time-title-4',
],
[
'block_with_required_class' => '<div class="field date"',
'title' => '<span>Test option time title 4</span>',
'price' => 'data-price-amount="5"',
],
],
];
}
}
@@ -0,0 +1,135 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Block\Product\View\Options;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Config\Source\ProductPriceOptionsInterface;
use Magento\Catalog\Model\Product\Option;
/**
* Data provider with product custom options from file group(file).
*/
class FileGroupDataProvider
{
/**
* Return options data.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
* @return array
*/
public function getData(): array
{
return [
'type_file_required' => [
[
Option::KEY_TITLE => 'Test option file title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FILE,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-file-title-1',
Option::KEY_SORT_ORDER => 1,
Option::KEY_FILE_EXTENSION => 'png, jpg',
],
[
'block_with_required_class' => '<div class="field file required">',
'label_for_created_option' => '<label class="label" for="options_%s_file"',
'title' => '<span>Test option file title 1</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<input type="file"/',
'file_extension' => '<strong>png, jpg</strong>',
],
],
'type_file_not_required' => [
[
Option::KEY_TITLE => 'Test option file title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FILE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-file-title-2',
Option::KEY_SORT_ORDER => 1,
Option::KEY_FILE_EXTENSION => 'png, jpg',
],
[
'block_with_required_class' => '<div class="field file">',
'label_for_created_option' => '<label class="label" for="options_%s_file"',
'title' => '<span>Test option file title 2</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<input type="file"/',
'file_extension' => '<strong>png, jpg</strong>',
],
],
'type_file_fixed_price' => [
[
Option::KEY_TITLE => 'Test option file title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FILE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-file-title-3',
Option::KEY_SORT_ORDER => 1,
Option::KEY_FILE_EXTENSION => 'png, jpg',
],
[
'block_with_required_class' => '<div class="field file">',
'label_for_created_option' => '<label class="label" for="options_%s_file"',
'title' => '<span>Test option file title 3</span>',
'price' => 'data-price-amount="50"',
'required_element' => '/<input type="file"/',
'file_extension' => '<strong>png, jpg</strong>',
],
],
'type_file_percent_price' => [
[
Option::KEY_TITLE => 'Test option file title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FILE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_SKU => 'test-option-file-title-4',
Option::KEY_SORT_ORDER => 1,
Option::KEY_FILE_EXTENSION => 'png, jpg',
],
[
'block_with_required_class' => '<div class="field file">',
'label_for_created_option' => '<label class="label" for="options_%s_file"',
'title' => '<span>Test option file title 4</span>',
'price' => 'data-price-amount="5"',
'required_element' => '/<input type="file"/',
'file_extension' => '<strong>png, jpg</strong>',
],
],
'type_file_with_width_and_height' => [
[
Option::KEY_TITLE => 'Test option file title 5',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FILE,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-file-title-5',
Option::KEY_SORT_ORDER => 1,
Option::KEY_FILE_EXTENSION => 'png, jpg',
Option::KEY_IMAGE_SIZE_X => 10,
Option::KEY_IMAGE_SIZE_Y => 81,
],
[
'block_with_required_class' => '<div class="field file">',
'label_for_created_option' => '<label class="label" for="options_%s_file"',
'title' => '<span>Test option file title 5</span>',
'price' => 'data-price-amount="50"',
'required_element' => '/<input type="file"/',
'file_extension' => '<strong>png, jpg</strong>',
'file_width' => '/%s:.*<strong>10 px.<\/strong>/',
'file_height' => '/%s:.*<strong>81 px.<\/strong>/',
],
],
];
}
}
@@ -0,0 +1,364 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Block\Product\View\Options;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Config\Source\ProductPriceOptionsInterface;
use Magento\Catalog\Model\Product\Option;
use Magento\Catalog\Model\Product\Option\Value;
/**
* Data provider with product custom options from select group(drop-down, radio buttons, checkbox, multiple select).
*/
class SelectGroupDataProvider
{
/**
* Return options data.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
* @return array
*/
public function getData(): array
{
return [
'type_drop_down_required' => [
[
Option::KEY_TITLE => 'Test option drop-down title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Test option drop-down title 1 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-drop-down-title-1-value-1',
],
[
'block_with_required_class' => '<div class="field required">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option drop-down title 1</span>',
'required_element' => '/<select/',
'option_value_item' => '/<option value="%s" price="10" >%s \+\s{11}\$10.00.*/',
'not_contain_arr' => [
'/<select.*multiple="multiple"/',
],
],
],
'type_drop_down_not_required' => [
[
Option::KEY_TITLE => 'Test option drop-down title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option drop-down title 2 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-drop-down-title-2-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option drop-down title 2</span>',
'required_element' => '/<select/',
'option_value_item' => '/<option value="%s" price="10" >%s \+\s{11}\$10.00.*/',
'not_contain_arr' => [
'/<select.*multiple="multiple"/',
],
],
],
'type_drop_down_value_fixed_price' => [
[
Option::KEY_TITLE => 'Test option drop-down title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option drop-down title 3 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-drop-down-title-3-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option drop-down title 3</span>',
'required_element' => '/<select/',
'option_value_item' => '/<option value="%s" price="50" >%s \+\s{11}\$50.00.*/',
'not_contain_arr' => [
'/<select.*multiple="multiple"/',
],
],
],
'type_drop_down_value_percent_price' => [
[
Option::KEY_TITLE => 'Test option drop-down title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option drop-down title 4 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Value::KEY_SKU => 'test-option-drop-down-title-4-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option drop-down title 4</span>',
'required_element' => '/<select/',
'option_value_item' => '/<option value="%s" price="5" >%s \+\s{11}\$5.00.*/',
'not_contain_arr' => [
'/<select.*multiple="multiple"/',
],
],
],
'type_radio_button_required' => [
[
Option::KEY_TITLE => 'Test option radio-button title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Test option radio-button title 1 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-radio-button-title-1-value-1',
],
[
'block_with_required_class' => '<div class="field required">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option radio-button title 1</span>',
'required_element' => '/<input type="radio"/',
'price' => 'data-price-amount="10"',
],
],
'type_radio_button_not_required' => [
[
Option::KEY_TITLE => 'Test option radio-button title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option radio-button title 2 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-radio-button-title-2-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option radio-button title 2</span>',
'required_element' => '/<input type="radio"/',
'price' => 'data-price-amount="10"',
],
],
'type_radio_button_value_fixed_price' => [
[
Option::KEY_TITLE => 'Test option radio-button title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option radio-button title 3 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-radio-button-title-3-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option radio-button title 3</span>',
'required_element' => '/<input type="radio"/',
'price' => 'data-price-amount="50"',
],
],
'type_radio_button_value_percent_price' => [
[
Option::KEY_TITLE => 'Test option radio-button title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_RADIO,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option radio-button title 4 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Value::KEY_SKU => 'test-option-radio-button-title-4-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option radio-button title 4</span>',
'required_element' => '/<input type="radio"/',
'price' => 'data-price-amount="5"',
],
],
'type_checkbox_required' => [
[
Option::KEY_TITLE => 'Test option checkbox title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Test option checkbox title 1 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-checkbox-title-1-value-1',
],
[
'block_with_required_class' => '<div class="field required">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option checkbox title 1</span>',
'required_element' => '/<input type="checkbox"/',
'price' => 'data-price-amount="10"',
],
],
'type_checkbox_not_required' => [
[
Option::KEY_TITLE => 'Test option checkbox title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option checkbox title 2 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-checkbox-title-2-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option checkbox title 2</span>',
'required_element' => '/<input type="checkbox"/',
'price' => 'data-price-amount="10"',
],
],
'type_checkbox_value_fixed_price' => [
[
Option::KEY_TITLE => 'Test option checkbox title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option checkbox title 3 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-checkbox-title-3-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option checkbox title 3</span>',
'required_element' => '/<input type="checkbox"/',
'price' => 'data-price-amount="50"',
],
],
'type_checkbox_value_percent_price' => [
[
Option::KEY_TITLE => 'Test option checkbox title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option checkbox title 4 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Value::KEY_SKU => 'test-option-checkbox-title-4-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option checkbox title 4</span>',
'required_element' => '/<input type="checkbox"/',
'price' => 'data-price-amount="5"',
],
],
'type_multiselect_required' => [
[
Option::KEY_TITLE => 'Test option multiselect title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE,
Option::KEY_IS_REQUIRE => 1,
],
[
Value::KEY_TITLE => 'Test option multiselect title 1 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-multiselect-title-1-value-1',
],
[
'block_with_required_class' => '<div class="field required">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option multiselect title 1</span>',
'required_element' => '/<select.*multiple="multiple"/',
'option_value_item' => '/<option value="%s" price="10" >%s \+\s{11}\$10.00.*/',
],
],
'type_multiselect_not_required' => [
[
Option::KEY_TITLE => 'Test option multiselect title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option multiselect title 2 value 1',
Value::KEY_PRICE => 10,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-multiselect-title-2-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option multiselect title 2</span>',
'required_element' => '/<select.*multiple="multiple"/',
'option_value_item' => '/<option value="%s" price="10" >%s \+\s{11}\$10.00.*/',
],
],
'type_multiselect_value_fixed_price' => [
[
Option::KEY_TITLE => 'Test option multiselect title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option multiselect title 3 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Value::KEY_SKU => 'test-option-multiselect-title-3-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option multiselect title 3</span>',
'required_element' => '/<select.*multiple="multiple"/',
'option_value_item' => '/<option value="%s" price="50" >%s \+\s{11}\$50.00.*/',
],
],
'type_multiselect_value_percent_price' => [
[
Option::KEY_TITLE => 'Test option multiselect title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE,
Option::KEY_IS_REQUIRE => 0,
],
[
Value::KEY_TITLE => 'Test option multiselect title 4 value 1',
Value::KEY_PRICE => 50,
Value::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Value::KEY_SKU => 'test-option-multiselect-title-4-value-1',
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="select_%s">',
'title' => '<span>Test option multiselect title 4</span>',
'required_element' => '/<select.*multiple="multiple"/',
'option_value_item' => '/<option value="%s" price="5" >%s \+\s{11}\$5.00.*/',
],
],
];
}
}
@@ -0,0 +1,213 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Block\Product\View\Options;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Config\Source\ProductPriceOptionsInterface;
use Magento\Catalog\Model\Product\Option;
/**
* Data provider with product custom options from text group(field, area).
*/
class TextGroupDataProvider
{
/**
* Return options data.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
* @return array
*/
public function getData(): array
{
return [
'type_field_required' => [
[
Option::KEY_TITLE => 'Test option field title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-field-title-1',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field required">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option field title 1</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<input type="text"/',
],
],
'type_field_not_required' => [
[
Option::KEY_TITLE => 'Test option field title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-field-title-2',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option field title 2</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<input type="text"/',
],
],
'type_field_fixed_price' => [
[
Option::KEY_TITLE => 'Test option field title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-field-title-3',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option field title 3</span>',
'price' => 'data-price-amount="50"',
'required_element' => '/<input type="text"/',
],
],
'type_field_percent_price' => [
[
Option::KEY_TITLE => 'Test option field title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_SKU => 'test-option-field-title-4',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option field title 4</span>',
'price' => 'data-price-amount="5"',
'required_element' => '/<input type="text"/',
],
],
'type_field_max_characters' => [
[
Option::KEY_TITLE => 'Test option field title 5',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_FIELD,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-field-title-5',
Option::KEY_MAX_CHARACTERS => 99,
],
[
'block_with_required_class' => '<div class="field">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option field title 5</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<input type="text"/',
'max_characters' => 'Maximum 99 characters',
],
],
'type_area_required' => [
[
Option::KEY_TITLE => 'Test option area title 1',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_AREA,
Option::KEY_IS_REQUIRE => 1,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-area-title-1',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field textarea required">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option area title 1</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<textarea/',
],
],
'type_area_not_required' => [
[
Option::KEY_TITLE => 'Test option area title 2',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_AREA,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-area-title-2',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field textarea">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option area title 2</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<textarea/',
],
],
'type_area_fixed_price' => [
[
Option::KEY_TITLE => 'Test option area title 3',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_AREA,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-area-title-3',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field textarea">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option area title 3</span>',
'price' => 'data-price-amount="50"',
'required_element' => '/<textarea/',
],
],
'type_area_percent_price' => [
[
Option::KEY_TITLE => 'Test option area title 4',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_AREA,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 50,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_PERCENT,
Option::KEY_SKU => 'test-option-area-title-4',
Option::KEY_MAX_CHARACTERS => 0,
],
[
'block_with_required_class' => '<div class="field textarea">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option area title 4</span>',
'price' => 'data-price-amount="5"',
'required_element' => '/<textarea/',
],
],
'type_area_max_characters' => [
[
Option::KEY_TITLE => 'Test option area title 5',
Option::KEY_TYPE => ProductCustomOptionInterface::OPTION_TYPE_AREA,
Option::KEY_IS_REQUIRE => 0,
Option::KEY_PRICE => 10,
Option::KEY_PRICE_TYPE => ProductPriceOptionsInterface::VALUE_FIXED,
Option::KEY_SKU => 'test-option-area-title-5',
Option::KEY_MAX_CHARACTERS => 99,
],
[
'block_with_required_class' => '<div class="field textarea">',
'label_for_created_option' => '<label class="label" for="options_%s_text">',
'title' => '<span>Test option area title 5</span>',
'price' => 'data-price-amount="10"',
'required_element' => '/<textarea/',
'max_characters' => 'Maximum 99 characters',
],
],
];
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category\Attribute\LayoutUpdateManager;
/**
* Easy way to fake available files.
*/
class CategoryLayoutUpdateManager extends LayoutUpdateManager
{
/**
* @var array Keys are category IDs, values - file names.
*/
private $fakeFiles = [];
/**
* Supply fake files for a category.
*
* @param int $forCategoryId
* @param string[]|null $files Pass null to reset.
*/
public function setCategoryFakeFiles(int $forCategoryId, ?array $files): void
{
if ($files === null) {
unset($this->fakeFiles[$forCategoryId]);
} else {
$this->fakeFiles[$forCategoryId] = $files;
}
}
/**
* @inheritDoc
*/
public function fetchAvailableFiles(CategoryInterface $category): array
{
if (array_key_exists($category->getId(), $this->fakeFiles)) {
return $this->fakeFiles[$category->getId()];
}
return parent::fetchAvailableFiles($category);
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
/**
* Load category by category name
*/
class GetCategoryByName
{
/** @var CollectionFactory */
private $categoryCollectionFactory;
/**
* @param CollectionFactory $categoryCollectionFactory
*/
public function __construct(CollectionFactory $categoryCollectionFactory)
{
$this->categoryCollectionFactory = $categoryCollectionFactory;
}
/**
* Load category by name.
*
* @param string $categoryName
* @return CategoryInterface
*/
public function execute(string $categoryName): CategoryInterface
{
$categoryCollection = $this->categoryCollectionFactory->create();
return $categoryCollection->addAttributeToFilter(CategoryInterface::KEY_NAME, $categoryName)
->setPageSize(1)
->getFirstItem();
}
}
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Indexer\Category\Product\Action;
use Magento\Catalog\Model\Indexer\Category\Product\Action\Full as OriginFull;
/**
* Class Full reindex action
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Full extends OriginFull
{
//
}
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\SearchFactory;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
/**
* Quick search products by query.
*/
class QuickSearchByQuery
{
/**
* @var SearchFactory
*/
private $searchFactory;
/**
* @param SearchFactory $searchFactory
*/
public function __construct(
SearchFactory $searchFactory
) {
$this->searchFactory = $searchFactory;
}
/**
* Flush search instances cache and find products by search query.
*
* @param string $query
* @param string $sortedField
* @param string $sortOrder
* @return Collection
*/
public function execute(
string $query,
string $sortedField = 'relevance',
string $sortOrder = 'desc'
): Collection {
$productCollection = $this->searchFactory->create()->getProductCollection();
$productCollection->addSearchFilter($query);
$productCollection->setOrder($sortedField, $sortOrder);
return $productCollection;
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\TestFramework\Eav\Model\Attribute\DataProvider\AbstractBaseAttributeData;
use Magento\Store\Model\Store;
use Magento\Catalog\Model\Product\Attribute\Backend\Price as BackendPrice;
/**
* Product attribute data for attribute with input type weee.
*/
class Decimal extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['is_filterable'] = '0';
$this->defaultAttributePostData['is_filterable_in_search'] = '0';
$this->defaultAttributePostData['used_for_sort_by'] = '0';
}
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
$result = parent::getAttributeData();
unset($result["{$this->getFrontendInput()}_with_default_value"]);
unset($result["{$this->getFrontendInput()}_without_default_value"]);
return $result;
}
/**
* @inheritdoc
*/
public function getAttributeDataWithCheckArray(): array
{
$result = parent::getAttributeDataWithCheckArray();
unset($result["{$this->getFrontendInput()}_with_default_value"]);
unset($result["{$this->getFrontendInput()}_without_default_value"]);
return $result;
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'decimal_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'price';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Decimal Attribute Update',
],
'frontend_input' => 'price',
'is_required' => '1',
'is_unique' => '1',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_filterable' => '2',
'is_filterable_in_search' => '1',
'position' => '2',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '1',
'used_in_product_listing' => '0',
'used_for_sort_by' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
return array_merge(
$updatePostData,
[
'frontend_label' => 'Decimal Attribute Update',
'attribute_code' => 'decimal_attribute',
'is_global' => ScopedAttributeInterface::SCOPE_GLOBAL,
'default_value' => null,
'frontend_class' => null,
'is_user_defined' => '1',
'backend_type' => 'decimal',
'backend_model' => BackendPrice::class,
]
);
}
}
@@ -0,0 +1,132 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider;
use Magento\Catalog\Model\Product\Attribute\Frontend\Image;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\Eav\Model\Attribute\DataProvider\AbstractBaseAttributeData;
/**
* Product attribute data for attribute with input type media image.
*/
class MediaImage extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['used_for_sort_by'] = '0';
}
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
$result = parent::getAttributeData();
unset($result["{$this->getFrontendInput()}_with_default_value"]);
unset($result["{$this->getFrontendInput()}_without_default_value"]);
return $result;
}
/**
* @inheritdoc
*/
public function getAttributeDataWithCheckArray(): array
{
$result = parent::getAttributeDataWithCheckArray();
unset($result["{$this->getFrontendInput()}_with_default_value"]);
unset($result["{$this->getFrontendInput()}_without_default_value"]);
return $result;
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'image_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'media_image';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Decimal Attribute Update',
],
'frontend_input' => 'media_image',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
return array_merge(
$updatePostData,
[
'frontend_label' => 'Decimal Attribute Update',
'is_required' => '0',
'attribute_code' => 'image_attribute',
'default_value' => null,
'is_unique' => '0',
'frontend_class' => null,
'is_searchable' => '0',
'search_weight' => '1',
'is_visible_in_advanced_search' => '0',
'is_comparable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'position' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '1',
'used_for_sort_by' => '0',
'is_user_defined' => '1',
'backend_type' => 'varchar',
'frontend_model' => Image::class,
]
);
}
}
@@ -0,0 +1,172 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
/**
* Base custom options data provider.
*/
abstract class AbstractBase
{
/**
* Return data for create options for all cases.
*
* @return array
*/
public function getDataForCreateOptions(): array
{
return [
"type_{$this->getType()}_title" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_required_options" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_not_required_options" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 0,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_options_with_fixed_price" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_options_with_percent_price" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'percent',
],
],
"type_{$this->getType()}_price" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 22,
'price_type' => 'percent',
],
],
"type_{$this->getType()}_sku" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 22,
'price_type' => 'percent',
],
],
];
}
/**
* Return data for create options for all cases.
*
* @return array
*/
public function getDataForUpdateOptions(): array
{
return array_merge_recursive(
$this->getDataForCreateOptions(),
[
"type_{$this->getType()}_title" => [
[
'title' => 'Test updated option title',
]
],
"type_{$this->getType()}_required_options" => [
[
'is_require' => 0,
],
],
"type_{$this->getType()}_not_required_options" => [
[
'is_require' => 1,
],
],
"type_{$this->getType()}_options_with_fixed_price" => [
[
'price_type' => 'percent',
],
],
"type_{$this->getType()}_options_with_percent_price" => [
[
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_price" => [
[
'price' => 60,
],
],
"type_{$this->getType()}_sku" => [
[
'sku' => 'Updated option sku',
],
],
]
);
}
/**
* Return option type.
*
* @return string
*/
abstract protected function getType(): string;
}
@@ -0,0 +1,199 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractBase;
/**
* Abstract data provider for options from select group.
*/
abstract class AbstractSelect extends AbstractBase
{
/**
* @inheritdoc
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function getDataForCreateOptions(): array
{
return [
"type_{$this->getType()}_title" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
"type_{$this->getType()}_required_options" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
"type_{$this->getType()}_not_required_options" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 0,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
"type_{$this->getType()}_options_with_fixed_price" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
"type_{$this->getType()}_options_with_percent_price" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 10,
'price_type' => 'percent',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
"type_{$this->getType()}_price" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 22,
'price_type' => 'fixed',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
"type_{$this->getType()}_sku" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'title' => 'Test option title 1',
'type' => $this->getType(),
],
[
'record_id' => 0,
'title' => 'Test option 1 value 1',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'test-option-1-value-1',
'sort_order' => 1,
],
],
];
}
/**
* @inheritdoc
*/
public function getDataForUpdateOptions(): array
{
return array_merge_recursive(
$this->getDataForCreateOptions(),
[
"type_{$this->getType()}_title" => [
[
'title' => 'Updated test option title 1',
],
[],
],
"type_{$this->getType()}_required_options" => [
[
'is_require' => 0,
],
[],
],
"type_{$this->getType()}_not_required_options" => [
[
'is_require' => 1,
],
[],
],
"type_{$this->getType()}_options_with_fixed_price" => [
[],
[
'price_type' => 'percent',
],
],
"type_{$this->getType()}_options_with_percent_price" => [
[],
[
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_price" => [
[],
[
'price' => 666,
],
],
"type_{$this->getType()}_sku" => [
[],
[
'sku' => 'updated-test-option-1-value-1',
],
],
]
);
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractBase;
/**
* Abstract data provider for options from text group.
*/
abstract class AbstractText extends AbstractBase
{
/**
* @inheritdoc
*/
public function getDataForCreateOptions(): array
{
return array_merge_recursive(
parent::getDataForCreateOptions(),
[
"type_{$this->getType()}_options_with_max_charters_configuration" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 30,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
],
],
"type_{$this->getType()}_options_without_max_charters_configuration" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getDataForUpdateOptions(): array
{
return array_merge_recursive(
parent::getDataForUpdateOptions(),
[
"type_{$this->getType()}_options_with_max_charters_configuration" => [
[
'max_characters' => 0,
],
],
"type_{$this->getType()}_options_without_max_charters_configuration" => [
[
'max_characters' => 55,
],
],
]
);
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractText;
/**
* Data provider for custom options from text group with type "area".
*/
class Area extends AbstractText
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_AREA;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractSelect;
/**
* Data provider for custom options from select group with type "Checkbox".
*/
class Checkbox extends AbstractSelect
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractBase;
/**
* Data provider for custom options from date group with type "date".
*/
class Date extends AbstractBase
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_DATE;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractBase;
/**
* Data provider for custom options from date group with type "date & time".
*/
class DateTime extends AbstractBase
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_DATE_TIME;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractSelect;
/**
* Data provider for custom options from select group with type "Drop-down".
*/
class DropDown extends AbstractSelect
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractText;
/**
* Data provider for custom options from text group with type "field".
*/
class Field extends AbstractText
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_FIELD;
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractBase;
/**
* Data provider for options from file group with type "file".
*/
class File extends AbstractBase
{
/**
* @inheritdoc
*/
public function getDataForCreateOptions(): array
{
return array_merge_recursive(
parent::getDataForCreateOptions(),
[
"type_{$this->getType()}_option_file_extension" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 30,
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
'file_extension' => 'gif',
'image_size_x' => 10,
'image_size_y' => 20,
],
],
"type_{$this->getType()}_option_maximum_file_size" => [
[
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'title' => 'Test option title 1',
'type' => $this->getType(),
'price' => 10,
'price_type' => 'fixed',
'file_extension' => 'gif',
'image_size_x' => 10,
'image_size_y' => 20,
],
],
]
);
}
/**
* @inheritdoc
*/
public function getDataForUpdateOptions(): array
{
return array_merge_recursive(
parent::getDataForUpdateOptions(),
[
"type_{$this->getType()}_option_file_extension" => [
[
'file_extension' => 'jpg',
],
],
"type_{$this->getType()}_option_maximum_file_size" => [
[
'image_size_x' => 300,
'image_size_y' => 815,
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_FILE;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractSelect;
/**
* Data provider for custom options from select group with type "Drop-down".
*/
class MultipleSelect extends AbstractSelect
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractSelect;
/**
* Data provider for custom options from select group with type "Radio Buttons".
*/
class RadioButtons extends AbstractSelect
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_RADIO;
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\AbstractBase;
/**
* Data provider for custom options from date group with type "time".
*/
class Time extends AbstractBase
{
/**
* @inheritdoc
*/
protected function getType(): string
{
return ProductCustomOptionInterface::OPTION_TYPE_TIME;
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Option\Type\File;
use Magento\Catalog\Model\Product\Option\Type\File\ValidatorFile;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
/**
* Creates mock for ValidatorFile to replace real instance in fixtures.
*/
class ValidatorFileMock extends TestCase
{
/**
* Returns mock.
*
* @param array|null $fileData
* @return ValidatorFile|MockObject
*/
public function getInstance($fileData = null)
{
if (empty($fileData)) {
$fileData = [
'type' => 'image/jpeg',
'title' => "test.jpg",
'quote_path' => "custom_options/quote/s/t/4624d2.jpg",
'order_path' => "custom_options/order/s/t/89d25b4624d2.jpg",
"fullpath" => "pub/media/custom_options/quote/s/t/e47389d25b4624d2.jpg",
"size" => "71901",
"width" => 5,
"height" => 5,
"secret_key" => "10839ec1631b77e5e473",
];
}
$instance = $this->getMockBuilder(ValidatorFile::class)
->disableOriginalConstructor()
->getMock();
$instance->method('SetProduct')->willReturnSelf();
$instance->method('validate')->willReturn($fileData);
return $instance;
}
}
@@ -0,0 +1,77 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model\Product\Price;
use Magento\Catalog\Model\Indexer\Product\Price\PriceTableResolver;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Customer\Model\Indexer\CustomerGroupDimensionProvider;
use Magento\Framework\Indexer\DimensionFactory;
use Magento\Store\Model\Indexer\WebsiteDimensionProvider;
/**
* Search and return price data from price index table.
*/
class GetPriceIndexDataByProductId
{
/**
* @var ProductResource
*/
private $productResource;
/**
* @var PriceTableResolver
*/
private $priceTableResolver;
/**
* @var DimensionFactory
*/
private $dimensionFactory;
/**
* @param ProductResource $productResource
* @param PriceTableResolver $priceTableResolver
* @param DimensionFactory $dimensionFactory
*/
public function __construct(
ProductResource $productResource,
PriceTableResolver $priceTableResolver,
DimensionFactory $dimensionFactory
) {
$this->productResource = $productResource;
$this->priceTableResolver = $priceTableResolver;
$this->dimensionFactory = $dimensionFactory;
}
/**
* Returns price data by product id.
*
* @param int $productId
* @param int $groupId
* @param int $websiteId
* @return array
*/
public function execute(int $productId, int $groupId, int $websiteId): array
{
$tableName = $this->priceTableResolver->resolve(
'catalog_product_index_price',
[
$this->dimensionFactory->create(WebsiteDimensionProvider::DIMENSION_NAME, (string)$websiteId),
$this->dimensionFactory->create(CustomerGroupDimensionProvider::DIMENSION_NAME, (string)$groupId),
]
);
$select = $this->productResource->getConnection()->select()
->from($tableName)
->where('entity_id = ?', $productId)
->where('customer_group_id = ?', $groupId)
->where('website_id = ?', $websiteId);
return $this->productResource->getConnection()->fetchAll($select);
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Catalog\Model;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product\Attribute\LayoutUpdateManager;
/**
* Easy way to fake available files.
*/
class ProductLayoutUpdateManager extends LayoutUpdateManager
{
/**
* @var array Keys are product IDs, values - file names.
*/
private $fakeFiles = [];
/**
* Supply fake files for a product.
*
* @param int $forProductId
* @param string[]|null $files Pass null to reset.
*/
public function setFakeFiles(int $forProductId, ?array $files): void
{
if ($files === null) {
unset($this->fakeFiles[$forProductId]);
} else {
$this->fakeFiles[$forProductId] = $files;
}
}
/**
* @inheritDoc
*/
public function fetchAvailableFiles(ProductInterface $product): array
{
if (array_key_exists($product->getId(), $this->fakeFiles)) {
return $this->fakeFiles[$product->getId()];
}
return parent::fetchAvailableFiles($product);
}
}
@@ -0,0 +1,52 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Cms\Model;
use Magento\Cms\Api\Data\PageInterface;
/**
* Manager allowing to fake available files.
*/
class CustomLayoutManager extends \Magento\Cms\Model\Page\CustomLayout\CustomLayoutManager
{
/**
* @var string[][]
*/
private $files = [];
/**
* Fake available files for given page.
*
* Pass null to unassign fake files.
*
* @param int $forPageId
* @param string[]|null $files
* @return void
*/
public function fakeAvailableFiles(int $forPageId, ?array $files): void
{
if ($files === null) {
unset($this->files[$forPageId]);
} else {
$this->files[$forPageId] = $files;
}
}
/**
* @inheritDoc
*/
public function fetchAvailableFiles(PageInterface $page): array
{
if (array_key_exists($page->getId(), $this->files)) {
return $this->files[$page->getId()];
}
return parent::fetchAvailableFiles($page);
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
class Config
{
/**
* @var MutableScopeConfigInterface
*/
private $mutableScopeConfig;
/**
* @var array
*/
private $configData;
/**
* @param MutableScopeConfigInterface $mutableScopeConfig
* @param string $configPath
*/
public function __construct(MutableScopeConfigInterface $mutableScopeConfig, $configPath)
{
$this->mutableScopeConfig = $mutableScopeConfig;
$this->configData = $this->readFile($configPath);
}
/**
* Rewrite config from integration config to global config
*/
public function rewriteAdditionalConfig()
{
foreach ($this->configData as $path => $value) {
$this->mutableScopeConfig->setValue($path, $value, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
}
/**
* @param string $configPath
* @return array
*/
private function readFile($configPath)
{
/** @var array $config */
$config = require $configPath;
return $config;
}
}
@@ -0,0 +1,141 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Config\Model;
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
/**
* Class checks config table data using direct calls
*/
class ConfigStorage
{
/** @var ConfigInterface */
private $configResource;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @param ConfigInterface $configResource
* @param StoreManagerInterface $storeManager
*/
public function __construct(ConfigInterface $configResource, StoreManagerInterface $storeManager)
{
$this->configResource = $configResource;
$this->storeManager = $storeManager;
}
/**
* Get value from db
*
* @param string $path
* @param string $scope
* @param string|null $scopeCode
* @return string|false
*/
public function getValueFromDb(
string $path,
string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
?string $scopeCode = null
) {
$connect = $this->configResource->getConnection();
$scope = $this->normalizeScope($scope);
$scopeId = $this->getIdByScope($scope, $scopeCode);
$select = $connect->select()->from(['main_table' => $this->configResource->getMainTable()], 'value')
->where('main_table.path = ?', $path)
->where('main_table.scope = ?', $scope)
->where('main_table.scope_id = ?', $scopeId);
return $connect->fetchOne($select);
}
/**
* Check is record exist in DB
*
* @param string $path
* @param string $scope
* @param string|null $scopeCode
* @return bool
*/
public function checkIsRecordExist(
string $path,
string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
?string $scopeCode = null
): bool {
$connect = $this->configResource->getConnection();
$scope = $this->normalizeScope($scope);
$scopeId = $this->getIdByScope($scope, $scopeCode);
$select = $connect->select()->from(['main_table' => $this->configResource->getMainTable()], 'COUNT(*)')
->where('main_table.path = ?', $path)
->where('main_table.scope = ?', $scope)
->where('main_table.scope_id = ?', $scopeId);
return (bool)$connect->fetchOne($select);
}
/**
* Get scope id by scope code
*
* @param string $scope
* @param string|null $scopeCode
* @return int
*/
private function getIdByScope(string $scope, ?string $scopeCode): int
{
$scopeId = 0;
if ($scope === ScopeInterface::SCOPE_WEBSITES) {
$scopeId = (int)$this->storeManager->getWebsite($scopeCode)->getId();
} elseif ($scope === ScopeInterface::SCOPE_STORES) {
$scopeId = (int)$this->storeManager->getStore($scopeCode)->getId();
}
return $scopeId;
}
/**
* Normalize scope
*
* @param string $scope
* @return string
*/
private function normalizeScope(string $scope): string
{
if ($scope === ScopeInterface::SCOPE_WEBSITE) {
$scope = ScopeInterface::SCOPE_WEBSITES;
}
if ($scope === ScopeInterface::SCOPE_STORE) {
$scope = ScopeInterface::SCOPE_STORES;
}
return $scope;
}
/**
* Delete configuration from db
*
* @param string $path
* @param string $scope
* @param string|null $scopeCode
* @return void
*/
public function deleteConfigFromDb(
string $path,
string $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
?string $scopeCode = null
) {
$scope = $this->normalizeScope($scope);
$scopeId = $this->getIdByScope($scope, $scopeCode);
$this->configResource->deleteConfig($path, $scope, $scopeId);
}
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\ConfigurableProduct\Block\CustomOptions;
use Magento\TestFramework\Catalog\Block\Product\View\Options\DateGroupDataProvider as OptionsDateGroupDataProvider;
/**
* @inheritdoc
*/
class DateGroupDataProvider extends OptionsDateGroupDataProvider
{
/**
* @inheritdoc
*/
public function getData(): array
{
$optionsData = parent::getData();
unset(
$optionsData['type_date_percent_price'],
$optionsData['type_date_and_time_percent_price'],
$optionsData['type_time_percent_price']
);
return $optionsData;
}
}
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\ConfigurableProduct\Block\CustomOptions;
use Magento\TestFramework\Catalog\Block\Product\View\Options\FileGroupDataProvider as OptionsFileGroupDataProvider;
/**
* @inheritdoc
*/
class FileGroupDataProvider extends OptionsFileGroupDataProvider
{
/**
* @inheritdoc
*/
public function getData(): array
{
$optionsData = parent::getData();
unset($optionsData['type_file_percent_price']);
return $optionsData;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\ConfigurableProduct\Block\CustomOptions;
use Magento\TestFramework\Catalog\Block\Product\View\Options\SelectGroupDataProvider as OptionsSelectGroupDataProvider;
/**
* @inheritdoc
*/
class SelectGroupDataProvider extends OptionsSelectGroupDataProvider
{
/**
* @inheritdoc
*/
public function getData(): array
{
$optionsData = parent::getData();
unset(
$optionsData['type_drop_down_value_percent_price'],
$optionsData['type_radio_button_value_percent_price'],
$optionsData['type_checkbox_value_percent_price'],
$optionsData['type_multiselect_value_percent_price']
);
return $optionsData;
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\ConfigurableProduct\Block\CustomOptions;
use Magento\TestFramework\Catalog\Block\Product\View\Options\TextGroupDataProvider as OptionsTextGroupDataProvider;
/**
* @inheritdoc
*/
class TextGroupDataProvider extends OptionsTextGroupDataProvider
{
/**
* @inheritdoc
*/
public function getData(): array
{
$optionsData = parent::getData();
unset(
$optionsData['type_field_percent_price'],
$optionsData['type_area_percent_price']
);
return $optionsData;
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\ConfigurableProduct\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
/**
* Delete configurable product with linked products
*/
class DeleteConfigurableProduct
{
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var ProductResource */
private $productResource;
/** @var Registry */
private $registry;
/**
* @param ProductRepositoryInterface $productRepository
* @param ProductResource $productResource
* @param Registry $registry
*/
public function __construct(
ProductRepositoryInterface $productRepository,
ProductResource $productResource,
Registry $registry
) {
$this->productRepository = $productRepository;
$this->productResource = $productResource;
$this->registry = $registry;
}
/**
* Delete configurable product and linked products
*
* @param string $sku
* @return void
*/
public function execute(string $sku): void
{
$configurableProduct = $this->productRepository->get($sku, false, null, true);
$childrenIds = $configurableProduct->getExtensionAttributes()->getConfigurableProductLinks();
$childrenSkus = array_column($this->productResource->getProductsSku($childrenIds), 'sku');
$childrenSkus[] = $sku;
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
foreach ($childrenSkus as $childSku) {
try {
$this->productRepository->deleteById($childSku);
} catch (NoSuchEntityException $e) {
//product already removed
}
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Console;
use Magento\Framework\Console\Cli;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Provides the ability to inject additional DI configuration to call a CLI command
*/
class CliProxy implements \Magento\Framework\ObjectManager\NoninterceptableInterface
{
/**
* @var Cli
*/
private $subject;
/**
* @param string $name
* @param string $version
* @throws \ReflectionException
* @throws LocalizedException
*/
public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
{
$this->subject = new Cli($name, $version);
$this->injectDiConfiguration($this->subject);
}
/**
* Runs the current application.
*
* @see \Magento\Framework\Console\Cli::doRun
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null
* @throws \Exception
*/
public function doRun(InputInterface $input, OutputInterface $output)
{
return $this->getSubject()->doRun($input, $output);
}
/**
* Runs the current application.
*
* @see \Symfony\Component\Console\Application::run
* @param InputInterface|null $input
* @param OutputInterface|null $output
* @return int
* @throws \Exception
*/
public function run(InputInterface $input = null, OutputInterface $output = null)
{
return $this->getSubject()->run($input, $output);
}
/**
* Get subject
*
* @return Cli
*/
private function getSubject(): Cli
{
return $this->subject;
}
/**
* Inject additional DI configuration
*
* @param Cli $cli
* @return bool
* @throws LocalizedException
* @throws \ReflectionException
*/
private function injectDiConfiguration(Cli $cli): bool
{
$diPreferences = $this->getDiPreferences();
if ($diPreferences) {
$object = new \ReflectionObject($cli);
$attribute = $object->getProperty('objectManager');
$attribute->setAccessible(true);
/** @var ObjectManagerInterface $objectManager */
$objectManager = $attribute->getValue($cli);
$objectManager->configure($diPreferences);
$attribute->setAccessible(false);
}
return true;
}
/**
* Get additional DI preferences
*
* @return array|array[]
* @throws LocalizedException
* @SuppressWarnings(PHPMD.Superglobals)
*/
private function getDiPreferences(): array
{
$diPreferences = [];
$diPreferencesPath = $_SERVER['TESTS_BASE_DIR'] . '/etc/di/preferences/cli/';
$preferenceFiles = glob($diPreferencesPath . '*.php');
foreach ($preferenceFiles as $file) {
if (!is_readable($file)) {
throw new LocalizedException(__("'%1' is not readable file.", $file));
}
$diPreferences = array_replace($diPreferences, include $file);
}
return $diPreferences ? ['preferences' => $diPreferences] : $diPreferences;
}
}
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Replacement for PhpCookieManager model that doesn't send cookie headers in testing environment
*/
namespace Magento\TestFramework;
class CookieManager extends \Magento\Framework\Stdlib\Cookie\PhpCookieManager
{
/**
* Dummy function, which sets value directly to $_COOKIE super-global array instead of calling setcookie()
*
* @param string $name
* @param string $value
* @param array $metadataArray
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
protected function setCookie($name, $value, array $metadataArray)
{
$_COOKIE[$name] = $value;
}
}
@@ -0,0 +1,24 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Core\Version;
/**
* Class for magento version flag.
*/
class View
{
/**
* Returns flag that checks that magento version is clean community version.
*
* @return bool
*/
public function isVersionUpdated(): bool
{
return false;
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Customer\Model;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
/**
* Delete customer by email or id
*/
class DeleteCustomer
{
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var Registry */
private $registry;
/**
* @param CustomerRepositoryInterface $customerRepository
* @param Registry $registry
*/
public function __construct(CustomerRepositoryInterface $customerRepository, Registry $registry)
{
$this->customerRepository = $customerRepository;
$this->registry = $registry;
}
/**
* Delete customer by id or email
*
* @param int|string $id
* @return void
*/
public function execute($id): void
{
$isSecure = $this->registry->registry('isSecureArea');
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
try {
$customer = is_numeric($id) ? $this->customerRepository->getById($id) : $this->customerRepository->get($id);
$this->customerRepository->delete($customer);
} catch (NoSuchEntityException $e) {
//customer already deleted
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', $isSecure);
}
}
@@ -0,0 +1,162 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Abstract database handler for integration tests
*/
namespace Magento\TestFramework\Db;
abstract class AbstractDb
{
/**
* DB host name
*
* @var string
*/
protected $_host = '';
/**
* DB credentials -- user name
*
* @var string
*/
protected $_user = '';
/**
* DB credentials -- password
*
* @var string
*/
protected $_password = '';
/**
* DB name
*
* @var string
*/
protected $_schema = '';
/**
* Path to a temporary directory in the file system
*
* @var string
*/
protected $_varPath = '';
/**
* @var \Magento\Framework\Shell
*/
protected $_shell;
/**
* Set initial essential parameters
*
* @param string $host
* @param string $user
* @param string $password
* @param string $schema
* @param string $varPath
* @param \Magento\Framework\Shell $shell
*/
public function __construct($host, $user, $password, $schema, $varPath, \Magento\Framework\Shell $shell)
{
$this->_host = $host;
$this->_user = $user;
$this->_password = $password;
$this->_schema = $schema;
$this->_varPath = $varPath;
$this->_shell = $shell;
}
/**
* Remove all DB objects
*/
abstract public function cleanup();
/**
* Get filename for setup db dump
*
* @return string
*/
abstract protected function getSetupDbDumpFilename();
/**
* Is dump exists
*
* @return bool
*/
abstract public function isDbDumpExists();
/**
* Store setup db dump
*/
abstract public function storeDbDump();
/**
* Restore db from setup db dump
*/
abstract public function restoreFromDbDump();
/**
* @return string
*/
abstract public function getVendorName();
/**
* @return string
*/
public function getSchema()
{
return $this->_schema;
}
/**
* @return string
*/
public function getHost()
{
return $this->_host;
}
/**
* @return string
*/
public function getUser()
{
return $this->_user;
}
/**
* @return string
*/
public function getPassword()
{
return $this->_password;
}
/**
* Create file with sql script content.
* Utility method that is used in children classes
*
* @param string $file
* @param string $content
* @return int
*/
protected function _createScript($file, $content)
{
return file_put_contents($file, $content);
}
/**
* @throws \LogicException
*/
protected function assertVarPathWritable()
{
if (!is_dir($this->_varPath) || !is_writable($this->_varPath)) {
throw new \LogicException("The specified '{$this->_varPath}' is not a directory or not writable.");
}
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/**
* See \Magento\TestFramework\Db\Adapter\TransactionInterface
*/
namespace Magento\TestFramework\Db\Adapter;
class Mysql extends \Magento\Framework\DB\Adapter\Pdo\Mysql implements \Magento\TestFramework\Db\Adapter\TransactionInterface
{
/**
* @var int
*/
protected $_levelAdjustment = 0;
/**
* See \Magento\TestFramework\Db\Adapter\TransactionInterface
*
* @return \Magento\TestFramework\Db\Adapter\Mysql
*/
public function beginTransparentTransaction()
{
$this->_levelAdjustment += 1;
return $this->beginTransaction();
}
/**
* See \Magento\TestFramework\Db\Adapter\TransactionInterface
*
* @return \Magento\TestFramework\Db\Adapter\Mysql
*/
public function commitTransparentTransaction()
{
$this->_levelAdjustment -= 1;
return $this->commit();
}
/**
* See \Magento\TestFramework\Db\Adapter\TransactionInterface
*
* @return \Magento\TestFramework\Db\Adapter\Mysql
*/
public function rollbackTransparentTransaction()
{
$this->_levelAdjustment -= 1;
return $this->rollback();
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* DB adapter transaction interface that allows starting transaction with adjusted level,
* transparently to the application
*/
namespace Magento\TestFramework\Db\Adapter;
interface TransactionInterface
{
/**
* Increment "transparent" transaction counter and start real transaction
*
* @return \Magento\Framework\DB\Adapter\Pdo\Mysql
*/
public function beginTransparentTransaction();
/**
* Decrement "transparent" transaction counter and commit real transaction
*
* @return \Magento\Framework\DB\Adapter\Pdo\Mysql
*/
public function commitTransparentTransaction();
/**
* Decrement "transparent" transaction counter and rollback real transaction
*
* @return \Magento\Framework\DB\Adapter\Pdo\Mysql
*/
public function rollbackTransparentTransaction();
}
@@ -0,0 +1,22 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Db;
/**
* Test framework custom connection adapter
*/
class ConnectionAdapter extends \Magento\Framework\Model\ResourceModel\Type\Db\Pdo\Mysql
{
/**
* Retrieve DB connection class name
*
* @return string
*/
protected function getDbConnectionClassName()
{
return \Magento\TestFramework\Db\Adapter\Mysql::class;
}
}
@@ -0,0 +1,244 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* MySQL platform database handler
*/
namespace Magento\TestFramework\Db;
use Magento\Framework\Exception\LocalizedException;
class Mysql extends \Magento\TestFramework\Db\AbstractDb
{
/**
* Mysql default Port.
*/
const DEFAULT_PORT = 3306;
/**
* Name of configuration file.
*/
const DEFAULTS_EXTRA_FILE_NAME = 'defaults_extra.cnf';
/**
* MySQL DB dump file
*
* @var string
*/
private $_dbDumpFile;
/**
* A file that contains credentials to database, to obscure them from logs
*
* @var string
*/
private $_defaultsExtraFile;
/**
* Port number for connection
*
* @var integer
*/
private $_port;
/**
* @var bool
*/
private $isMysqldumpVersion8;
/**
* @var bool
*/
private $isUsingAuroraDb;
/**
* {@inheritdoc}
*
* @param string $host
* @param string $user
* @param string $password
* @param string $schema
* @param string $varPath
* @param \Magento\Framework\Shell $shell
*/
public function __construct($host, $user, $password, $schema, $varPath, \Magento\Framework\Shell $shell)
{
parent::__construct($host, $user, $password, $schema, $varPath, $shell);
$this->_port = self::DEFAULT_PORT;
if (strpos($this->_host, ':') !== false) {
list($host, $port) = explode(':', $this->_host);
$this->_host = $host;
$this->_port = (int) $port;
}
$this->_dbDumpFile = $this->_varPath . '/setup_dump_' . $this->_schema . '.sql';
$this->_defaultsExtraFile = rtrim($this->_varPath, '\\/') . '/' . self::DEFAULTS_EXTRA_FILE_NAME;
}
/**
* Remove all DB objects
*/
public function cleanup()
{
$this->ensureDefaultsExtraFile();
$this->_shell->execute(
'mysql --defaults-file=%s --host=%s --port=%s %s -e %s',
[
$this->_defaultsExtraFile,
$this->_host,
$this->_port,
$this->_schema,
"DROP DATABASE `{$this->_schema}`; CREATE DATABASE `{$this->_schema}`"
]
);
}
/**
* Get filename for setup db dump
*
* @return string
*/
protected function getSetupDbDumpFilename()
{
return $this->_dbDumpFile;
}
/**
* Is dump exists
*
* @return bool
*/
public function isDbDumpExists()
{
return file_exists($this->getSetupDbDumpFilename());
}
/**
* Store setup db dump
*/
public function storeDbDump()
{
$this->ensureDefaultsExtraFile();
$additionalArguments = [];
if ($this->isMysqlDumpVersion8()) {
$additionalArguments[] = '--column-statistics=0';
}
if ($this->isUsingAuroraDb()) {
$additionalArguments[] = '--set-gtid-purged=OFF';
}
$format = sprintf(
'%s %s %s %s',
'mysqldump --defaults-file=%s --host=%s --port=%s',
'--no-tablespaces',
implode(' ', $additionalArguments),
'%s > %s'
);
$this->_shell->execute(
$format,
[
$this->_defaultsExtraFile,
$this->_host,
$this->_port,
$this->_schema,
$this->getSetupDbDumpFilename()
]
);
}
/**
* @inheritdoc
*
* @throws LocalizedException
*/
public function restoreFromDbDump()
{
$this->ensureDefaultsExtraFile();
if (!$this->isDbDumpExists()) {
throw new \LogicException("DB dump file does not exist: " . $this->getSetupDbDumpFilename());
}
$this->_shell->execute(
'mysql --defaults-file=%s --host=%s --port=%s %s < %s',
[$this->_defaultsExtraFile, $this->_host, $this->_port, $this->_schema, $this->getSetupDbDumpFilename()]
);
}
/**
* @inheritdoc
*/
public function getVendorName()
{
return 'mysql';
}
/**
* Create defaults extra file
*
* @return void
*/
private function ensureDefaultsExtraFile()
{
if (!file_exists($this->_defaultsExtraFile)) {
$this->assertVarPathWritable();
$extraConfig = [
'[client]',
'user=' . $this->_user,
'password="' . $this->_password . '"'
];
file_put_contents($this->_defaultsExtraFile, implode(PHP_EOL, $extraConfig));
chmod($this->_defaultsExtraFile, 0640);
}
}
/**
* Check if mysql dump is version 8.
*
* @return bool
* @throws LocalizedException
*/
private function isMysqlDumpVersion8(): bool
{
if (!$this->isMysqldumpVersion8) {
$version = $this->_shell->execute(
'mysqldump --version'
);
$this->isMysqldumpVersion8 = (bool) preg_match('/8\.0\./', $version);
}
return $this->isMysqldumpVersion8;
}
/**
* Is the DB connection Aurora RDS?
*
* @return bool
*/
private function isUsingAuroraDb(): bool
{
if (!isset($this->isUsingAuroraDb)) {
try {
$this->_shell->execute(
'mysql --defaults-file=%s --host=%s --port=%s %s --execute="SELECT AURORA_VERSION()"',
[
$this->_defaultsExtraFile,
$this->_host,
$this->_port,
$this->_schema
]
);
$this->isUsingAuroraDb = true;
} catch (LocalizedException $e) {
$this->isUsingAuroraDb = false;
}
}
return $this->isUsingAuroraDb;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Db;
use Magento\Framework\App\ResourceConnection as AppResource;
use Magento\Framework\DB\Ddl\Sequence as DdlSequence;
use Magento\SalesSequence\Model\EntityPool;
class Sequence
{
/**
* @var AppResource
*/
protected $appResource;
/**
* @var DdlSequence
*/
protected $ddlSequence;
/**
* @var EntityPool
*/
private $entityPool;
/**
* @param AppResource $appResource
* @param DdlSequence $ddlSequence
* @param EntityPool $entityPool
*/
public function __construct(
AppResource $appResource,
DdlSequence $ddlSequence,
EntityPool $entityPool
) {
$this->appResource = $appResource;
$this->ddlSequence = $ddlSequence;
$this->entityPool = $entityPool;
}
/**
* Generates sequence for store IDS 0..(n-1)
*
* @param int $n
* @return void
*/
public function generateSequences($n = 10)
{
for ($i = 0; $i < $n; $i++) {
$this->generate($i);
}
}
/**
* Generates sequence for store ID
*
* @param int $storeId
* @return void
*/
public function generate(int $storeId): void
{
$connection = $this->appResource->getConnection();
foreach ($this->entityPool->getEntities() as $entityName) {
$sequenceName = $this->appResource->getTableName(sprintf('sequence_%s_%s', $entityName, $storeId));
if (!$connection->isTableExists($sequenceName)) {
$connection->query($this->ddlSequence->getCreateSequenceDdl($sequenceName));
}
}
}
}
@@ -0,0 +1,266 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Db\Sequence;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Webapi\Exception;
use Magento\SalesSequence\Model\ResourceModel\Meta as ResourceMetadata;
use Magento\Framework\App\ResourceConnection as AppResource;
use Magento\Framework\DB\Ddl\Sequence as DdlSequence;
use Magento\SalesSequence\Model\ProfileFactory;
use Magento\SalesSequence\Model\MetaFactory;
/**
* Class Builder
*/
class Builder extends \Magento\SalesSequence\Model\Builder
{
/**
* @var resourceMetadata
*/
protected $resourceMetadata;
/**
* @var ProfileFactory
*/
protected $profileFactory;
/**
* @var MetaFactory
*/
protected $metaFactory;
/**
* @var AppResource
*/
protected $appResource;
/**
* @var DdlSequence
*/
protected $ddlSequence;
/**
* List of required sequence attribute
*
* @var array
*/
protected $required = [
'entityType',
'storeId'
];
/**
* Default pattern for sequence creation, full list of attributes that can be defined by customer
*
* @var array
*/
protected $pattern = [
'entity_type',
'store_id',
'prefix',
'suffix',
'start_value',
'step',
'max_value',
'warning_value',
];
/**
* Concrete data of sequence
*
* @var array
*/
protected $data = [];
/**
* @param ResourceMetadata $resourceMetadata
* @param MetaFactory $metaFactory
* @param ProfileFactory $profileFactory
* @param AppResource $appResource
* @param DdlSequence $ddlSequence
*/
public function __construct(
ResourceMetadata $resourceMetadata,
MetaFactory $metaFactory,
ProfileFactory $profileFactory,
AppResource $appResource,
DdlSequence $ddlSequence
) {
$this->resourceMetadata = $resourceMetadata;
$this->metaFactory = $metaFactory;
$this->profileFactory = $profileFactory;
$this->appResource = $appResource;
$this->ddlSequence = $ddlSequence;
$this->data = array_flip($this->pattern);
}
/**
* @param string $entityType
* @return $this
*/
public function setEntityType($entityType)
{
$this->data['entity_type'] = $entityType;
return $this;
}
/**
* @param int $storeId
* @return $this
*/
public function setStoreId($storeId)
{
$this->data['store_id'] = $storeId;
return $this;
}
/**
* @param string $prefix
* @return $this
*/
public function setPrefix($prefix)
{
$this->data['prefix'] = $prefix;
return $this;
}
/**
* @param string $suffix
* @return $this
*/
public function setSuffix($suffix)
{
$this->data['suffix'] = $suffix;
return $this;
}
/**
* @param int $startValue
* @return $this
*/
public function setStartValue($startValue)
{
$this->data['start_value'] = $startValue;
return $this;
}
/**
* @param int $step
* @return $this
*/
public function setStep($step)
{
$this->data['step'] = $step;
return $this;
}
/**
* @param int $maxValue
* @return $this
*/
public function setMaxValue($maxValue)
{
$this->data['max_value'] = $maxValue;
return $this;
}
/**
* @param int $warningValue
* @return $this
*/
public function setWarningValue($warningValue)
{
$this->data['warning_value'] = $warningValue;
return $this;
}
/**
* Validate sequence before save
*
* @throws \Magento\Framework\Exception\AlreadyExistsException
* @return void
*/
protected function validate()
{
$metadata = $this->resourceMetadata->loadByEntityTypeAndStore(
$this->data['entity_type'],
$this->data['store_id']
);
$connection = $this->appResource->getConnection();
if ($metadata->getId() && !$connection->isTableExists($this->getSequenceName())) {
throw new \Magento\Framework\Exception\AlreadyExistsException(
__('Sequence with this metadata already exists')
);
}
}
/**
* @return string
*/
protected function getSequenceName()
{
return $this->appResource->getTableName(
sprintf(
'sequence_%s_%s',
$this->data['entity_type'],
$this->data['store_id']
)
);
}
/**
* Create sequence with metadata and profile
*
* @throws \Exception
* @throws \Magento\Framework\Exception\AlreadyExistsException
* @return void
*/
public function create()
{
$metadata = $this->resourceMetadata->loadByEntityTypeAndStore(
$this->data['entity_type'],
$this->data['store_id']
);
if ($metadata->getSequenceTable() == $this->getSequenceName()) {
return;
}
$this->data['sequence_table'] = $this->getSequenceName();
$this->data['is_active'] = 1;
$profile = $this->profileFactory->create(
[
'data' => array_intersect_key(
$this->data,
array_flip(
[
'prefix', 'suffix', 'start_value', 'step', 'max_value', 'warning_value',
'is_active', 'active_profile'
]
)
)
]
);
$profile->setHasDataChanges(true);
$this->data['active_profile'] = $profile;
$metadata = $this->metaFactory->create(
[
'data' => array_intersect_key(
$this->data,
array_flip(['entity_type', 'store_id', 'sequence_table', 'active_profile'])
)
]
);
$metadata->setHasDataChanges(true);
try {
$this->resourceMetadata->save($metadata);
} catch (Exception $e) {
$this->resourceMetadata->delete($metadata);
throw $e;
}
$this->data = array_flip($this->pattern);
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Directory\Model;
use Magento\Directory\Model\RegionFactory;
/**
* Return region ID by region default name and country code.
*/
class GetRegionIdByName
{
/**
* @var RegionFactory
*/
private $regionFactory;
/**
* @var array
*/
private $regionIdsCache;
/**
* @param RegionFactory $regionFactory
*/
public function __construct(
RegionFactory $regionFactory
) {
$this->regionFactory = $regionFactory;
}
/**
* Get region ID from cache property if region id exist or load it.
*
* @param string $regionName
* @param string $countryId
* @return int|null
*/
public function execute(string $regionName, string $countryId): ?int
{
$cacheKey = "{$regionName}_{$countryId}";
if (!isset($this->regionIdsCache[$cacheKey])) {
$region = $this->regionFactory->create()->loadByName($regionName, $countryId);
$this->regionIdsCache[$cacheKey] = $region->getRegionId() ? (int)$region->getRegionId() : null;
}
return $this->regionIdsCache[$cacheKey];
}
}
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Directory\Model;
use Magento\Directory\Model\ResourceModel\Currency;
/**
* Remove currency rates by currency code
*/
class RemoveCurrencyRateByCode
{
/** @var Currency */
private $currencyResource;
/**
* @param Currency $currencyResource
*/
public function __construct(Currency $currencyResource)
{
$this->currencyResource = $currencyResource;
}
/**
* Remove currency rates
*
* @param string $currencyCode
* @return void
*/
public function execute(string $currencyCode): void
{
$connection = $this->currencyResource->getConnection();
$rateTable = $this->currencyResource->getTable('directory_currency_rate');
$connection->delete($rateTable, $connection->quoteInto('currency_to = ? OR currency_from = ?', $currencyCode));
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Downloadable\Model;
use Magento\Downloadable\Model\ResourceModel\Link\Purchased as PurchasedResource;
use Magento\Downloadable\Model\ResourceModel\Link\Purchased\CollectionFactory;
/**
* Delete records from downloadable_link_purchased associated with provided order
*/
class RemoveLinkPurchasedByOrderIncrementId
{
/** @var CollectionFactory */
private $linkCollectionFactory;
/** @var PurchasedResource */
private $purchasedResource;
/**
* @param CollectionFactory $linkCollectionFactory
* @param PurchasedResource $purchasedResource
*/
public function __construct(CollectionFactory $linkCollectionFactory, PurchasedResource $purchasedResource)
{
$this->linkCollectionFactory = $linkCollectionFactory;
$this->purchasedResource = $purchasedResource;
}
/**
* Remove records from downloadable_link_purchased related to provided order
*
* @param string $orderIncrementId
* @return void
*/
public function execute(string $orderIncrementId): void
{
$collection = $this->linkCollectionFactory->create();
$collection->addFieldToFilter('order_increment_id', $orderIncrementId);
foreach ($collection as $item) {
$this->purchasedResource->delete($item);
}
}
}
@@ -0,0 +1,180 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Store\Model\Store;
/**
* Base POST data for create attribute with options.
*/
abstract class AbstractAttributeDataWithOptions extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['serialized_options_arr'] = $this->getOptionsDataArr();
$this->defaultAttributePostData['is_filterable'] = '0';
$this->defaultAttributePostData['is_filterable_in_search'] = '0';
}
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
$result = parent::getAttributeData();
unset($result["{$this->getFrontendInput()}_with_default_value"]);
unset($result["{$this->getFrontendInput()}_without_default_value"]);
return $result;
}
/**
* @inheritdoc
*/
public function getAttributeDataWithErrorMessage(): array
{
$wrongSerializeMessage = 'The attribute couldn\'t be saved due to an error. Verify your information and ';
$wrongSerializeMessage .= 'try again. If the error persists, please try again later.';
return array_replace_recursive(
parent::getAttributeDataWithErrorMessage(),
[
"{$this->getFrontendInput()}_with_wrong_serialized_options" => [
array_merge(
$this->defaultAttributePostData,
[
'serialized_options_arr' => [],
'serialized_options' => '?.\\//',
]
),
(string)__($wrongSerializeMessage)
],
]
);
}
/**
* @inheritdoc
*/
public function getAttributeDataWithCheckArray(): array
{
$result = parent::getAttributeDataWithCheckArray();
unset($result["{$this->getFrontendInput()}_with_default_value"]);
unset($result["{$this->getFrontendInput()}_without_default_value"]);
return $result;
}
/**
* Return product attribute data set for update attribute options.
*
* @return array
*/
public function getUpdateOptionsProvider(): array
{
$frontendInput = $this->getFrontendInput();
return [
"{$frontendInput}_update_options" => [
'post_data' => [
'options_array' => [
'option_1' => [
'order' => '5',
'value' => [
Store::DEFAULT_STORE_ID => 'Option 1 Admin',
'default' => 'Option 1 Store 1',
'fixture_second_store' => 'Option 1 Store 2',
'fixture_third_store' => 'Option 1 Store 3',
],
'delete' => '',
],
'option_2' => [
'order' => '6',
'value' => [
Store::DEFAULT_STORE_ID => 'Option 2 Admin',
'default' => 'Option 2 Store 1',
'fixture_second_store' => 'Option 2 Store 2',
'fixture_third_store' => 'Option 2 Store 3',
],
'delete' => '',
'default' => 1,
],
],
],
],
"{$frontendInput}_delete_options" => [
'post_data' => [
'options_array' => [
'option_1' => [
'value' => [],
'delete' => '',
],
'option_2' => [
'value' => [],
'delete' => '1',
],
'option_3' => [
'value' => [],
'delete' => '',
],
'option_4' => [
'value' => [],
'delete' => '1',
],
],
],
],
];
}
/**
* Return attribute options data.
*
* @return array
*/
protected function getOptionsDataArr(): array
{
return [
[
'option' => [
'order' => [
'option_0' => '1',
],
'value' => [
'option_0' => [
'Admin value 1',
'Default store view value 1',
],
],
'delete' => [
'option_0' => '',
],
],
],
[
'option' => [
'order' => [
'option_1' => '2',
],
'value' => [
'option_1' => [
'Admin value 2',
'Default store view value 2',
],
],
'delete' => [
'option_1' => '',
],
],
],
];
}
}
@@ -0,0 +1,388 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Store\Model\Store;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
/**
* Base POST data for create attribute.
*/
abstract class AbstractBaseAttributeData
{
/**
* Default POST data for create attribute.
*
* @var array
*/
protected $defaultAttributePostData = [
'active_tab' => 'main',
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Test attribute name',
],
'is_required' => '0',
'dropdown_attribute_validation' => '',
'dropdown_attribute_validation_unique' => '',
'attribute_code' => '',
'is_global' => ScopedAttributeInterface::SCOPE_STORE,
'default_value_text' => '',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '',
'is_unique' => '0',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '0',
'is_comparable' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
];
/**
* @inheritdoc
*/
public function __construct()
{
$this->defaultAttributePostData['frontend_input'] = $this->getFrontendInput();
}
/**
* Return create product attribute data set.
*
* @return array
*/
public function getAttributeData(): array
{
return [
"{$this->getFrontendInput()}_with_required_fields" => [
$this->defaultAttributePostData,
],
"{$this->getFrontendInput()}_with_store_view_scope" => [
$this->defaultAttributePostData,
],
"{$this->getFrontendInput()}_with_global_scope" => [
array_merge($this->defaultAttributePostData, ['is_global' => ScopedAttributeInterface::SCOPE_GLOBAL]),
],
"{$this->getFrontendInput()}_with_website_scope" => [
array_merge($this->defaultAttributePostData, ['is_global' => ScopedAttributeInterface::SCOPE_WEBSITE]),
],
"{$this->getFrontendInput()}_with_attribute_code" => [
array_merge($this->defaultAttributePostData, ['attribute_code' => 'test_custom_attribute_code']),
],
"{$this->getFrontendInput()}_with_default_value" => [
array_merge($this->defaultAttributePostData, ['default_value_text' => 'Default attribute value']),
],
"{$this->getFrontendInput()}_without_default_value" => [
$this->defaultAttributePostData,
],
"{$this->getFrontendInput()}_with_unique_value" => [
array_merge($this->defaultAttributePostData, ['is_unique' => '1']),
],
"{$this->getFrontendInput()}_without_unique_value" => [
$this->defaultAttributePostData,
],
"{$this->getFrontendInput()}_with_enabled_add_to_column_options" => [
array_merge($this->defaultAttributePostData, ['is_used_in_grid' => '1']),
],
"{$this->getFrontendInput()}_without_enabled_add_to_column_options" => [
array_merge($this->defaultAttributePostData, ['is_used_in_grid' => '0']),
],
"{$this->getFrontendInput()}_with_enabled_use_in_filter_options" => [
$this->defaultAttributePostData,
],
"{$this->getFrontendInput()}_without_enabled_use_in_filter_options" => [
array_merge($this->defaultAttributePostData, ['is_filterable_in_grid' => '0']),
],
];
}
/**
* Return create product attribute data set with error message.
*
* @return array
*/
public function getAttributeDataWithErrorMessage(): array
{
$wrongAttributeCode = 'Attribute code "????" is invalid. Please use only letters (a-z or A-Z), numbers ';
$wrongAttributeCode .= '(0-9) or underscore (_) in this field, and the first character should be a letter.';
return [
"{$this->getFrontendInput()}_with_wrong_frontend_input" => [
array_merge($this->defaultAttributePostData, ['frontend_input' => 'wrong_input_type']),
(string)__('Input type "wrong_input_type" not found in the input types list.')
],
"{$this->getFrontendInput()}_with_wrong_attribute_code" => [
array_merge($this->defaultAttributePostData, ['attribute_code' => '????']),
(string)__($wrongAttributeCode)
],
];
}
/**
* Return create product attribute data set with array for check data.
*
* @return array
*/
public function getAttributeDataWithCheckArray(): array
{
return array_merge_recursive(
$this->getAttributeData(),
[
"{$this->getFrontendInput()}_with_required_fields" => [
[
'attribute_code' => 'test_attribute_name',
],
],
"{$this->getFrontendInput()}_with_store_view_scope" => [
[
'attribute_code' => 'test_attribute_name',
'is_global' => ScopedAttributeInterface::SCOPE_STORE,
],
],
"{$this->getFrontendInput()}_with_global_scope" => [
[
'attribute_code' => 'test_attribute_name',
'is_global' => ScopedAttributeInterface::SCOPE_GLOBAL,
],
],
"{$this->getFrontendInput()}_with_website_scope" => [
[
'attribute_code' => 'test_attribute_name',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
],
],
"{$this->getFrontendInput()}_with_attribute_code" => [
[
'attribute_code' => 'test_custom_attribute_code',
],
],
"{$this->getFrontendInput()}_with_default_value" => [
[
'attribute_code' => 'test_attribute_name',
'default_value' => 'Default attribute value',
],
],
"{$this->getFrontendInput()}_without_default_value" => [
[
'attribute_code' => 'test_attribute_name',
'default_value_text' => '',
],
],
"{$this->getFrontendInput()}_with_unique_value" => [
[
'attribute_code' => 'test_attribute_name',
'is_unique' => '1',
],
],
"{$this->getFrontendInput()}_without_unique_value" => [
[
'attribute_code' => 'test_attribute_name',
'is_unique' => '0',
],
],
"{$this->getFrontendInput()}_with_enabled_add_to_column_options" => [
[
'attribute_code' => 'test_attribute_name',
'is_used_in_grid' => '1',
],
],
"{$this->getFrontendInput()}_without_enabled_add_to_column_options" => [
[
'attribute_code' => 'test_attribute_name',
'is_used_in_grid' => false,
],
],
"{$this->getFrontendInput()}_with_enabled_use_in_filter_options" => [
[
'attribute_code' => 'test_attribute_name',
'is_filterable_in_grid' => '1',
],
],
"{$this->getFrontendInput()}_without_enabled_use_in_filter_options" => [
[
'attribute_code' => 'test_attribute_name',
'is_filterable_in_grid' => false,
],
],
]
);
}
/**
* Return product attribute data set for update attribute.
*
* @return array
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return [
"{$frontendInput}_update_all_fields" => [
'post_data' => $this->getUpdatePostData(),
'expected_data' => $this->getUpdateExpectedData(),
],
"{$frontendInput}_other_is_user_defined" => [
'post_data' => [
'is_user_defined' => '2',
],
'expected_data' => [
'is_user_defined' => '1',
],
],
"{$frontendInput}_with_is_global_null" => [
'post_data' => [
'is_global' => null,
],
'expected_data' => [
'is_global' => ScopedAttributeInterface::SCOPE_GLOBAL,
],
],
"{$frontendInput}_is_visible_in_advanced_search" => [
'post_data' => [
'is_searchable' => '0',
'is_visible_in_advanced_search' => '1',
],
'expected_data' => [
'is_searchable' => '0',
'is_visible_in_advanced_search' => '0',
],
],
"{$frontendInput}_update_with_attribute_set" => [
'post_data' => [
'set' => '4',
'new_attribute_set_name' => 'Text Attribute Set',
'group' => 'text_attribute_group',
'groupName' => 'Text Attribute Group',
'groupSortOrder' => '1',
],
'expected_data' => [],
],
];
}
/**
* Return product attribute data set with error message for update attribute.
*
* @return array
*/
public function getUpdateProviderWithErrorMessage(): array
{
$frontendInput = $this->getFrontendInput();
return [
"{$frontendInput}_same_attribute_set_name" => [
'post_data' => [
'set' => '4',
'new_attribute_set_name' => 'Default',
],
'error_message' => (string)__('An attribute set named \'Default\' already exists.'),
],
"{$frontendInput}_empty_set_id" => [
'post_data' => [
'set' => '',
'new_attribute_set_name' => 'Text Attribute Set',
],
'error_message' => (string)__('Something went wrong while saving the attribute.'),
],
"{$frontendInput}_nonexistent_attribute_id" => [
'post_data' => [
'attribute_id' => 9999,
],
'error_message' => (string)__('This attribute no longer exists.'),
],
"{$frontendInput}_attribute_other_entity_type" => [
'post_data' => [
'attribute_id' => 45,
],
'error_message' => (string)__('We can\'t update the attribute.'),
],
];
}
/**
* Return product attribute data set for update attribute frontend labels.
*
* @return array
*/
public function getUpdateFrontendLabelsProvider(): array
{
$frontendInput = $this->getFrontendInput();
return [
"{$frontendInput}_update_frontend_label" => [
'post_data' => [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Test Attribute Update',
'default' => 'Default Store Update',
'fixture_second_store' => 'Second Store Update',
'fixture_third_store' => 'Third Store Update',
]
],
'expected_data' => [
'frontend_label' => 'Test Attribute Update',
'store_labels' => [
'default' => 'Default Store Update',
'fixture_second_store' => 'Second Store Update',
'fixture_third_store' => 'Third Store Update',
],
],
],
"{$frontendInput}_remove_frontend_label" => [
'post_data' => [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Test Attribute Update',
'default' => 'Default Store Update',
'fixture_second_store' => '',
'fixture_third_store' => '',
]
],
'expected_data' => [
'frontend_label' => 'Test Attribute Update',
'store_labels' => [
'default' => 'Default Store Update',
],
],
],
"{$frontendInput}_with_frontend_label_string" => [
'post_data' => [
'frontend_label' => 'Test Attribute Update',
],
'expected_data' => [
'frontend_label' => 'Test Attribute Update',
'store_labels' => [
'default' => 'Default Store View',
'fixture_second_store' => 'Fixture Second Store',
'fixture_third_store' => 'Fixture Third Store',
],
],
],
];
}
/**
* Return attribute frontend input.
*
* @return string
*/
abstract protected function getFrontendInput(): string;
/**
* Return post data for attribute update.
*
* @return array
*/
abstract protected function getUpdatePostData(): array;
/**
* Return expected data for attribute update.
*
* @return array
*/
abstract protected function getUpdateExpectedData(): array;
}
@@ -0,0 +1,161 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
/**
* Product attribute data for attribute with input type date.
*/
class Date extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['used_for_sort_by'] = '0';
}
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
return array_replace_recursive(
parent::getAttributeData(),
[
"{$this->getFrontendInput()}_with_default_value" => [
[
'default_value_text' => '',
'default_value_date' => '10/29/2019',
]
]
]
);
}
/**
* @inheritdoc
*/
public function getAttributeDataWithCheckArray(): array
{
return array_replace_recursive(
parent::getAttributeDataWithCheckArray(),
[
"{$this->getFrontendInput()}_with_default_value" => [
1 => [
'default_value' => '2019-10-29 00:00:00',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'date_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getUpdateProviderWithErrorMessage(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProviderWithErrorMessage(),
[
"{$frontendInput}_wrong_default_value" => [
'post_data' => [
'default_value_date' => '//2019/12/12',
],
'error_message' => (string)__('The default date is invalid. Verify the date and try again.'),
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'date';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Date Attribute Update',
],
'frontend_input' => 'date',
'is_required' => '1',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'default_value_date' => '12/29/2019',
'is_unique' => '1',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '1',
'used_in_product_listing' => '0',
'used_for_sort_by' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
unset($updatePostData['default_value_date']);
return array_merge(
$updatePostData,
[
'frontend_label' => 'Date Attribute Update',
'attribute_code' => 'date_attribute',
'default_value' => '2019-12-29 00:00:00',
'frontend_class' => null,
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'position' => '0',
'is_user_defined' => '1',
'backend_type' => 'datetime',
]
);
}
}
@@ -0,0 +1,161 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
/**
* Product attribute data for attribute with input type datetime.
*/
class DateTime extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['used_for_sort_by'] = '0';
}
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
return array_replace_recursive(
parent::getAttributeData(),
[
"{$this->getFrontendInput()}_with_default_value" => [
[
'default_value_text' => '',
'default_value_datetime' => '02/4/2020 6:30 AM',
]
]
]
);
}
/**
* @inheritdoc
*/
public function getAttributeDataWithCheckArray(): array
{
return array_replace_recursive(
parent::getAttributeDataWithCheckArray(),
[
"{$this->getFrontendInput()}_with_default_value" => [
1 => [
'default_value' => '2020-02-04 06:30:00',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'datetime_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getUpdateProviderWithErrorMessage(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProviderWithErrorMessage(),
[
"{$frontendInput}_wrong_default_value" => [
'post_data' => [
'default_value_datetime' => '//02/4/2020 6:30 AM',
],
'error_message' => (string)__('The default date is invalid. Verify the date and try again.'),
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'datetime';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Date Time Attribute Update',
],
'frontend_input' => 'datetime',
'is_required' => '1',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'default_value_datetime' => '02/4/2020 6:30 AM',
'is_unique' => '1',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '1',
'used_in_product_listing' => '0',
'used_for_sort_by' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
unset($updatePostData['default_value_datetime']);
return array_merge(
$updatePostData,
[
'frontend_label' => 'Date Time Attribute Update',
'attribute_code' => 'datetime_attribute',
'default_value' => '2020-02-04 06:30:00',
'frontend_class' => null,
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'position' => '0',
'is_user_defined' => '1',
'backend_type' => 'datetime',
]
);
}
}
@@ -0,0 +1,106 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
/**
* Product attribute data for attribute with input type dropdown.
*/
class DropDown extends AbstractAttributeDataWithOptions
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['used_for_sort_by'] = '0';
$this->defaultAttributePostData['swatch_input_type'] = 'dropdown';
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'dropdown_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'select';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Drop-Down Attribute Update',
],
'frontend_input' => 'select',
'is_required' => '1',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'is_unique' => '1',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_filterable' => '2',
'is_filterable_in_search' => '1',
'position' => '2',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '0',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
return array_merge(
$updatePostData,
[
'frontend_label' => 'Drop-Down Attribute Update',
'attribute_code' => 'dropdown_attribute',
'default_value' => null,
'frontend_class' => null,
'is_user_defined' => '1',
'backend_type' => 'varchar',
]
);
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
/**
* Product attribute data for attribute with input type multiple select.
*/
class MultipleSelect extends AbstractAttributeDataWithOptions
{
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'multiselect_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'multiselect';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Multiselect Attribute Update',
],
'frontend_input' => 'multiselect',
'is_required' => '1',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'is_unique' => '1',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_filterable' => '2',
'is_filterable_in_search' => '1',
'position' => '2',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '0',
'is_visible_on_front' => '1',
'used_in_product_listing' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
return array_merge(
$updatePostData,
[
'frontend_label' => 'Multiselect Attribute Update',
'attribute_code' => 'multiselect_attribute',
'default_value' => null,
'frontend_class' => null,
'used_for_sort_by' => '0',
'is_user_defined' => '1',
'backend_type' => 'text',
]
);
}
}
@@ -0,0 +1,150 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
/**
* Product attribute data for attribute with input type text.
*/
class Text extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function __construct()
{
parent::__construct();
$this->defaultAttributePostData['frontend_class'] = '';
$this->defaultAttributePostData['used_for_sort_by'] = '0';
}
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
return array_replace_recursive(
parent::getAttributeData(),
[
"{$this->getFrontendInput()}_with_input_validation" => [
array_merge($this->defaultAttributePostData, ['frontend_class' => 'validate-alpha']),
],
"{$this->getFrontendInput()}_without_input_validation" => [
$this->defaultAttributePostData,
],
]
);
}
/**
* @inheritdoc
*/
public function getAttributeDataWithCheckArray(): array
{
return array_merge_recursive(
parent::getAttributeDataWithCheckArray(),
[
"{$this->getFrontendInput()}_with_input_validation" => [
[
'attribute_code' => 'test_attribute_name',
'frontend_class' => 'validate-alpha',
],
],
"{$this->getFrontendInput()}_without_input_validation" => [
[
'attribute_code' => 'test_attribute_name',
'frontend_class' => '',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'varchar_attribute_update',
],
'expected_data' => [
'attribute_code' => 'varchar_attribute',
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'text';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Varchar Attribute Update',
],
'is_required' => '1',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'default_value_text' => 'Varchar Attribute Default',
'is_unique' => '1',
'frontend_class' => 'validate-alphanum',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '0',
'is_visible_on_front' => '1',
'used_in_product_listing' => '0',
'used_for_sort_by' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
unset($updatePostData['default_value_text']);
return array_merge(
$updatePostData,
[
'frontend_label' => 'Varchar Attribute Update',
'frontend_input' => 'text',
'attribute_code' => 'varchar_attribute',
'default_value' => 'Varchar Attribute Default',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'position' => '0',
'is_user_defined' => '1',
'backend_type' => 'varchar',
]
);
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\TestFramework\Eav\Model\Attribute\DataProvider;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Store\Model\Store;
/**
* Product attribute data for attribute with text area input type.
*/
class TextArea extends AbstractBaseAttributeData
{
/**
* @inheritdoc
*/
public function getAttributeData(): array
{
return array_replace_recursive(
parent::getAttributeData(),
[
"{$this->getFrontendInput()}_with_default_value" => [
[
'default_value_text' => '',
'default_value_textarea' => 'Default attribute value',
],
],
]
);
}
/**
* @inheritdoc
*/
public function getUpdateProvider(): array
{
$frontendInput = $this->getFrontendInput();
return array_replace_recursive(
parent::getUpdateProvider(),
[
"{$frontendInput}_other_attribute_code" => [
'post_data' => [
'attribute_code' => 'text_attribute_update',
],
'expected_data' => [
'attribute_code' => 'text_attribute',
],
],
"{$frontendInput}_change_frontend_input" => [
'post_data' => [
'frontend_input' => 'texteditor',
],
'expected_data' => [
'frontend_input' => 'textarea',
'is_wysiwyg_enabled' => '1'
],
],
]
);
}
/**
* @inheritdoc
*/
protected function getFrontendInput(): string
{
return 'textarea';
}
/**
* @inheritdoc
*/
protected function getUpdatePostData(): array
{
return [
'frontend_label' => [
Store::DEFAULT_STORE_ID => 'Text Attribute Update',
],
'frontend_input' => 'textarea',
'is_required' => '1',
'is_global' => ScopedAttributeInterface::SCOPE_WEBSITE,
'default_value_textarea' => 'Text Attribute Default',
'is_unique' => '1',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '1',
'search_weight' => '2',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '1',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '1',
'used_in_product_listing' => '1',
];
}
/**
* @inheritdoc
*/
protected function getUpdateExpectedData(): array
{
$updatePostData = $this->getUpdatePostData();
unset($updatePostData['default_value_textarea']);
return array_merge(
$updatePostData,
[
'frontend_label' => 'Text Attribute Update',
'attribute_code' => 'text_attribute',
'default_value' => 'Text Attribute Default',
'frontend_class' => null,
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'position' => '0',
'used_for_sort_by' => '0',
'is_user_defined' => '1',
'backend_type' => 'text',
'is_wysiwyg_enabled' => '0',
]
);
}
}

Some files were not shown because too many files have changed in this diff Show More