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,271 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Test for an environment-dependent DB adapter that implements \Magento\Framework\DB\Adapter\AdapterInterface
*/
namespace Magento\Framework\DB\Adapter;
/**
* @magentoDbIsolation disabled
*/
class InterfaceTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\DB\Adapter\AdapterInterface
*/
protected $_connection;
/**
* @var string
*/
protected $_tableName;
/**
* @var string
*/
protected $_oneColumnIdxName;
/**
* @var string
*/
protected $_twoColumnIdxName;
protected function setUp(): void
{
/** @var \Magento\Framework\Setup\ModuleDataSetupInterface $installer */
$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\Setup\ModuleDataSetupInterface::class
);
$this->_connection = $installer->getConnection();
$this->_tableName = $this->_connection->getTableName('table_two_column_idx');
$this->_oneColumnIdxName = $this->_connection->getIndexName($this->_tableName, ['column1']);
$this->_twoColumnIdxName = $this->_connection->getIndexName($this->_tableName, ['column1', 'column2']);
$table = $this->_connection->newTable(
$this->_tableName
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'column1',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER
)->addColumn(
'column2',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER
)->addIndex(
$this->_oneColumnIdxName,
['column1']
)->addIndex(
$this->_twoColumnIdxName,
['column1', 'column2']
);
$this->_connection->createTable($table);
}
/**
* Cleanup DDL cache for the fixture table
*/
protected function tearDown(): void
{
$this->_connection->dropTable($this->_tableName);
$this->_connection->resetDdlCache($this->_tableName);
$this->_connection = null;
}
protected function assertPreConditions(): void
{
$this->assertTrue(
$this->_connection->tableColumnExists($this->_tableName, 'column1'),
'Table column "column1" must be provided by the fixture.'
);
$this->assertTrue(
$this->_connection->tableColumnExists($this->_tableName, 'column2'),
'Table column "column2" must be provided by the fixture.'
);
$this->assertEquals(
['column1'],
$this->_getIndexColumns($this->_tableName, $this->_oneColumnIdxName),
'Single-column index must be provided by the fixture.'
);
$this->assertEquals(
['column1', 'column2'],
$this->_getIndexColumns($this->_tableName, $this->_twoColumnIdxName),
'Multiple-column index must be provided by the fixture.'
);
}
/**
* Retrieve list of columns used for an index or return false, if an index with a given name does not exist
*
* @param string $tableName
* @param string $indexName
* @param string|null $schemaName
* @return array|false
*/
protected function _getIndexColumns($tableName, $indexName, $schemaName = null)
{
foreach ($this->_connection->getIndexList($tableName, $schemaName) as $idxData) {
if ($idxData['KEY_NAME'] == $indexName) {
return $idxData['COLUMNS_LIST'];
}
}
return false;
}
public function testDropColumn()
{
$this->_connection->dropColumn($this->_tableName, 'column1');
$this->assertFalse(
$this->_connection->tableColumnExists($this->_tableName, 'column1'),
'Table column must not exist after it has been dropped.'
);
}
/**
* @depends testDropColumn
*/
public function testDropColumnRemoveFromIndexes()
{
$this->_connection->dropColumn($this->_tableName, 'column1');
$this->assertFalse(
$this->_getIndexColumns($this->_tableName, $this->_oneColumnIdxName),
'Column index must be dropped along with the column.'
);
$this->assertEquals(
['column2'],
$this->_getIndexColumns($this->_tableName, $this->_twoColumnIdxName),
'References to the dropped column must be removed from the multiple-column indexes.'
);
}
/**
* @depends testDropColumn
*/
public function testDropColumnRemoveIndexDuplicate()
{
$this->_connection->dropColumn($this->_tableName, 'column2');
$this->assertEquals(
['column1'],
$this->_getIndexColumns($this->_tableName, $this->_oneColumnIdxName),
'Column index must be preserved.'
);
$this->assertFalse(
$this->_getIndexColumns($this->_tableName, $this->_twoColumnIdxName),
'Multiple-column index must be dropped to not duplicate existing index by indexed columns.'
);
}
/**
* @param array $columns
* @param array $data
* @param array $expected
* @dataProvider insertArrayDataProvider
*/
public function testInsertArray(array $columns, array $data, array $expected)
{
$this->_connection->insertArray($this->_tableName, $columns, $data);
$select = $this->_connection->select()->from($this->_tableName, array_keys($expected[0]))->order('column1');
$result = $this->_connection->fetchAll($select);
$this->assertEquals($expected, $result);
}
/**
* Data provider for insertArray() test
*
* @return array
*/
public function insertArrayDataProvider()
{
return [
'one column' => [
['column1'],
[[1], [2]],
[['column1' => 1, 'column2' => null], ['column1' => 2, 'column2' => null]],
],
'one column simple' => [
['column1'],
[1, 2],
[['column1' => 1, 'column2' => null], ['column1' => 2, 'column2' => null]],
],
'two columns' => [
['column1', 'column2'],
[[1, 2], [3, 4]],
[['column1' => 1, 'column2' => 2], ['column1' => 3, 'column2' => 4]],
],
'several columns with identity' => [ // test possibility to insert data with filled identity field
['id', 'column1', 'column2'],
[[1, 0, 0], [2, 1, 1], [3, 2, 2]],
[
['id' => 1, 'column1' => 0, 'column2' => 0],
['id' => 2, 'column1' => 1, 'column2' => 1],
['id' => 3, 'column1' => 2, 'column2' => 2]
],
]
];
}
/**
*/
public function testInsertArrayTwoColumnsWithSimpleData()
{
$this->expectException(\Zend_Db_Exception::class);
$this->_connection->insertArray($this->_tableName, ['column1', 'column2'], [1, 2]);
}
/**
* @dataProvider insertDataProvider
*/
public function testInsertMultiple($data)
{
$this->_connection->insertMultiple($this->_tableName, $data);
$select = $this->_connection->select()->from($this->_tableName);
$result = $this->_connection->fetchRow($select);
$this->assertEquals($data, $result);
}
/**
* @dataProvider insertDataProvider
*/
public function testInsertOnDuplicate($data)
{
$this->_connection->insertOnDuplicate($this->_tableName, $data);
$select = $this->_connection->select()->from($this->_tableName);
$result = $this->_connection->fetchRow($select);
$this->assertEquals($data, $result);
}
/**
* @dataProvider insertDataProvider
*/
public function testInsertForce($data)
{
$this->assertEquals(1, $this->_connection->insertForce($this->_tableName, $data));
$select = $this->_connection->select()->from($this->_tableName);
$result = $this->_connection->fetchRow($select);
$this->assertEquals($data, $result);
}
/**
* Data provider for insert() tests
*
* @return array
*/
public function insertDataProvider()
{
return ['column with identity field' => [['id' => 1, 'column1' => 10, 'column2' => 20]]];
}
}
@@ -0,0 +1,296 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\DB\Adapter\Pdo;
use Magento\Framework\App\ResourceConnection;
use Magento\TestFramework\Helper\CacheCleaner;
use Magento\Framework\DB\Ddl\Table;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class checks Mysql adapter behaviour
*
* @magentoDbIsolation disabled
*/
class MysqlTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ResourceConnection
*/
private $resourceConnection;
protected function setUp(): void
{
set_error_handler(null);
$this->resourceConnection = Bootstrap::getObjectManager()
->get(ResourceConnection::class);
}
protected function tearDown(): void
{
restore_error_handler();
}
/**
* Check PDO stringify fetches options
*/
public function testStringifyFetchesTrue(): void
{
$tableName = $this->resourceConnection->getTableName('table_with_int_column');
$columnId = 'integer_column';
$adapter = $this->getDbAdapter();
$table = $adapter
->newTable($tableName)
->addColumn($columnId, Table::TYPE_INTEGER);
$adapter->createTable($table);
$adapter->insert($tableName, [$columnId => 100]);
$select = $adapter->select()
->from($tableName)
->columns([$columnId])
->limit(1);
$result = $adapter->fetchOne($select);
$this->assertIsString($result);
$adapter->dropTable($tableName);
}
/**
* Test lost connection re-initializing
*
* @throws \Exception
*/
public function testWaitTimeout()
{
if (!$this->getDbAdapter() instanceof \Magento\Framework\DB\Adapter\Pdo\Mysql) {
$this->markTestSkipped('This test is for \Magento\Framework\DB\Adapter\Pdo\Mysql');
}
try {
$minWaitTimeout = 1;
$this->setWaitTimeout($minWaitTimeout);
$this->assertEquals($minWaitTimeout, $this->getWaitTimeout(), 'Wait timeout was not changed');
// Sleep for time greater than wait_timeout and try to perform query
sleep($minWaitTimeout + 1);
$result = $this->executeQuery('SELECT 1');
$this->assertInstanceOf(\Magento\Framework\DB\Statement\Pdo\Mysql::class, $result);
} finally {
$this->getDbAdapter()->closeConnection();
}
}
/**
* Get session wait_timeout
*
* @return int
*/
private function getWaitTimeout()
{
$result = $this->executeQuery('SELECT @@session.wait_timeout');
return (int)$result->fetchColumn();
}
/**
* Set session wait_timeout
*
* @param int $waitTimeout
*/
private function setWaitTimeout($waitTimeout)
{
$this->executeQuery("SET @@session.wait_timeout = {$waitTimeout}");
}
/**
* Execute SQL query and return result statement instance
*
* @param $sql
* @return void|\Zend_Db_Statement_Pdo
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Zend_Db_Adapter_Exception
*/
private function executeQuery($sql)
{
return $this->getDbAdapter()->query($sql);
}
/**
* Retrieve database adapter instance
*
* @return \Magento\Framework\DB\Adapter\Pdo\Mysql
*/
private function getDbAdapter()
{
return $this->resourceConnection->getConnection();
}
public function testGetCreateTable()
{
$tableName = $this->resourceConnection->getTableName('core_config_data');
$this->assertEquals(
$this->getDbAdapter()->getCreateTable($tableName),
$this->getDbAdapter()->getCreateTable($tableName)
);
}
public function testGetForeignKeys()
{
$tableName = $this->resourceConnection->getTableName('core_config_data');
$this->assertEquals(
$this->getDbAdapter()->getForeignKeys($tableName),
$this->getDbAdapter()->getForeignKeys($tableName)
);
}
public function testGetIndexList()
{
$tableName = $this->resourceConnection->getTableName('core_config_data');
$this->assertEquals(
$this->getDbAdapter()->getIndexList($tableName),
$this->getDbAdapter()->getIndexList($tableName)
);
}
public function testDescribeTable()
{
$tableName = $this->resourceConnection->getTableName('core_config_data');
$this->assertEquals(
$this->getDbAdapter()->describeTable($tableName),
$this->getDbAdapter()->describeTable($tableName)
);
}
/**
* Test that Zend_Db_Expr can be used as a column default value.
* @see https://github.com/magento/magento2/pull/9131
*/
public function testCreateTableColumnWithExpressionAsColumnDefaultValue()
{
$adapter = $this->getDbAdapter();
$tableName = 'table_column_with_expression_as_column_default_value';
$table = $adapter
->newTable($tableName)
->addColumn(
'row_id',
Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Row Id'
)
->addColumn(
'created_at',
Table::TYPE_DATETIME,
null,
['default' => new \Zend_Db_Expr('CURRENT_TIMESTAMP')]
)
->addColumn(
'integer_column',
Table::TYPE_INTEGER,
11,
['default' => 123456]
)->addColumn(
'string_column',
Table::TYPE_TEXT,
255,
['default' => 'default test text']
)
->setComment('Test table column with expression as column default value');
$adapter->createTable($table);
$tableDescription = $adapter->describeTable($tableName);
//clean up database from test table
$adapter->dropTable($tableName);
$this->assertArrayHasKey('created_at', $tableDescription, 'Column created_at does not exists');
$this->assertArrayHasKey('integer_column', $tableDescription, 'Column integer_column does not exists');
$this->assertArrayHasKey('string_column', $tableDescription, 'Column string_column does not exists');
$dateColumn = $tableDescription['created_at'];
$intColumn = $tableDescription['integer_column'];
$stringColumn = $tableDescription['string_column'];
//Test default value with expression
$this->assertEquals('created_at', $dateColumn['COLUMN_NAME'], 'Incorrect column name');
$this->assertEquals(Table::TYPE_DATETIME, $dateColumn['DATA_TYPE'], 'Incorrect column type');
$this->assertMatchesRegularExpression(
'/(CURRENT_TIMESTAMP|current_timestamp\(\))/',
$dateColumn['DEFAULT'],
'Incorrect column default expression value'
);
//Test default value with integer value
$this->assertEquals('integer_column', $intColumn['COLUMN_NAME'], 'Incorrect column name');
$this->assertEquals('int', $intColumn['DATA_TYPE'], 'Incorrect column type');
$this->assertEquals(123456, $intColumn['DEFAULT'], 'Incorrect column default integer value');
//Test default value with string value
$this->assertEquals('string_column', $stringColumn['COLUMN_NAME'], 'Incorrect column name');
$this->assertEquals('varchar', $stringColumn['DATA_TYPE'], 'Incorrect column type');
$this->assertEquals('default test text', $stringColumn['DEFAULT'], 'Incorrect column default string value');
}
/**
* Test get auto increment field
*
* @param array $options
* @param string|bool $expected
* @throws \Zend_Db_Exception
* @dataProvider getAutoIncrementFieldDataProvider
*/
public function testGetAutoIncrementField(array $options, $expected)
{
$adapter = $this->getDbAdapter();
$tableName = 'table_auto_increment_field';
$table = $adapter
->newTable($tableName)
->addColumn(
'row_id',
Table::TYPE_INTEGER,
null,
$options,
'Row Id'
)
->addColumn(
'created_at',
Table::TYPE_DATETIME,
null,
['default' => new \Zend_Db_Expr('CURRENT_TIMESTAMP')]
)
->addColumn(
'integer_column',
Table::TYPE_INTEGER,
11,
['default' => 123456]
)->addColumn(
'string_column',
Table::TYPE_TEXT,
255,
['default' => 'default test text']
)
->setComment('Test table with auto increment column');
$adapter->createTable($table);
$autoIncrementField = $adapter->getAutoIncrementField($tableName);
$this->assertEquals($expected, $autoIncrementField);
//clean up database from test table
$adapter->dropTable($tableName);
}
public function getAutoIncrementFieldDataProvider()
{
return [
'auto increment field' => [
'field options' => ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'expected result' => 'row_id',
],
'non auto increment field' => [
'field options' => ['unsigned' => true, 'nullable' => false,],
'expected result' => false,
]
];
}
}
@@ -0,0 +1,347 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\DB\DataConverter;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Adapter\Pdo\Mysql;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\DB\FieldDataConversionException;
use Magento\Framework\DB\FieldDataConverter;
use Magento\Framework\DB\Select;
use Magento\Framework\DB\Select\QueryModifierInterface;
use Magento\Framework\DB\Select\InQueryModifier;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\DB\Query\Generator;
use Magento\Framework\DB\Query\BatchIterator;
use Magento\Framework\ObjectManagerInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class DataConverterTest extends TestCase
{
/**
* @var InQueryModifier|MockObject
*/
private $queryModifierMock;
/**
* @var SerializedToJson
*/
private $dataConverter;
/**
* @var BatchIterator|MockObject
*/
private $iteratorMock;
/**
* @var Generator|MockObject
*/
private $queryGeneratorMock;
/**
* @var Select|MockObject
*/
private $selectByRangeMock;
/**
* @var Mysql|MockObject
*/
private $adapterMock;
/**
* @var FieldDataConverter
*/
private $fieldDataConverter;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* Set up before test
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/** @var InQueryModifier $queryModifier */
$this->queryModifierMock = $this->getMockBuilder(QueryModifierInterface::class)
->disableOriginalConstructor()
->setMethods(['modify'])
->getMockForAbstractClass();
$this->dataConverter = $this->objectManager->get(SerializedToJson::class);
$this->iteratorMock = $this->getMockBuilder(BatchIterator::class)
->disableOriginalConstructor()
->setMethods(['current', 'valid', 'next'])
->getMock();
$iterationComplete = false;
// mock valid() call so iterator passes only current() result in foreach invocation
$this->iteratorMock->expects($this->any())
->method('valid')
->willReturnCallback(
function () use (&$iterationComplete) {
if (!$iterationComplete) {
$iterationComplete = true;
return true;
} else {
return false;
}
}
);
$this->queryGeneratorMock = $this->getMockBuilder(Generator::class)
->disableOriginalConstructor()
->setMethods(['generate'])
->getMock();
$this->selectByRangeMock = $this->getMockBuilder(Select::class)
->disableOriginalConstructor()
->setMethods([])
->getMock();
$this->queryGeneratorMock->expects($this->any())
->method('generate')
->willReturn($this->iteratorMock);
// mocking only current as next() is not supposed to be called
$this->iteratorMock->expects($this->any())
->method('current')
->willReturn($this->selectByRangeMock);
$this->adapterMock = $this->getMockBuilder(Mysql::class)
->disableOriginalConstructor()
->setMethods(['fetchPairs', 'fetchAll', 'quoteInto', 'update', 'prepareSqlCondition'])
->getMock();
$this->adapterMock->expects($this->any())
->method('quoteInto')
->willReturn('field=value');
$batchIteratorFactory = $this->createMock(\Magento\Framework\DB\Query\BatchRangeIteratorFactory::class);
$batchIteratorFactory->method('create')->willReturn($this->iteratorMock);
$this->fieldDataConverter = $this->objectManager->create(
FieldDataConverter::class,
[
'queryGenerator' => $this->queryGeneratorMock,
'dataConverter' => $this->dataConverter,
'batchIteratorFactory' => $batchIteratorFactory,
]
);
}
/**
* Test that exception with valid text is thrown when data is corrupted
*
*/
public function testDataConvertErrorReporting()
{
$this->expectException(FieldDataConversionException::class);
$this->expectExceptionMessage('Error converting field `value` in table `table` where `id`=2 using');
$rows = [
1 => 'N;',
2 => 'a:2:{s:3:"foo";s:3:"bar";s:3:"bar";s:',
];
$this->adapterMock->expects($this->any())
->method('fetchPairs')
->with($this->selectByRangeMock)
->willReturn($rows);
$this->adapterMock->expects($this->once())
->method('update')
->with('table', ['value' => 'null'], ['id IN (?)' => [1]]);
$this->fieldDataConverter->convert($this->adapterMock, 'table', 'id', 'value', $this->queryModifierMock);
}
public function testAlreadyConvertedDataSkipped()
{
$rows = [
2 => '[]',
3 => '{}',
4 => 'null',
5 => '""',
6 => '0',
7 => 'N;',
8 => '{"valid": "json value"}',
];
$this->adapterMock->expects($this->any())
->method('fetchPairs')
->with($this->selectByRangeMock)
->willReturn($rows);
$this->adapterMock->expects($this->once())
->method('update')
->with('table', ['value' => 'null'], ['id IN (?)' => [7]]);
$this->fieldDataConverter->convert($this->adapterMock, 'table', 'id', 'value', $this->queryModifierMock);
}
public function testAlreadyConvertedDataSkippedWithCompositeIdentifier(): void
{
$rows = [
[
'key_one' => 1,
'key_two' => 1,
'value' => '[]',
],
[
'key_one' => 1,
'key_two' => 2,
'value' => '{}',
],
[
'key_one' => 3,
'key_two' => 3,
'value' => 'N;',
],
[
'key_one' => 4,
'key_two' => 1,
'value' => '{"valid": "json value"}',
]
];
$this->adapterMock->expects($this->any())
->method('prepareSqlCondition')
->willReturnCallback(
function ($column, $value) {
return "$column = $value";
}
);
$this->adapterMock->expects($this->any())
->method('fetchAll')
->with($this->selectByRangeMock)
->willReturn($rows);
$this->adapterMock->expects($this->once())
->method('update')
->with('table', ['value' => 'null'], 'key_one = 3 AND key_two = 3');
$this->fieldDataConverter->convert($this->adapterMock, 'table', 'id1,id2', 'value', $this->queryModifierMock);
}
/**
* @magentoDbIsolation disabled
* @magentoDataFixture createFixtureTable
*/
public function testTableWithCompositeIdentifier(): void
{
$resource = Bootstrap::getObjectManager()->get(ResourceConnection::class);
$tableName = 'test_fixture_table';
$keyOneValues = range(1, 9);
$keyTwoValues = [3, 6, 9];
$records = [];
foreach ($keyOneValues as $keyOneValue) {
foreach (array_slice($keyTwoValues, 0, rand(1, 3)) as $keyTwoValue) {
$records[] = [
'key_one' => $keyOneValue,
'key_two' => $keyTwoValue,
// phpcs:ignore
'value' => serialize(['key_one' => $keyOneValue, 'key_two' => $keyTwoValue]),
];
}
}
// phpcs:ignore
$repeatedVal = serialize([]);
$records[] = [
'key_one' => 10,
'key_two' => 3,
'value' => $repeatedVal,
];
$records[] = [
'key_one' => 10,
'key_two' => 6,
'value' => $repeatedVal,
];
$records[] = [
'key_one' => 11,
'key_two' => 6,
'value' => $repeatedVal,
];
$resource->getConnection()->insertMultiple($tableName, $records);
$expected = [];
foreach ($records as $record) {
$record['value'] = $this->dataConverter->convert($record['value']);
$expected[] = $record;
}
$batchSize = 5;
$fieldDataConverter = $this->objectManager->create(
FieldDataConverter::class,
[
'dataConverter' => $this->dataConverter,
'envBatchSize' => $batchSize
]
);
$fieldDataConverter->convert($resource->getConnection(), $tableName, 'key_one,key_two', 'value');
$actual = $resource->getConnection()->fetchAll(
$resource->getConnection()->select()->from($tableName)
);
$this->assertEquals($expected, $actual, json_encode($records));
}
public static function createFixtureTable(): void
{
$resource = Bootstrap::getObjectManager()->get(ResourceConnection::class);
$tableName = 'test_fixture_table';
$table = $resource->getConnection()
->newTable(
$tableName
)
->addColumn(
'key_one',
Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false]
)
->addColumn(
'key_two',
Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false]
)
->addColumn(
'value',
Table::TYPE_TEXT,
null,
['nullable' => true]
)
->addIndex(
$tableName . '_index_key_one_key_two',
[
'key_one',
'key_two',
],
[
'type' => AdapterInterface::INDEX_TYPE_PRIMARY
]
);
$resource->getConnection()->createTable($table);
}
public static function createFixtureTableRollback(): void
{
$resource = Bootstrap::getObjectManager()->get(ResourceConnection::class);
$tableName = 'test_fixture_table';
$resource->getConnection()->dropTable($tableName);
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\DB;
class HelperTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\DB\Helper
*/
protected $_model;
/**
* @var \Magento\Framework\DB\Select
*/
protected $_select;
protected function setUp(): void
{
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\DB\Helper::class,
['modulePrefix' => 'core']
);
$collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Store\Model\ResourceModel\Store\Collection::class
);
$this->_select = $collection->getSelect();
}
public function testPrepareColumnsList()
{
$columns = $this->_model->prepareColumnsList($this->_select);
$this->assertContains('STORE_ID', array_keys($columns));
}
public function testAddGroupConcatColumn()
{
$select = (string)$this->_model->addGroupConcatColumn($this->_select, 'test_alias', 'store_id');
$this->assertStringContainsString('GROUP_CONCAT', $select);
$this->assertStringContainsString('test_alias', $select);
}
public function testGetDateDiff()
{
$diff = $this->_model->getDateDiff('2011-01-01', '2011-01-01');
$this->assertInstanceOf('Zend_Db_Expr', $diff);
$this->assertStringContainsString('TIMESTAMPDIFF(DAY', (string)$diff);
}
public function testAddLikeEscape()
{
$value = $this->_model->addLikeEscape('test');
$this->assertInstanceOf('Zend_Db_Expr', $value);
$this->assertStringContainsString('test', (string)$value);
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\DB;
use Magento\Framework\Flag;
class TransactionTest extends \PHPUnit\Framework\TestCase
{
protected $objectManager;
/**
* @var \Magento\Framework\DB\Transaction
*/
protected $_model;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $this->objectManager
->create(\Magento\Framework\DB\Transaction::class);
}
/**
* @magentoAppArea adminhtml
*/
public function testSaveDelete()
{
/** @var Flag $first */
$first = $this->objectManager->create(Flag::class, ['data' => ['flag_code' => 'test1']]);
$first->setFlagData('test1data');
$second = $this->objectManager->create(Flag::class, ['data' => ['flag_code' => 'test2']]);
$second->setFlagData('test2data');
$first->save();
$this->_model->addObject($first)->addObject($second, 'second');
$this->_model->save();
$this->assertNotEmpty($first->getId());
$this->assertNotEmpty($second->getId());
$this->_model->delete();
$test = $this->objectManager->create(Flag::class);
$test->load($first->getId());
$this->assertEmpty($test->getId());
}
/**
* @magentoDbIsolation disabled
*/
public function testTransactionLevelDbIsolationDisable()
{
$resourceConnection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\App\ResourceConnection::class);
$this->assertEquals(0, $resourceConnection->getConnection('default')->getTransactionLevel());
}
/**
* @magentoDbIsolation enabled
*/
public function testTransactionLevelDbIsolationEnabled()
{
$resourceConnection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\App\ResourceConnection::class);
$this->assertEquals(1, $resourceConnection->getConnection('default')->getTransactionLevel());
}
/**
* @magentoDataFixture Magento/Framework/DB/_files/dummy_fixture.php
*/
public function testTransactionLevelDbIsolationDefault()
{
$resourceConnection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\App\ResourceConnection::class);
$this->assertEquals(1, $resourceConnection->getConnection('default')->getTransactionLevel());
}
}
@@ -0,0 +1,8 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
//this fixture should not do anything