ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,129 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Model;
use Magento\Cms\Model\ResourceModel\Block;
use Magento\Cms\Model\BlockFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Stdlib\DateTime\Timezone;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
*/
class BlockTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Block
*/
private $blockResource;
/**
* @var BlockFactory
*/
private $blockFactory;
/**
* @var GetBlockByIdentifier
*/
private $blockIdentifier;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/** @var BlockFactory $blockFactory */
/** @var Block $blockResource */
/** @var GetBlockByIdentifier $getBlockByIdentifierCommand */
$this->blockResource = $this->objectManager->create(Block::class);
$this->blockFactory = $this->objectManager->create(BlockFactory::class);
$this->blockIdentifier = $this->objectManager->create(GetBlockByIdentifier::class);
}
/**
* Tests the get by identifier command
* @param array $blockData
* @throws \Exception
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDbIsolation enabled
* @dataProvider testGetByIdentifierDataProvider
*/
public function testGetByIdentifier(array $blockData)
{
# Prepare and save the temporary block
$tempBlock = $this->blockFactory->create();
$tempBlock->setData($blockData);
$this->blockResource->save($tempBlock);
# Load previously created block and compare identifiers
$storeId = reset($blockData['stores']);
$block = $this->blockIdentifier->execute($blockData['identifier'], $storeId);
$this->assertEquals($blockData['identifier'], $block->getIdentifier());
}
/**
* Tests the get by identifier command
* @param array $blockData
* @throws \Exception
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDbIsolation enabled
* @dataProvider testGetByIdentifierDataProvider
*/
public function testUpdateTime(array $blockData)
{
/**
* @var $db \Magento\Framework\DB\Adapter\AdapterInterface
*/
$db = $this->objectManager->get(\Magento\Framework\App\ResourceConnection::class)
->getConnection(ResourceConnection::DEFAULT_CONNECTION);
# Prepare and save the temporary block
$tempBlock = $this->blockFactory->create();
$tempBlock->setData($blockData);
$beforeTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
$this->blockResource->save($tempBlock);
$afterTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
# Load previously created block and compare identifiers
$storeId = reset($blockData['stores']);
$block = $this->blockIdentifier->execute($blockData['identifier'], $storeId);
$blockTimestamp = strtotime($block->getUpdateTime());
/*
* These checks prevent a race condition MAGETWO-87353
*/
$this->assertGreaterThanOrEqual($beforeTimestamp, $blockTimestamp);
$this->assertLessThanOrEqual($afterTimestamp, $blockTimestamp);
}
/**
* Data provider for "testGetByIdentifier" and "testUpdateTime" method
* @return array
*/
public function testGetByIdentifierDataProvider(): array
{
return [
[
'data' => [
'title' => 'Test title',
'stores' => [0],
'identifier' => 'test-identifier',
'content' => 'Test content',
'is_active' => 1
]
]
];
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Page;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
use Magento\Cms\Model\Page\CustomLayout\Data\CustomLayoutSelected;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\Framework\View\Result\PageFactory as PageResultFactory;
use Magento\Framework\View\Model\Layout\MergeFactory;
use Magento\Framework\View\Model\Layout\Merge;
/**
* Test the manager.
*/
class CustomLayoutManagerTest extends TestCase
{
/**
* @var CustomLayoutRepositoryInterface
*/
private $repo;
/**
* @var CustomLayoutManagerInterface
*/
private $manager;
/**
* @var PageFactory
*/
private $pageFactory;
/**
* @var PageResultFactory
*/
private $resultFactory;
/**
* @var IdentityMap
*/
private $identityMap;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->resultFactory = $objectManager->get(PageResultFactory::class);
//Mocking available list of files for the page.
$handles = [
'cms_page_view_selectable_page100_select1',
'cms_page_view_selectable_page100_select2'
];
$processor = $this->getMockBuilder(Merge::class)->disableOriginalConstructor()->getMock();
$processor->method('getAvailableHandles')->willReturn($handles);
$processorFactory = $this->getMockBuilder(MergeFactory::class)->disableOriginalConstructor()->getMock();
$processorFactory->method('create')->willReturn($processor);
$this->manager = $objectManager->create(
CustomLayoutManagerInterface::class,
['layoutProcessorFactory' => $processorFactory]
);
$this->repo = $objectManager->create(
CustomLayoutRepositoryInterface::class,
['manager' => $this->manager]
);
$this->pageFactory = $objectManager->get(PageFactory::class);
$this->identityMap = $objectManager->get(IdentityMap::class);
}
/**
* Test updating a page's custom layout.
*
* @magentoDataFixture Magento/Cms/_files/pages.php
* @throws \Throwable
* @return void
*/
public function testCustomLayoutUpdate(): void
{
/** @var Page $page */
$page = $this->pageFactory->create(['customLayoutRepository' => $this->repo]);
$page->load('page100', 'identifier');
$pageId = (int)$page->getId();
$this->identityMap->add($page);
//Set file ID
$this->repo->save(new CustomLayoutSelected($pageId, 'select2'));
//Test handles
$result = $this->resultFactory->create();
$this->manager->applyUpdate($result, $this->repo->getFor($pageId));
$this->identityMap->remove((int)$page->getId());
$this->assertContains(
'cms_page_view_selectable_page100_select2',
$result->getLayout()->getUpdate()->getHandles()
);
}
}
@@ -0,0 +1,160 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Page;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
use Magento\Cms\Model\Page\CustomLayout\Data\CustomLayoutSelected;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Model\Layout\Merge;
use Magento\Framework\View\Model\Layout\MergeFactory;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test the repository.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CustomLayoutRepositoryTest extends TestCase
{
/**
* @var CustomLayoutRepositoryInterface
*/
private $repo;
/**
* @var PageFactory
*/
private $pageFactory;
/**
* @var CustomLayoutManager
*/
private $fakeManager;
/**
* @var IdentityMap
*/
private $identityMap;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->configure([
'preferences' => [
\Magento\Cms\Model\Page\CustomLayoutManagerInterface::class =>
\Magento\TestFramework\Cms\Model\CustomLayoutManager::class
]
]);
$this->fakeManager = $objectManager->get(CustomLayoutManager::class);
$this->repo = $objectManager->create(CustomLayoutRepositoryInterface::class, ['manager' => $this->fakeManager]);
$this->pageFactory = $objectManager->get(PageFactory::class);
$this->identityMap = $objectManager->get(IdentityMap::class);
}
/**
* Create page instance.
*
* @param string $id
* @return Page
*/
private function createPage(string $id): Page
{
$page = $this->pageFactory->create(['customLayoutRepository' => $this->repo]);
$page->load($id, 'identifier');
$this->identityMap->add($page);
return $page;
}
/**
* Test updating a page's custom layout.
*
* @magentoDataFixture Magento/Cms/_files/pages.php
* @return void
*/
public function testCustomLayout(): void
{
$page = $this->createPage('page100');
$pageId = (int)$page->getId();
$this->fakeManager->fakeAvailableFiles($pageId, ['select1', 'select2']);
//Invalid file ID
$exceptionRaised = null;
try {
$this->repo->save(new CustomLayoutSelected($pageId, 'some_file'));
} catch (\Throwable $exception) {
$exceptionRaised = $exception;
}
$this->assertNotEmpty($exceptionRaised);
$this->assertInstanceOf(\InvalidArgumentException::class, $exceptionRaised);
//Set file ID
$this->repo->save(new CustomLayoutSelected($pageId, 'select2'));
//Test saved
$saved = $this->repo->getFor($pageId);
$this->assertEquals('select2', $saved->getLayoutFileId());
//Removing custom file
$this->repo->deleteFor($pageId);
//Test saved
$notFound = false;
try {
$this->repo->getFor($pageId);
} catch (NoSuchEntityException $exception) {
$notFound = true;
}
$this->assertTrue($notFound);
}
/**
* Test that layout updates are saved with save method.
*
* @magentoDataFixture Magento/Cms/_files/pages.php
* @return void
*/
public function testSaved(): void
{
$page = $this->createPage('page100');
$this->fakeManager->fakeAvailableFiles((int)$page->getId(), ['select1', 'select2']);
//Special no-update instruction
$page->setData('layout_update_selected', '_no_update_');
$page->save();
$this->assertNull($page->getData('layout_update_selected'));
//Existing file update
$page->setData('layout_update_selected', 'select1');
$page->save();
/** @var Page $page */
$page = $this->pageFactory->create();
$page->load('page100', 'identifier');
$this->assertEquals('select1', $page->getData('layout_update_selected'));
$this->assertEquals('select1', $this->repo->getFor((int)$page->getId())->getLayoutFileId());
//Invalid file
$caught = null;
$page->setData('layout_update_selected', 'nonExisting');
try {
$page->save();
} catch (\Throwable $exception) {
$caught = $exception;
}
$this->assertInstanceOf(LocalizedException::class, $caught);
$this->assertEquals($caught->getMessage(), 'Invalid Custom Layout Update selected');
}
}
@@ -0,0 +1,176 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Page;
use Magento\Cms\Api\GetPageByIdentifierInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test pages data provider.
*
* @magentoAppArea adminhtml
*/
class DataProviderTest extends TestCase
{
private $providerData = [
'name' => 'test',
'primaryFieldName' => 'page_id',
'requestFieldName' => 'page_id',
];
/**
* @var DataProvider
*/
private $provider;
/**
* @var GetPageByIdentifierInterface
*/
private $repo;
/**
* @var CustomLayoutManager
*/
private $filesFaker;
/**
* @var HttpRequest
*/
private $request;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->configure([
'preferences' => [CustomLayoutManagerInterface::class => CustomLayoutManager::class]
]);
$this->repo = $this->objectManager->get(GetPageByIdentifierInterface::class);
$this->filesFaker = $this->objectManager->get(CustomLayoutManager::class);
$this->request = $this->objectManager->get(HttpRequest::class);
$this->provider = $this->objectManager->create(
DataProvider::class,
array_merge($this->providerData, ['customLayoutManager' => $this->filesFaker])
);
}
/**
* Check that custom layout date is handled properly.
*
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
* @dataProvider customLayoutDataProvider
*
* @param string $identifier
* @param string|null $layoutUpdateSelected
* @return void
*/
public function testCustomLayoutData(string $identifier, ?string $layoutUpdateSelected): void
{
$page = $this->repo->execute($identifier, 0);
$request = $this->objectManager->create(RequestInterface::class);
$request->setParam('page_id', $page->getId());
$provider = $this->objectManager->create(
DataProvider::class,
array_merge($this->providerData, ['request' => $request])
);
$data = $provider->getData();
$pageData = $data[$page->getId()];
$this->assertEquals($layoutUpdateSelected, $pageData['layout_update_selected']);
}
/**
* DataProvider for testCustomLayoutData
*
* @return array
*/
public function customLayoutDataProvider(): array
{
return [
['test_custom_layout_page_1', '_existing_'],
['test_custom_layout_page_2', null],
['test_custom_layout_page_3', 'test_selected'],
];
}
/**
* Check that proper meta for custom layout field is returned.
*
* @return void
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
*/
public function testCustomLayoutMeta(): void
{
//Testing a page without layout xml
$page = $this->repo->execute('test_custom_layout_page_3', 0);
$this->filesFaker->fakeAvailableFiles((int)$page->getId(), ['test1', 'test2']);
$this->request->setParam('page_id', $page->getId());
$meta = $this->provider->getMeta();
$this->assertArrayHasKey('design', $meta);
$this->assertArrayHasKey('children', $meta['design']);
$this->assertArrayHasKey('custom_layout_update_select', $meta['design']['children']);
$this->assertArrayHasKey('arguments', $meta['design']['children']['custom_layout_update_select']);
$this->assertArrayHasKey('data', $meta['design']['children']['custom_layout_update_select']['arguments']);
$this->assertArrayHasKey(
'options',
$meta['design']['children']['custom_layout_update_select']['arguments']['data']
);
$expectedList = [
['label' => 'No update', 'value' => '_no_update_'],
['label' => 'test1', 'value' => 'test1'],
['label' => 'test2', 'value' => 'test2']
];
$metaList = $meta['design']['children']['custom_layout_update_select']['arguments']['data']['options'];
sort($expectedList);
sort($metaList);
$this->assertEquals($expectedList, $metaList);
//Page with old layout xml
$page = $this->repo->execute('test_custom_layout_page_1', 0);
$this->filesFaker->fakeAvailableFiles((int)$page->getId(), ['test3']);
$this->request->setParam('page_id', $page->getId());
$meta = $this->provider->getMeta();
$this->assertArrayHasKey('design', $meta);
$this->assertArrayHasKey('children', $meta['design']);
$this->assertArrayHasKey('custom_layout_update_select', $meta['design']['children']);
$this->assertArrayHasKey('arguments', $meta['design']['children']['custom_layout_update_select']);
$this->assertArrayHasKey('data', $meta['design']['children']['custom_layout_update_select']['arguments']);
$this->assertArrayHasKey(
'options',
$meta['design']['children']['custom_layout_update_select']['arguments']['data']
);
$expectedList = [
['label' => 'No update', 'value' => '_no_update_'],
['label' => 'Use existing layout update XML', 'value' => '_existing_'],
['label' => 'test3', 'value' => 'test3'],
];
$metaList = $meta['design']['children']['custom_layout_update_select']['arguments']['data']['options'];
sort($expectedList);
sort($metaList);
$this->assertEquals($expectedList, $metaList);
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model;
use Magento\Cms\Api\GetPageByIdentifierInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test page repo.
*/
class PageRepositoryTest extends TestCase
{
/**
* @var PageRepositoryInterface
*/
private $repo;
/**
* @var GetPageByIdentifierInterface
*/
private $retriever;
/**
* @inheritDoc
*/
protected function setUp(): void
{
Bootstrap::getObjectManager()->configure([
'preferences' => [
\Magento\Cms\Model\Page\CustomLayoutManagerInterface::class =>
\Magento\TestFramework\Cms\Model\CustomLayoutManager::class
]
]);
$objectManager = Bootstrap::getObjectManager();
$this->repo = $objectManager->get(PageRepositoryInterface::class);
$this->retriever = $objectManager->get(GetPageByIdentifierInterface::class);
}
/**
* Test that the field is deprecated.
*
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
* @return void
*/
public function testSaveUpdateXml(): void
{
$page = $this->retriever->execute('test_custom_layout_page_1', 0);
$page->setTitle($page->getTitle() . 'TEST');
//Is successfully saved without changes to the custom layout xml.
$page = $this->repo->save($page);
//New value is not accepted.
$page->setCustomLayoutUpdateXml('<container name="new_container_for_save_update_xml" />');
$forbidden = false;
try {
$page = $this->repo->save($page);
} catch (CouldNotSaveException $exception) {
$forbidden = true;
}
$this->assertTrue($forbidden);
//New value is not accepted.
$page->setLayoutUpdateXml('<container name="new_container_for_save_update_xml2" />');
$forbidden = false;
try {
$page = $this->repo->save($page);
} catch (CouldNotSaveException $exception) {
$forbidden = true;
}
$this->assertTrue($forbidden);
//Can be removed
$page->setCustomLayoutUpdateXml(null);
$page->setLayoutUpdateXml(null);
$page = $this->repo->save($page);
$this->assertEmpty($page->getCustomLayoutUpdateXml());
$this->assertEmpty($page->getLayoutUpdateXml());
}
/**
* Verifies that cms page with identifier which duplicates existed route shouldn't be saved
*
* @return void
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages.php
*/
public function testSaveWithRouteDuplicate(): void
{
$page = $this->retriever->execute('page100', 0);
$page->setIdentifier('customer');
$this->expectException(CouldNotSaveException::class);
$this->repo->save($page);
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Model;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Stdlib\DateTime\DateTime;
/**
* @magentoAppArea adminhtml
*/
class PageTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
\Magento\TestFramework\Bootstrap::ADMIN_NAME
);
/** @var $session \Magento\Backend\Model\Auth\Session */
$session = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Backend\Model\Auth\Session::class
);
$session->setUser($user);
}
/**
* Tests the get by identifier command
* @param array $pageData
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDbIsolation enabled
* @dataProvider testGetByIdentifierDataProvider
*/
public function testGetByIdentifier(array $pageData)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Cms\Model\GetPageByIdentifier $getPageByIdentifierCommand */
/** @var \Magento\Cms\Model\ResourceModel\Page $pageResource */
/** @var \Magento\Cms\Model\PageFactory $pageFactory */
$pageFactory = $objectManager->create(\Magento\Cms\Model\PageFactory::class);
$pageResource = $objectManager->create(\Magento\Cms\Model\ResourceModel\Page::class);
$getPageByIdentifierCommand = $objectManager->create(\Magento\Cms\Model\GetPageByIdentifier::class);
# Prepare and save the temporary page
$tempPage = $pageFactory->create();
$tempPage->setData($pageData);
$pageResource->save($tempPage);
# Load previously created block and compare identifiers
$storeId = reset($pageData['stores']);
$page = $getPageByIdentifierCommand->execute($pageData['identifier'], $storeId);
$this->assertEquals($pageData['identifier'], $page->getIdentifier());
}
/**
* @param array $data
* @param string $expectedIdentifier
* @magentoDbIsolation enabled
* @dataProvider generateIdentifierFromTitleDataProvider
*/
public function testGenerateIdentifierFromTitle($data, $expectedIdentifier)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Cms\Model\Page $page */
$page = $objectManager->create(\Magento\Cms\Model\Page::class);
$page->setData($data);
$page->save();
$this->assertEquals($expectedIdentifier, $page->getIdentifier());
}
/**
* @magentoDbIsolation enabled
*/
public function testUpdateTime()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/**
* @var $db \Magento\Framework\DB\Adapter\AdapterInterface
*/
$db = $objectManager->get(\Magento\Framework\App\ResourceConnection::class)
->getConnection(ResourceConnection::DEFAULT_CONNECTION);
/** @var \Magento\Cms\Model\Page $page */
$page = $objectManager->create(\Magento\Cms\Model\Page::class);
$page->setData(['title' => 'Test', 'stores' => [1]]);
$beforeTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
$page->save();
$afterTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
$page = $objectManager->get(PageRepositoryInterface::class)->getById($page->getId());
$pageTimestamp = strtotime($page->getUpdateTime());
/*
* These checks prevent a race condition MAGETWO-95534
*/
$this->assertGreaterThanOrEqual($beforeTimestamp, $pageTimestamp);
$this->assertLessThanOrEqual($afterTimestamp, $pageTimestamp);
}
public function generateIdentifierFromTitleDataProvider() : array
{
return [
['data' => ['title' => 'Test title', 'stores' => [1]], 'expectedIdentifier' => 'test-title'],
[
'data' => ['title' => 'Кирилический заголовок', 'stores' => [1]],
'expectedIdentifier' => 'kirilicheskij-zagolovok'
],
[
'data' => ['title' => 'Test title', 'identifier' => 'custom-identifier', 'stores' => [1]],
'expectedIdentifier' => 'custom-identifier'
]
];
}
/**
* Data provider for "testGetByIdentifier" method
* @return array
*/
public function testGetByIdentifierDataProvider() : array
{
return [
['data' => [
'title' => 'Test title',
'identifier' => 'test-identifier',
'page_layout' => '1column',
'stores' => [1],
'content' => 'Test content',
'is_active' => 1
]]
];
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\ResourceModel\Block\Grid;
use Magento\Cms\Model\ResourceModel\Page;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class CollectionTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* Verifies that filter condition date is being converted to config timezone before select sql query
*
* @dataProvider getCollectionFiltersDataProvider
* @return void
*/
public function testAddFieldToFilter($field): void
{
$filterDate = "2021-12-05 00:00:00";
/** @var TimezoneInterface $timeZone */
$timeZone = $this->objectManager->get(TimezoneInterface::class);
/** @var Collection $gridCollection */
$gridCollection = $this->objectManager->create(
Collection::class,
[
'mainTable' => 'cms_block',
'resourceModel' => Page::class
]
);
$convertedDate = $timeZone->convertConfigTimeToUtc($filterDate);
$collection = $gridCollection->addFieldToFilter($field, ['qteq' => $filterDate]);
$expectedSelectCondition = "`{$field}` = '{$convertedDate}'";
$this->assertStringContainsString($expectedSelectCondition, $collection->getSelectSql(true));
}
/**
* @return array
*/
public function getCollectionFiltersDataProvider(): array
{
return [
'cms_page_collection_for_creation_time' => [
'field' => 'creation_time',
],
'cms_page_collection_for_order_update_time' => [
'field' => 'update_time',
],
];
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\ResourceModel\Page\Grid;
use Magento\Cms\Model\ResourceModel\Page;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class CollectionTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* Verifies that filter condition date is being converted to config timezone before select sql query
*
* @dataProvider getCollectionFiltersDataProvider
* @return void
*/
public function testAddFieldToFilter($field): void
{
$filterDate = "2021-12-06 00:00:00";
/** @var TimezoneInterface $timeZone */
$timeZone = $this->objectManager->get(TimezoneInterface::class);
/** @var Collection $gridCollection */
$gridCollection = $this->objectManager->create(
Collection::class,
[
'mainTable' => 'cms_page',
'resourceModel' => Page::class
]
);
$convertedDate = $timeZone->convertConfigTimeToUtc($filterDate);
$collection = $gridCollection->addFieldToFilter($field, ['qteq' => $filterDate]);
$expectedSelectCondition = "`{$field}` = '{$convertedDate}'";
$this->assertStringContainsString($expectedSelectCondition, $collection->getSelectSql(true));
}
/**
* @return array
*/
public function getCollectionFiltersDataProvider(): array
{
return [
'cms_page_collection_for_creation_time' => [
'field' => 'creation_time',
],
'cms_page_collection_for_order_update_time' => [
'field' => 'update_time',
],
];
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Model\Wysiwyg;
use Magento\Framework\View\DesignInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestModuleWysiwygConfig\Model\Config as TestModuleWysiwygConfig;
/**
* @magentoAppArea adminhtml
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Cms\Model\Wysiwyg\Config
*/
private $model;
/**
* @var DesignInterface
*/
private $design;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->model = $objectManager->create(\Magento\Cms\Model\Wysiwyg\Config::class);
$this->design = $objectManager->get(DesignInterface::class);
}
/**
* Tests that config returns valid config array in it
*
* @return void
*/
public function testGetConfig()
{
$config = $this->model->getConfig();
$this->assertInstanceOf(\Magento\Framework\DataObject::class, $config);
}
/**
* Tests that config returns right urls going to the published library path
*
* @return void
*/
public function testGetConfigCssUrls()
{
$config = $this->model->getConfig();
$designTheme = $this->design->getConfigurationDesignTheme('adminhtml');
$publicPathPattern = "http://localhost/static/%s/adminhtml/{$designTheme}/en_US/%s";
$tinyMceConfig = $config->getData('tinymce');
$contentCss = $tinyMceConfig['content_css'];
if (is_array($contentCss)) {
foreach ($contentCss as $url) {
$this->assertStringMatchesFormat($publicPathPattern, $url);
}
} else {
$this->assertStringMatchesFormat($publicPathPattern, $contentCss);
}
}
/**
* Test enabled module is able to modify WYSIWYG config
*
* @return void
*
* @magentoConfigFixture default/cms/wysiwyg/editor Magento_TestModuleWysiwygConfig/wysiwyg/tinymceTestAdapter
*/
public function testTestModuleEnabledModuleIsAbleToModifyConfig()
{
$objectManager = Bootstrap::getObjectManager();
$compositeConfigProvider = $objectManager->create(\Magento\Cms\Model\Wysiwyg\CompositeConfigProvider::class);
$model = $objectManager->create(
\Magento\Cms\Model\Wysiwyg\Config::class,
['configProvider' => $compositeConfigProvider]
);
$config = $model->getConfig();
// @phpstan-ignore-next-line
$this->assertEquals(TestModuleWysiwygConfig::CONFIG_HEIGHT, $config['height']);
// @phpstan-ignore-next-line
$this->assertEquals(TestModuleWysiwygConfig::CONFIG_CONTENT_CSS, $config['content_css']);
$this->assertArrayHasKey('tinymce', $config);
$this->assertArrayHasKey('toolbar', $config['tinymce']);
$this->assertStringNotContainsString(
'charmap',
$config['tinymce']['toolbar'],
'Failed to address that the custom test module removes "charmap" button from the toolbar'
);
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Wysiwyg\Images;
use Magento\Backend\Model\UrlInterface;
use Magento\Cms\Helper\Wysiwyg\Images as ImagesHelper;
use Magento\Framework\Url\EncoderInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class GetInsertImageContentTest extends TestCase
{
/**
* @var GetInsertImageContent
*/
private $getInsertImageContent;
/**
* @var ImagesHelper
*/
private $imagesHelper;
/**
* @var EncoderInterface
*/
private $urlEncoder;
/**
* @var UrlInterface
*/
protected $url;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->getInsertImageContent = Bootstrap::getObjectManager()->get(GetInsertImageContent::class);
$this->imagesHelper = Bootstrap::getObjectManager()->get(ImagesHelper::class);
$this->urlEncoder = Bootstrap::getObjectManager()->get(EncoderInterface::class);
$this->url = Bootstrap::getObjectManager()->get(UrlInterface::class);
}
/**
* Test for GetInsertImageContent::execute
*
* @dataProvider imageDataProvider
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @param string $filename
* @param bool $forceStaticPath
* @param bool $renderAsTag
* @param string|null $storeCode
* @param string $expectedResult
*/
public function testExecute(
string $filename,
bool $forceStaticPath,
bool $renderAsTag,
?string $storeCode,
string $expectedResult
): void {
$storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class);
$storeId = $storeCode ? (int)$storeManager->getStore($storeCode)->getId() : null;
if (!$forceStaticPath && !$renderAsTag && !$this->imagesHelper->isUsingStaticUrlsAllowed()) {
$expectedResult = $this->url->getUrl(
'cms/wysiwyg/directive',
[
'___directive' => $this->urlEncoder->encode($expectedResult),
'_escape_params' => false,
]
);
}
$this->assertEquals(
$expectedResult,
$this->getInsertImageContent->execute(
$this->imagesHelper->idEncode($filename),
$forceStaticPath,
$renderAsTag,
$storeId
)
);
}
/**
* Data provider for testExecute
*
* @return array[]
*/
public function imageDataProvider(): array
{
return [
[
'test-image.jpg',
false,
true,
'default',
'<img src="{{media url=&quot;test-image.jpg&quot;}}" alt="" />',
],
[
'catalog/category/test-image.jpg',
true,
false,
'default',
'/media/catalog/category/test-image.jpg',
],
[
'test-image.jpg',
false,
false,
'default',
'{{media url="test-image.jpg"}}',
],
[
'/test-image.jpg',
false,
true,
'fixturestore',
'<img src="{{media url=&quot;/test-image.jpg&quot;}}" alt="" />',
],
[
'test-image.jpg',
false,
true,
null,
'<img src="{{media url=&quot;test-image.jpg&quot;}}" alt="" />',
],
];
}
}
@@ -0,0 +1,185 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*
*/
namespace Magento\Cms\Model\Wysiwyg\Images;
use Magento\Cms\Model\Wysiwyg\Images\Storage\Collection;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\DataObject;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem\DriverInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test methods of class Storage
*
* @SuppressWarnings(PHPMD.LongVariable)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class GetThumbnailUrlsTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Storage
*/
private $storage;
/**
* @var DriverInterface
*/
private $driver;
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->filesystem = $this->objectManager->get(Filesystem::class);
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = rtrim($this->imagesHelper->getStorageRoot(), '/')
. '/MagentoCmsModelWysiwygImagesStorageTest';
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['MagentoCmsModelWysiwygImagesStorageTest']),
);
$this->storage = $this->objectManager->create(Storage::class);
$this->driver = $this->mediaDirectory->getDriver();
}
protected function tearDown(): void
{
$this->mediaDirectory->delete($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* Test that getThumbnailUrl() returns correct URL for root folder or sub-folders images
*
* @param string $directory
* @param string $filename
* @param array $expectedUrls
* @return void
* @magentoAppIsolation enabled
* @magentoAppArea adminhtml
* @dataProvider getThumbnailUrlDataProvider
*/
public function testGetThumbnailUrl(string $directory, string $filename, array $expectedUrls): void
{
$root = $this->storage->getCmsWysiwygImages()->getStorageRoot();
$directory = implode('/', array_filter([rtrim($root, '/'), trim($directory, '/')]));
$path = $directory . '/' . $filename;
$this->generateImage($path);
$this->storage->resizeFile($path);
$collection = $this->storage->getFilesCollection($directory, 'image');
$paths = [];
foreach ($collection as $item) {
$paths[] = parse_url($item->getThumbUrl(), PHP_URL_PATH);
}
$this->assertEquals($expectedUrls, $paths);
$this->driver->deleteFile($path);
}
/**
* Provide scenarios for testing getThumbnailUrl()
*
* @return array
*/
public function getThumbnailUrlDataProvider(): array
{
return [
[
'/',
'image1.png',
[]
],
[
'/cms',
'image2.png',
[]
],
[
'/cms/pages',
'image3.png',
[]
],
[
'/MagentoCmsModelWysiwygImagesStorageTest',
'image2.png',
['/media/.thumbsMagentoCmsModelWysiwygImagesStorageTest/image2.png']
],
[
'/MagentoCmsModelWysiwygImagesStorageTest/pages',
'image3.png',
['/media/.thumbsMagentoCmsModelWysiwygImagesStorageTest/pages/image3.png']
]
];
}
/**
* Generate a dummy image of the given width and height.
*
* @param string $path
* @return string
*/
private function generateImage(string $path)
{
$this->mediaDirectory->create(dirname($this->mediaDirectory->getRelativePath($path)));
ob_start();
$image = imagecreatetruecolor(1024, 768);
imagepng($image);
$this->driver->filePutContents($path, ob_get_clean());
return $path;
}
}
@@ -0,0 +1,394 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*
*/
namespace Magento\Cms\Model\Wysiwyg\Images;
use Magento\Cms\Model\Wysiwyg\Images\Storage\Collection;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\DataObject;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem\DriverInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test methods of class Storage
*
* @SuppressWarnings(PHPMD.LongVariable)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class StorageTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Storage
*/
private $storage;
/**
* @var DriverInterface
*/
private $driver;
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->filesystem = $this->objectManager->get(Filesystem::class);
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = rtrim($this->imagesHelper->getStorageRoot(), '/')
. '/MagentoCmsModelWysiwygImagesStorageTest';
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['MagentoCmsModelWysiwygImagesStorageTest']),
);
$this->storage = $this->objectManager->create(Storage::class);
$this->driver = $this->mediaDirectory->getDriver();
}
protected function tearDown(): void
{
$this->mediaDirectory->delete($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* @magentoAppIsolation enabled
* @return void
*/
public function testGetFilesCollection(): void
{
Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$fileName = 'magento_image.jpg';
$imagePath = realpath(__DIR__ . '/../../../../Catalog/_files/' . $fileName);
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$modifiableFilePath = $mediaDirectory->getAbsolutePath('MagentoCmsModelWysiwygImagesStorageTest/' . $fileName);
$this->driver->copy(
$imagePath,
$modifiableFilePath
);
$this->storage->resizeFile($modifiableFilePath);
$collection = $this->storage->getFilesCollection($this->fullDirectoryPath, '/image');
$this->assertInstanceOf(Collection::class, $collection);
foreach ($collection as $item) {
$thumbUrl = parse_url($item->getThumbUrl(), PHP_URL_PATH);
$this->assertInstanceOf(DataObject::class, $item);
$this->assertStringEndsWith('/' . $fileName, $item->getUrl());
$this->assertEquals(
'/media/.thumbsMagentoCmsModelWysiwygImagesStorageTest/magento_image.jpg',
$thumbUrl,
"Check if Thumbnail URL is equal to the generated URL"
);
$this->assertEquals(
'image/jpeg',
$item->getMimeType(),
"Check if Mime Type is equal to the image in the file system"
);
return;
}
}
/**
* @magentoAppArea adminhtml
* @return void
*/
public function testGetThumbsPath(): void
{
$this->assertStringStartsWith(
$this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(),
$this->storage->getThumbsPath()
);
}
/**
* @return void
*/
public function testDeleteDirectory(): void
{
$path = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath();
$dir = 'MagentoCmsModelWysiwygImagesStorageTest/testDeleteDirectory';
$fullPath = $path . $dir;
$this->storage->createDirectory('testDeleteDirectory', $path . '/MagentoCmsModelWysiwygImagesStorageTest');
$this->assertTrue($this->mediaDirectory->isExist($fullPath));
$this->storage->deleteDirectory($fullPath);
$this->assertFileDoesNotExist($fullPath);
}
/**
* @return void
*/
public function testDeleteDirectoryWithExcludedDirPath(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('We cannot delete the selected directory.');
$dir = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath() . 'downloadable';
$this->storage->deleteDirectory($dir);
}
/**
* @return void
*/
public function testUploadFile(): void
{
$fileName = 'magento_small_image.jpg';
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$fixtureDir = realpath(__DIR__ . '/../../../../Catalog/_files');
copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image/jpeg',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$this->storage->uploadFile($this->fullDirectoryPath);
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . DIRECTORY_SEPARATOR . $fileName));
// phpcs:enable
}
/**
* @return void
*/
public function testUploadFileWithExcludedDirPath(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage(
'We can\'t upload the file to the current folder right now. Please try another folder.'
);
$fileName = 'magento_small_image.jpg';
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$fixtureDir = realpath(__DIR__ . '/../../../../Catalog/_files');
copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image/jpeg',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$dir = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath() . 'downloadable';
$this->storage->uploadFile($dir);
// phpcs:enable
}
/**
* @param string $fileName
* @param string $fileType
* @param string|null $storageType
*
* @return void
* @dataProvider testUploadFileWithWrongExtensionDataProvider
*/
public function testUploadFileWithWrongExtension(string $fileName, string $fileType, ?string $storageType): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('File validation failed.');
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$fixtureDir = realpath(__DIR__ . '/../../../_files');
copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => $fileType,
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$this->storage->uploadFile($this->fullDirectoryPath, $storageType);
$this->assertFalse(is_file($this->fullDirectoryPath . DIRECTORY_SEPARATOR . $fileName));
// phpcs:enable
}
/**
* @return array
*/
public function testUploadFileWithWrongExtensionDataProvider(): array
{
return [
[
'fileName' => 'text.txt',
'fileType' => 'text/plain',
'storageType' => null,
],
[
'fileName' => 'test.swf',
'fileType' => 'application/x-shockwave-flash',
'storageType' => 'media',
],
];
}
/**
* @return void
*/
public function testUploadFileWithWrongFile(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('File validation failed.');
$fileName = 'file.gif';
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$file = fopen($filePath, "wb");
fwrite($file, 'just a text');
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image/gif',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$this->storage->uploadFile($this->fullDirectoryPath);
$this->assertFalse(is_file($this->fullDirectoryPath . DIRECTORY_SEPARATOR . $fileName));
// phpcs:enable
}
/**
* Verify thumbnail generation for diferent sizes
*
* @param array $sizes
* @param bool $resized
* @dataProvider getThumbnailsSizes
*/
public function testResizeFile(array $sizes, bool $resized): void
{
$root = $this->storage->getCmsWysiwygImages()->getStorageRoot();
$path = rtrim($root, '/') . '/testfile.png';
$this->generateImage($path, $sizes['width'], $sizes['height']);
$this->storage->resizeFile($path);
$thumbPath = $this->storage->getThumbnailPath($path);
list($imageWidth, $imageHeight) = getimagesizefromstring($this->driver->fileGetContents($thumbPath));
$this->assertEquals(
$resized ? $this->storage->getResizeWidth() : $sizes['width'],
$imageWidth
);
$this->assertLessThanOrEqual(
$resized ? $this->storage->getResizeHeight() : $sizes['height'],
$imageHeight
);
$this->driver->deleteFile($path);
}
/**
* Provide sizes for resizeFile test
*/
public function getThumbnailsSizes(): array
{
return [
[
[
'width' => 1024,
'height' => 768,
],
true
],
[
[
'width' => 20,
'height' => 20,
],
false
]
];
}
/**
* Generate a dummy image of the given width and height.
*
* @param string $path
* @param int $width
* @param int $height
* @return string
*/
private function generateImage(string $path, int $width = 1024, int $height = 768)
{
$this->mediaDirectory->create(dirname($this->mediaDirectory->getRelativePath($path)));
$extension = pathinfo($path, PATHINFO_EXTENSION);
ob_start();
$image = imagecreatetruecolor($width, $height);
switch ($extension) {
case 'jpeg':
imagejpeg($image);
break;
case 'png':
imagepng($image);
break;
}
$this->driver->filePutContents($path, ob_get_clean());
return $path;
}
}