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,57 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category;
use Magento\Catalog\Helper\DefaultCategory;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for catalog category Add controller
*
* @see \Magento\Catalog\Controller\Adminhtml\Category\Add
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class AddTest extends AbstractBackendController
{
/**
* @var DefaultCategory
*/
private $defaultCategoryHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->defaultCategoryHelper = $this->_objectManager->get(DefaultCategory::class);
}
/**
* @return void
*/
public function testExecuteWithoutParams(): void
{
$this->dispatch('backend/catalog/category/add');
$this->assertRedirect($this->stringContains('catalog/category/index'));
}
/**
* @return void
*/
public function testExecuteAsAjax(): void
{
$this->getRequest()->setQueryValue('isAjax', true);
$this->getRequest()->setParam('parent', $this->defaultCategoryHelper->getId());
$this->dispatch('backend/catalog/category/add');
$this->assertJson($this->getResponse()->getBody());
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Delete;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Indexer\Category\Flat\State;
use Magento\Catalog\Model\ResourceModel\Category\Flat as CategoryFlatResource;
use Magento\Catalog\Model\ResourceModel\Category\Flat\CollectionFactory;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test cases related to delete category with enabled category flat.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class DeleteCategoryWithEnabledFlatTest extends AbstractBackendController
{
const STUB_CATEGORY_ID = 333;
/**
* @var IndexerRegistry
*/
private $indexerRegistry;
/**
* @var CategoryRepositoryInterface
*/
private $categoryRepository;
/**
* @var CategoryFlatResource
*/
private $categoryFlatResource;
/**
* @var CollectionFactory
*/
private $categoryFlatCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->indexerRegistry = $this->_objectManager->get(IndexerRegistry::class);
$this->categoryRepository = $this->_objectManager->get(CategoryRepositoryInterface::class);
$this->categoryFlatResource = $this->_objectManager->get(CategoryFlatResource::class);
$this->categoryFlatCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
parent::tearDown();
$categoryFlatIndexer = $this->indexerRegistry->get(State::INDEXER_ID);
$categoryFlatIndexer->invalidate();
$this->categoryFlatResource->getConnection()->dropTable($this->categoryFlatResource->getMainTable());
}
/**
* Check that product is deleted from flat table.
*
* @magentoConfigFixture current_store catalog/frontend/flat_catalog_category true
*
* @magentoDataFixture Magento/Catalog/_files/category.php
* @magentoDataFixture Magento/Catalog/_files/reindex_catalog_category_flat.php
*
* @return void
*/
public function testDeleteCategory(): void
{
// Given
$this->assertEquals(1, $this->getFlatCategoryCollectionSizeByCategoryId(self::STUB_CATEGORY_ID));
// When
$this->sendDeleteCategoryRequest(self::STUB_CATEGORY_ID);
// Then
$this->assertSessionMessages($this->equalTo([(string)__('You deleted the category.')]));
$this->assertEquals(0, $this->getFlatCategoryCollectionSizeByCategoryId(self::STUB_CATEGORY_ID));
$this->checkCategoryIsDeleted(self::STUB_CATEGORY_ID);
}
/**
* Return collection size from category flat collection by category ID.
*
* @param int $categoryId
* @return int
*/
private function getFlatCategoryCollectionSizeByCategoryId(int $categoryId): int
{
$categoryFlatCollection = $this->categoryFlatCollectionFactory->create();
$categoryFlatCollection->addIdFilter($categoryId);
return $categoryFlatCollection->getSize();
}
/**
* Assert that category is deleted.
*
* @param int $categoryId
* @return void
*/
private function checkCategoryIsDeleted(int $categoryId): void
{
$this->expectExceptionObject(
new NoSuchEntityException(__("No such entity with id = %entityId", ['entityId' => $categoryId]))
);
$this->categoryRepository->get($categoryId);
}
/**
* Method passes the request to Backend to remove given category.
*
* @param int $categoryId
* @return void
*/
private function sendDeleteCategoryRequest(int $categoryId): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['id' => $categoryId]);
$this->dispatch('backend/catalog/category/delete');
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test for class \Magento\Catalog\Controller\Adminhtml\Category\Delete
*
* @magentoAppArea adminhtml
*/
class DeleteTest extends AbstractBackendController
{
/**
* @return void
*/
public function testDeleteMissingCategory(): void
{
$incorrectId = 825852;
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['id' => $incorrectId]);
$this->dispatch('backend/catalog/category/delete');
$this->assertSessionMessages(
$this->equalTo([(string)__(sprintf('No such entity with id = %s', $incorrectId))]),
MessageInterface::TYPE_ERROR
);
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/category.php
*/
public function testDeleteCategory(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['id' => 333]);
$this->dispatch('backend/catalog/category/delete');
$this->assertSessionMessages($this->equalTo([(string)__('You deleted the category.')]));
}
}
@@ -0,0 +1,74 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test cases related to edit category.
*
* @see \Magento\Catalog\Controller\Adminhtml\Category\Edit
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class EditTest extends AbstractBackendController
{
/** @var CollectionFactory */
private $categoryCollectionFactory;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->categoryCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_root_category.php
*
* @return void
*/
public function testSwitchingStoreViewsCategory(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$id = (int)$this->getCategoryIdByName('Second Root Category');
$storeId = (int)$this->storeManager->getStore('default')->getId();
$this->getRequest()->setParams(['store' => $storeId, 'id' => $id]);
$this->dispatch('backend/catalog/category/edit');
$this->assertRedirect($this->stringContains('backend/catalog/category/index'));
$this->assertStringNotContainsString('/id/', $this->getResponse()->getHeader('Location')->getFieldValue());
}
/**
* Get category id by name
*
* @param string $name
* @return string|null
*/
private function getCategoryIdByName(string $name): ?string
{
$categoryCollection = $this->categoryCollectionFactory->create();
$category = $categoryCollection
->addAttributeToFilter(CategoryInterface::KEY_NAME, $name)
->setPageSize(1)
->getFirstItem();
return $category->getId();
}
}
@@ -0,0 +1,33 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for catalog category grid controller
*
* @see \Magento\Catalog\Controller\Adminhtml\Category\Grid
* @magentoAppArea adminhtml
*/
class GridTest extends AbstractBackendController
{
/**
* @magentoDbIsolation enabled
* @return void
*/
public function testRenderCategoryGrid(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/category/grid');
$content = $this->getResponse()->getBody();
$this->assertEquals(1, Xpath::getElementsCountForXpath('//div[@id="catalog_category_products"]', $content));
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Image;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test cases related to upload category image.
*
* @see \Magento\Catalog\Controller\Adminhtml\Category\Image\Upload
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class UploadTest extends AbstractBackendController
{
/** @var Filesystem */
private $filesystem;
/** @var WriteInterface */
private $tmpDirectory;
/** @var SerializerInterface */
private $json;
/** @var string */
private $fileToRemove;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->filesystem = $this->_objectManager->get(Filesystem::class);
$this->tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::TMP);
$this->json = $this->_objectManager->get(SerializerInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
if (file_exists($this->fileToRemove)) {
unlink($this->fileToRemove);
}
parent::tearDown();
}
/**
* @return void
*/
public function testWithNotAllowedFileExtension(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue('param_name', 'image');
$this->prepareFile('empty.csv');
$this->dispatch('backend/catalog/category_image/upload');
$responseBody = $this->json->unserialize($this->getResponse()->getBody());
$this->assertNotEmpty($responseBody['error']);
$this->assertStringContainsString((string)__('File validation failed.'), $responseBody['error']);
}
/**
* Prepare file
*
* @param string $fileName
* @return void
*/
private function prepareFile(string $fileName): void
{
$this->tmpDirectory->create($this->tmpDirectory->getAbsolutePath());
$filePath = $this->tmpDirectory->getAbsolutePath($fileName);
$this->fileToRemove = $filePath;
$fixtureDir = realpath(__DIR__ . '/../../../../_files');
$this->tmpDirectory->getDriver()->copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
}
}
@@ -0,0 +1,62 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Save;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Abstract save category.
*/
class AbstractSaveCategoryTest extends AbstractBackendController
{
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->serializer = $this->_objectManager->get(SerializerInterface::class);
}
/**
* Perform save category request with category POST data.
*
* @param array $data
* @return array
*/
protected function performSaveCategoryRequest(array $data): array
{
$data['return_session_messages_only'] = true;
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/catalog/category/save');
return $this->serializer->unserialize($this->getResponse()->getBody());
}
/**
* Assert that session has message about successfully category save.
*
* @param array $responseData
* @return void
*/
protected function assertRequestIsSuccessfullyPerformed(array $responseData): void
{
$this->assertTrue(isset($responseData['category']['entity_id']));
$this->assertFalse($responseData['error'], 'Response message: ' . $responseData['messages']);
$message = str_replace('.', '\.', (string)__('You saved the category.'));
$this->assertMatchesRegularExpression("/>{$message}</", $responseData['messages']);
}
}
@@ -0,0 +1,150 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Save;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Cms\Api\GetBlockByIdentifierInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
/**
* Test cases for save category controller.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class SaveCategoryTest extends AbstractSaveCategoryTest
{
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var GetBlockByIdentifierInterface */
private $getBlockByIdentifier;
/** @var string */
private $createdCategoryId;
/** @var StoreManagerInterface */
private $storeManager;
/** @var CollectionFactory */
private $categoryCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->categoryRepository = $this->_objectManager->get(CategoryRepositoryInterface::class);
$this->getBlockByIdentifier = $this->_objectManager->get(GetBlockByIdentifierInterface::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->categoryCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
if (!empty($this->createdCategoryId)) {
try {
$this->categoryRepository->deleteByIdentifier($this->createdCategoryId);
} catch (NoSuchEntityException $e) {
//Category already deleted.
}
$this->createdCategoryId = null;
}
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Cms/_files/block.php
*
* @return void
*/
public function testCreateCategoryWithCmsBlock(): void
{
$storeId = (int)$this->storeManager->getStore('default')->getId();
$blockId = $this->getBlockByIdentifier->execute('fixture_block', $storeId)->getId();
$postData = [
CategoryInterface::KEY_NAME => 'Category with cms block',
CategoryInterface::KEY_IS_ACTIVE => 1,
CategoryInterface::KEY_INCLUDE_IN_MENU => 1,
'display_mode' => Category::DM_MIXED,
'landing_page' => $blockId,
CategoryInterface::KEY_AVAILABLE_SORT_BY => ['position'],
'default_sort_by' => 'position',
];
$responseData = $this->performSaveCategoryRequest($postData);
$this->assertRequestIsSuccessfullyPerformed($responseData);
$this->createdCategoryId = $responseData['category']['entity_id'];
$category = $this->categoryRepository->get($this->createdCategoryId);
$this->assertEquals($blockId, $category->getLandingPage());
}
/**
* @return void
*/
public function testTryToCreateCategoryWithEmptyValues(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue([
CategoryInterface::KEY_NAME => 'test',
CategoryInterface::KEY_IS_ACTIVE => 1,
'use_config' => [],
'return_session_messages_only' => false,
]);
$this->dispatch('backend/catalog/category/save');
$message = (string)__(
'The "%1" attribute is required. Enter and try again.',
'Available Product Listing Sort By'
);
$this->assertSessionMessages($this->containsEqual($message), MessageInterface::TYPE_ERROR);
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_root_category.php
*
* @return void
*/
public function testSwitchingStoreViewsCategory(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$id = (int)$this->getCategoryIdByName('Second Root Category');
$storeId = (int)$this->storeManager->getStore('default')->getId();
$this->getRequest()->setParams(['store' => $storeId, 'id' => $id]);
$this->dispatch('backend/catalog/category/save');
$this->assertRedirect($this->stringContains('backend/catalog/category/index'));
$this->assertStringNotContainsString('/id/', $this->getResponse()->getHeader('Location')->getFieldValue());
}
/**
* Get category id by name
*
* @param string $name
* @return string|null
*/
private function getCategoryIdByName(string $name): ?string
{
$categoryCollection = $this->categoryCollectionFactory->create();
$category = $categoryCollection
->addAttributeToFilter(CategoryInterface::KEY_NAME, $name)
->setPageSize(1)
->getFirstItem();
return $category->getId();
}
}
@@ -0,0 +1,268 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Save;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Indexer\Category\Flat;
use Magento\Catalog\Model\Indexer\Category\Flat\State;
use Magento\Catalog\Model\ResourceModel\Category\Flat as CategoryFlatResource;
use Magento\Catalog\Model\ResourceModel\Category\Flat\CollectionFactory;
use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUrlRewriteDatabaseMap;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewrite as UrlRewriteResource;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
/**
* Test cases related to save category with enabled category flat.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class SaveCategoryWithEnabledFlatTest extends AbstractSaveCategoryTest
{
/**
* @var IndexerRegistry
*/
private $indexerRegistry;
/**
* @var UrlRewriteResource
*/
private $urlRewriteResource;
/**
* @var CategoryRepositoryInterface
*/
private $categoryRepository;
/**
* @var Flat
*/
private $categoryFlatIndexer;
/**
* @var CategoryFlatResource
*/
private $categoryFlatResource;
/**
* @var CollectionFactory
*/
private $categoryFlatCollectionFactory;
/**
* @var string
*/
private $createdCategoryId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->indexerRegistry = $this->_objectManager->get(IndexerRegistry::class);
$this->urlRewriteResource = $this->_objectManager->get(UrlRewriteResource::class);
$this->categoryRepository = $this->_objectManager->get(CategoryRepositoryInterface::class);
$this->categoryFlatIndexer = $this->_objectManager->get(Flat::class);
$this->categoryFlatResource = $this->_objectManager->get(CategoryFlatResource::class);
$this->categoryFlatCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
parent::tearDown();
$categoryFlatIndexer = $this->indexerRegistry->get(State::INDEXER_ID);
$categoryFlatIndexer->invalidate();
$this->categoryFlatResource->getConnection()->dropTable($this->categoryFlatResource->getMainTable());
$this->deleteAllCategoryUrlRewrites();
try {
$this->categoryRepository->deleteByIdentifier($this->createdCategoryId);
} catch (NoSuchEntityException $e) {
//Category already deleted.
}
$this->createdCategoryId = null;
}
/**
* Assert that category flat table is created and flat table contain category with created child category.
*
* @magentoDataFixture Magento/Catalog/_files/category.php
*
* @magentoConfigFixture current_store catalog/frontend/flat_catalog_category true
*
* @return void
*/
public function testAddChildCategory(): void
{
$parentCategory = $this->categoryRepository->get(333);
$postData = [
'name' => 'Custom category name',
'parent' => 333,
'is_active' => 1,
'include_in_menu' => 1,
'display_mode' => 'PRODUCTS',
'is_anchor' => true,
'use_config' => [
'available_sort_by' => 1,
'default_sort_by' => 1,
'filter_price_range' => 1,
],
];
$responseData = $this->performSaveCategoryRequest($postData);
$this->assertRequestIsSuccessfullyPerformed($responseData);
$this->createdCategoryId = $responseData['category']['entity_id'];
$this->categoryFlatIndexer->executeFull();
$this->assertTrue(
$this->categoryFlatResource->getConnection()->isTableExists($this->categoryFlatResource->getMainTable())
);
$this->assertEquals(1, $parentCategory->getChildrenCategories()->getSize());
$categoryFlatCollection = $this->categoryFlatCollectionFactory->create();
$categoryFlatCollection->addIdFilter([333, $this->createdCategoryId]);
$this->assertCount(2, $categoryFlatCollection->getItems());
/** @var Category $createdCategory */
$createdCategory = $categoryFlatCollection->getItemByColumnValue('entity_id', $this->createdCategoryId);
$this->assertEquals($parentCategory->getPath() . '/' . $this->createdCategoryId, $createdCategory->getPath());
$this->assertEquals($parentCategory->getEntityId(), $createdCategory->getParentId());
$this->assertEquals($parentCategory->getLevel() + 1, $createdCategory->getLevel());
}
/**
* Assert that category flat table is created and flat table contains category with expected data.
*
* @dataProvider enableCategoryDataProvider
*
* @magentoConfigFixture current_store catalog/frontend/flat_catalog_category true
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testSaveCategoryWithData(array $postData, array $expectedData): void
{
$responseData = $this->performSaveCategoryRequest($postData);
$this->assertRequestIsSuccessfullyPerformed($responseData);
$this->createdCategoryId = $responseData['category']['entity_id'];
$this->categoryFlatIndexer->executeFull();
$this->assertTrue(
$this->categoryFlatResource->getConnection()->isTableExists($this->categoryFlatResource->getMainTable())
);
$categoryFlatCollection = $this->categoryFlatCollectionFactory->create();
$categoryFlatCollection->addAttributeToSelect(array_keys($expectedData));
$categoryFlatCollection->addIdFilter($this->createdCategoryId);
$this->assertCount(1, $categoryFlatCollection->getItems());
/** @var Category $createdCategory */
$createdCategory = $categoryFlatCollection->getFirstItem();
foreach ($expectedData as $fieldName => $value) {
$this->assertEquals($value, $createdCategory->getDataByKey($fieldName));
}
}
/**
* Data provider with create category POST data.
*
* @return array
*/
public function enableCategoryDataProvider(): array
{
return [
'category_is_enabled' => [
[
'name' => 'Custom category name',
'parent' => 2,
'is_active' => 1,
'include_in_menu' => 1,
'display_mode' => 'PRODUCTS',
'is_anchor' => true,
'use_config' => [
'available_sort_by' => 1,
'default_sort_by' => 1,
'filter_price_range' => 1,
],
],
[
'is_active' => '1',
],
],
'category_is_disabled' => [
[
'name' => 'Custom category name',
'parent' => 2,
'is_active' => 0,
'include_in_menu' => 1,
'display_mode' => 'PRODUCTS',
'is_anchor' => true,
'use_config' => [
'available_sort_by' => 1,
'default_sort_by' => 1,
'filter_price_range' => 1,
],
],
[
'is_active' => '0'
]
],
'include_in_menu_is_enabled' => [
[
'name' => 'Custom category name',
'parent' => 2,
'is_active' => 1,
'include_in_menu' => 1,
'display_mode' => 'PRODUCTS',
'is_anchor' => true,
'use_config' => [
'available_sort_by' => 1,
'default_sort_by' => 1,
'filter_price_range' => 1,
],
],
[
'include_in_menu' => '1',
],
],
'include_in_menu_is_disabled' => [
[
'name' => 'Custom category name',
'parent' => 2,
'is_active' => 1,
'include_in_menu' => 0,
'display_mode' => 'PRODUCTS',
'is_anchor' => true,
'use_config' => [
'available_sort_by' => 1,
'default_sort_by' => 1,
'filter_price_range' => 1,
],
],
[
'include_in_menu' => '0',
],
],
];
}
/**
* Delete all URL rewrite with entity type equal to "category".
*
* @return void
*/
private function deleteAllCategoryUrlRewrites(): void
{
$deleteCondition = $this->urlRewriteResource->getConnection()
->quoteInto(UrlRewrite::ENTITY_TYPE . ' = ?', DataCategoryUrlRewriteDatabaseMap::ENTITY_TYPE);
$this->urlRewriteResource->getConnection()->delete(
$this->urlRewriteResource->getMainTable(),
$deleteCondition
);
}
}
@@ -0,0 +1,114 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Save;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Store\Model\StoreManagerInterface;
/**
* Test related to update category.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class UpdateCategoryTest extends AbstractSaveCategoryTest
{
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->categoryRepository = $this->_objectManager->get(CategoryRepositoryInterface::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
}
/**
* @dataProvider categoryDataProvider
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoDataFixture Magento/Catalog/_files/category.php
*
* @param array $postData
* @return void
*/
public function testUpdateCategoryForDefaultStoreView(array $postData): void
{
$storeId = (int)$this->storeManager->getStore('default')->getId();
$postData = array_merge($postData, ['store_id' => $storeId]);
$responseData = $this->performSaveCategoryRequest($postData);
$this->assertRequestIsSuccessfullyPerformed($responseData);
$category = $this->categoryRepository->get($postData['entity_id'], $postData['store_id']);
unset($postData['use_default']);
unset($postData['use_config']);
foreach ($postData as $key => $value) {
$this->assertEquals($value, $category->getData($key));
}
}
/**
* @return array
*/
public function categoryDataProvider(): array
{
return [
[
'post_data' => [
'entity_id' => 333,
CategoryInterface::KEY_IS_ACTIVE => '0',
CategoryInterface::KEY_INCLUDE_IN_MENU => '0',
CategoryInterface::KEY_NAME => 'Category default store',
'description' => 'Description for default store',
'landing_page' => '',
'display_mode' => Category::DM_MIXED,
CategoryInterface::KEY_AVAILABLE_SORT_BY => ['name', 'price'],
'default_sort_by' => 'price',
'filter_price_range' => 5,
'url_key' => 'default-store-category',
'meta_title' => 'meta_title default store',
'meta_keywords' => 'meta_keywords default store',
'meta_description' => 'meta_description default store',
'custom_use_parent_settings' => '0',
'custom_design' => '2',
'page_layout' => '2columns-right',
'custom_apply_to_products' => '1',
'use_default' => [
CategoryInterface::KEY_NAME => '0',
CategoryInterface::KEY_IS_ACTIVE => '0',
CategoryInterface::KEY_INCLUDE_IN_MENU => '0',
'url_key' => '0',
'meta_title' => '0',
'custom_use_parent_settings' => '0',
'custom_apply_to_products' => '0',
'description' => '0',
'landing_page' => '0',
'display_mode' => '0',
'custom_design' => '0',
'page_layout' => '0',
'meta_keywords' => '0',
'meta_description' => '0',
'custom_layout_update' => '0',
],
'use_config' => [
CategoryInterface::KEY_AVAILABLE_SORT_BY => false,
'default_sort_by' => false,
'filter_price_range' => false,
],
],
],
];
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Category\Save;
use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUrlRewriteDatabaseMap;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
/**
* Class defines url rewrite creation for category save controller
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class UrlRewriteTest extends AbstractSaveCategoryTest
{
/**
* @var UrlRewriteCollectionFactory
*/
private $urlRewriteCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->urlRewriteCollectionFactory = $this->_objectManager->get(UrlRewriteCollectionFactory::class);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @dataProvider categoryDataProvider
* @param array $data
* @return void
*/
public function testUrlRewrite(array $data): void
{
$responseData = $this->performSaveCategoryRequest($data);
$this->assertRequestIsSuccessfullyPerformed($responseData);
$categoryId = $responseData['category']['entity_id'];
$this->assertNotNull($categoryId, 'The category was not created');
$urlRewriteCollection = $this->urlRewriteCollectionFactory->create();
$urlRewriteCollection->addFieldToFilter(UrlRewrite::ENTITY_ID, ['eq' => $categoryId])
->addFieldToFilter(UrlRewrite::ENTITY_TYPE, ['eq' => DataCategoryUrlRewriteDatabaseMap::ENTITY_TYPE]);
$this->assertEquals(1, $urlRewriteCollection->getSize(), 'Wrong count of url rewrites was created');
}
/**
* @return array
*/
public function categoryDataProvider(): array
{
return [
'url_rewrite_is_created_during_category_save' => [
[
'path' => '1/2',
'name' => 'Custom Name',
'parent' => 2,
'is_active' => '0',
'include_in_menu' => '1',
'display_mode' => 'PRODUCTS',
'is_anchor' => true,
'use_config' => [
'available_sort_by' => 1,
'default_sort_by' => 1,
'filter_price_range' => 1,
],
],
],
];
}
}
@@ -0,0 +1,76 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Class contains of base logic for alert controllers tests
*/
abstract class AbstractAlertTest extends AbstractBackendController
{
/** @var ProductResource */
private $productResource;
/** @var StoreManagerInterface */
private $storeManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productResource = $this->_objectManager->get(ProductResource::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
}
/**
* Prepare request
*
* @param string $productSku
* @param string $storeCode
* @param int|null $limit
* @return void
*/
protected function prepareRequest(string $productSku, string $storeCode, ?int $limit): void
{
$productId = $this->productResource->getIdBySku($productSku);
$storeId = $this->storeManager->getStore($storeCode)->getId();
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->getRequest()->setParams(['id' => $productId, 'store' => $storeId, 'limit' => $limit]);
}
/**
* Assert alert grid records count related to provided email
*
* @param string $email
* @param int $expectedCount
* @return void
*/
protected function assertGridRecords(string $email, int $expectedCount): void
{
$content = $this->getResponse()->getContent();
$this->assertEquals(
$expectedCount,
Xpath::getElementsCountForXpath(sprintf($this->getRecordXpathTemplate(), $email), $content)
);
}
/**
* Get alert grid record xpath template
*
* @return string
*/
abstract protected function getRecordXpathTemplate(): string;
}
@@ -0,0 +1,250 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Controller\Adminhtml\Product\Action;
use Magento\Backend\Model\Session;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Helper\Product\Edit\Action\Attribute;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Framework\Message\MessageInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\UrlInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\MessageQueue\EnvironmentPreconditionException;
use Magento\TestFramework\MessageQueue\PreconditionFailedException;
use Magento\TestFramework\MessageQueue\PublisherConsumerController;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AttributeTest extends AbstractBackendController
{
/** @var PublisherConsumerController */
private $publisherConsumerController;
/**
* @var string[]
*/
private $consumers = ['product_action_attribute.update'];
protected function setUp(): void
{
parent::setUp();
$this->publisherConsumerController = $this->_objectManager->create(
PublisherConsumerController::class,
[
'consumers' => $this->consumers,
'logFilePath' => TESTS_TEMP_DIR . "/MessageQueueTestLog.txt",
'maxMessages' => null,
'appInitParams' => Bootstrap::getInstance()->getAppInitParams()
]
);
try {
$this->publisherConsumerController->startConsumers();
} catch (EnvironmentPreconditionException $e) {
$this->markTestSkipped($e->getMessage());
} catch (PreconditionFailedException $e) {
$this->fail(
$e->getMessage()
);
}
}
protected function tearDown(): void
{
$this->publisherConsumerController->stopConsumers();
parent::tearDown();
}
/**
* @covers \Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Save::execute
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation disabled
*/
public function testSaveActionRedirectsSuccessfully()
{
/** @var $session Session */
$session = $this->_objectManager->get(Session::class);
$session->setProductIds([1]);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product_action_attribute/save/store/0');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
/** @var \Magento\Backend\Model\UrlInterface $urlBuilder */
$urlBuilder = $this->_objectManager->get(UrlInterface::class);
/** @var Attribute $attributeHelper */
$attributeHelper = $this->_objectManager->get(Attribute::class);
$expectedUrl = $urlBuilder->getUrl(
'catalog/product/index',
['store' => $attributeHelper->getSelectedStoreId()]
);
$isRedirectPresent = false;
foreach ($this->getResponse()->getHeaders() as $header) {
if ($header->getFieldName() === 'Location' && strpos($header->getFieldValue(), $expectedUrl) === 0) {
$isRedirectPresent = true;
}
}
$this->assertTrue($isRedirectPresent);
}
/**
* @covers \Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Save::execute
*
* @dataProvider saveActionVisibilityAttrDataProvider
* @param array $attributes
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation disabled
*/
public function testSaveActionChangeVisibility($attributes)
{
/** @var ProductRepository $repository */
$repository = $this->_objectManager->create(ProductRepository::class);
$product = $repository->get('simple');
$product->setOrigData();
$product->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE);
$product->save();
/** @var $session Session */
$session = $this->_objectManager->get(Session::class);
$session->setProductIds([$product->getId()]);
$this->getRequest()->setParam('attributes', $attributes);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product_action_attribute/save/store/0');
/** @var \Magento\Catalog\Model\Category $category */
$categoryFactory = $this->_objectManager->get(CategoryFactory::class);
/** @var ListProduct $listProduct */
$listProduct = $this->_objectManager->get(ListProduct::class);
sleep(30); // timeout to processing queue
$this->publisherConsumerController->waitForAsynchronousResult(
function () use ($repository) {
sleep(10); // Should be refactored in the scope of MC-22947
return $repository->get(
'simple',
false,
null,
true
)->getVisibility() != Visibility::VISIBILITY_NOT_VISIBLE;
},
[]
);
$category = $categoryFactory->create()->load(2);
$layer = $listProduct->getLayer();
$layer->setCurrentCategory($category);
$productCollection = $layer->getProductCollection();
$productItem = $productCollection->getFirstItem();
$this->assertEquals($session->getProductIds(), [$productItem->getId()]);
}
/**
* @param array $attributes Request parameter.
*
* @covers \Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute\Validate::execute
*
* @dataProvider validateActionDataProvider
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @magentoDbIsolation disabled
*/
public function testValidateActionWithMassUpdate($attributes)
{
/** @var $session Session */
$session = $this->_objectManager->get(Session::class);
$session->setProductIds([1, 2]);
$this->getRequest()->setParam('attributes', $attributes);
$this->dispatch('backend/catalog/product_action_attribute/validate/store/0');
$this->assertEquals(200, $this->getResponse()->getHttpResponseCode());
$response = $this->getResponse()->getBody();
$this->assertJson($response);
$data = json_decode($response, true);
$this->assertArrayHasKey('error', $data);
$this->assertFalse($data['error']);
$this->assertCount(1, $data);
}
/**
* Data Provider for validation
*
* @return array
*/
public function validateActionDataProvider()
{
return [
[
'arguments' => [
'name' => 'Name',
'description' => 'Description',
'short_description' => 'Short Description',
'price' => '512',
'weight' => '16',
'meta_title' => 'Meta Title',
'meta_keyword' => 'Meta Keywords',
'meta_description' => 'Meta Description',
],
]
];
}
/**
* Data Provider for save with visibility attribute
*
* @return array
*/
public function saveActionVisibilityAttrDataProvider()
{
return [
['arguments' => ['visibility' => Visibility::VISIBILITY_BOTH]],
['arguments' => ['visibility' => Visibility::VISIBILITY_IN_CATALOG]]
];
}
/**
* Assert that custom layout update can not be change for existing entity.
*
* @return void
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testSaveActionCantChangeCustomLayoutUpdate(): void
{
/** @var ProductRepository $repository */
$repository = $this->_objectManager->get(ProductRepository::class);
$product = $repository->get('simple');
$product->setOrigData('custom_layout_update', 'test');
$product->setData('custom_layout_update', 'test');
$product->save();
/** @var $session Session */
$session = $this->_objectManager->get(Session::class);
$session->setProductIds([$product->getId()]);
$this->getRequest()->setParam('attributes', ['custom_layout_update' => 'test2']);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product_action_attribute/save/store/0');
$this->assertSessionMessages(
$this->equalTo(['Custom layout update text cannot be changed, only removed']),
MessageInterface::TYPE_ERROR
);
$this->assertEquals('test', $product->getData('custom_layout_update'));
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
/**
* Tests for price alert grid controller
*
* @see \Magento\Catalog\Controller\Adminhtml\Product\AlertsPriceGrid
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class AlertsPriceGridTest extends AbstractAlertTest
{
/**
* @dataProvider priceLimitProvider
*
* @magentoDataFixture Magento/ProductAlert/_files/simple_product_with_two_alerts.php
*
* @param string $email
* @param int|null $limit
* @param $expectedCount
* @return void
*/
public function testExecute(string $email, ?int $limit, $expectedCount): void
{
$this->prepareRequest('simple', 'default', $limit);
$this->dispatch('backend/catalog/product/alertsPriceGrid');
$this->assertGridRecords($email, $expectedCount);
}
/**
* @return array
*/
public function priceLimitProvider(): array
{
return [
'default_limit' => [
'email' => 'customer@example.com',
'limit' => null,
'expected_count' => 2,
],
'limit_1' => [
'email' => 'customer@example.com',
'limit' => 1,
'expected_count' => 1,
],
];
}
/**
* @inheritdoc
*/
protected function getRecordXpathTemplate(): string
{
return "//div[@id='alertPrice']//tbody/tr/td[contains(text(), '%s')]";
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
/**
* Tests for stock alert grid controller
*
* @see \Magento\Catalog\Controller\Adminhtml\Product\AlertsStockGrid
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class AlertsStockGridTest extends AbstractAlertTest
{
/**
* @dataProvider stockLimitProvider
*
* @magentoDataFixture Magento/ProductAlert/_files/simple_product_with_two_alerts.php
*
* @param string $email
* @param int|null $limit
* @param int $expectedCount
* @return void
*/
public function testExecute(string $email, ?int $limit, int $expectedCount): void
{
$this->prepareRequest('simple', 'default', $limit);
$this->dispatch('backend/catalog/product/alertsStockGrid');
$this->assertGridRecords($email, $expectedCount);
}
/**
* @return array
*/
public function stockLimitProvider(): array
{
return [
'default_limit' => [
'email' => 'customer@example.com',
'limit' => null,
'expected_count' => 2,
],
'limit_1' => [
'email' => 'customer@example.com',
'limit' => 1,
'expected_count' => 1,
],
];
}
/**
* @inheritdoc
*/
protected function getRecordXpathTemplate(): string
{
return "//div[@id='alertStock']//tbody/tr/td[contains(text(), '%s')]";
}
}
@@ -0,0 +1,83 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Delete;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Abstract delete attribute test using catalog/product_attribute/delete controller action.
*/
abstract class AbstractDeleteAttributeControllerTest extends AbstractBackendController
{
/**
* @var string
*/
protected $uri = 'backend/catalog/product_attribute/delete/attribute_id/%s';
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productAttributeRepository = $this->_objectManager->get(ProductAttributeRepositoryInterface::class);
}
/**
* Delete attribute via controller action.
*
* @param string $attributeCode
* @return void
*/
protected function dispatchDeleteAttribute(string $attributeCode): void
{
$attribute = $this->productAttributeRepository->get($attributeCode);
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->dispatch(sprintf($this->uri, $attribute->getAttributeId()));
$this->assertSessionMessages(
$this->equalTo([(string)__('You deleted the product attribute.')]),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Assert that attribute is deleted from DB.
*
* @param string $attributeCode
* @return void
*/
protected function assertAttributeIsDeleted(string $attributeCode): void
{
$this->expectExceptionObject(
new NoSuchEntityException(
__(
'The attribute with a "%1" attributeCode doesn\'t exist. Verify the attribute and try again.',
$attributeCode
)
)
);
$this->productAttributeRepository->get($attributeCode);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->markTestSkipped('AclHasAccess test is not complete');
}
}
@@ -0,0 +1,145 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Delete;
/**
* Delete catalog product attributes with input types like "media_image", "price",
* "date", "select", "multiselect", "textarea", "texteditor", "text" and "boolean".
* Attributes from Magento_Catalog and Magento_Eav modules.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class CatalogAttributesControllerTest extends AbstractDeleteAttributeControllerTest
{
/**
* Assert that attribute with input type "media_image" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_image_attribute.php
*
* @return void
*/
public function testDeleteMediaImageAttribute(): void
{
$this->dispatchDeleteAttribute('image_attribute');
$this->assertAttributeIsDeleted('image_attribute');
}
/**
* Assert that attribute with input type "price" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_decimal_attribute.php
*
* @return void
*/
public function testDeletePriceAttribute(): void
{
$this->dispatchDeleteAttribute('decimal_attribute');
$this->assertAttributeIsDeleted('decimal_attribute');
}
/**
* Assert that attribute with input type "date" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_date_attribute.php
*
* @return void
*/
public function testDeleteDateAttribute(): void
{
$this->dispatchDeleteAttribute('date_attribute');
$this->assertAttributeIsDeleted('date_attribute');
}
/**
* Assert that attribute with input type "select" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_dropdown_attribute.php
*
* @return void
*/
public function testDeleteSelectAttribute(): void
{
$this->dispatchDeleteAttribute('dropdown_attribute');
$this->assertAttributeIsDeleted('dropdown_attribute');
}
/**
* Assert that attribute with input type "multiselect" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/multiselect_attribute.php
*
* @return void
*/
public function testDeleteMultiselectAttribute(): void
{
$this->dispatchDeleteAttribute('multiselect_attribute');
$this->assertAttributeIsDeleted('multiselect_attribute');
}
/**
* Assert that attribute with input type "textarea" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_text_attribute.php
*
* @return void
*/
public function testDeleteTextareaAttribute(): void
{
$this->dispatchDeleteAttribute('text_attribute');
$this->assertAttributeIsDeleted('text_attribute');
}
/**
* Assert that attribute with input type "texteditor" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Eav/_files/product_texteditor_attribute.php
*
* @return void
*/
public function testDeleteTextEditorAttribute(): void
{
$this->dispatchDeleteAttribute('text_editor_attribute');
$this->assertAttributeIsDeleted('text_editor_attribute');
}
/**
* Assert that attribute with input type "text" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_varchar_attribute.php
*
* @return void
*/
public function testDeleteTextAttribute(): void
{
$this->dispatchDeleteAttribute('varchar_attribute');
$this->assertAttributeIsDeleted('varchar_attribute');
}
/**
* Assert that attribute with input type "boolean" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Catalog/_files/product_boolean_attribute.php
*
* @return void
*/
public function testDeleteBooleanAttribute(): void
{
$this->dispatchDeleteAttribute('boolean_attribute');
$this->assertAttributeIsDeleted('boolean_attribute');
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Delete;
use Magento\Catalog\Model\Category;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Escaper;
use Magento\Framework\Message\MessageInterface;
/**
* Error during delete attribute using catalog/product_attribute/delete controller action.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class DeleteAttributeControllerErrorTest extends AbstractDeleteAttributeControllerTest
{
/**
* @var Escaper
*/
private $escaper;
/**
* @var AttributeRepositoryInterface
*/
private $attributeRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->attributeRepository = $this->_objectManager->get(AttributeRepositoryInterface::class);
}
/**
* Try to delete attribute via controller action without attribute ID.
*
* @return void
*/
public function testDispatchWithoutAttributeId(): void
{
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->dispatch(sprintf($this->uri, ''));
$this->assertSessionMessages(
$this->equalTo([$this->escaper->escapeHtml((string)__('We can\'t find an attribute to delete.'))]),
MessageInterface::TYPE_ERROR
);
}
/**
* Try to delete category attribute via controller action.
*
* @magentoDataFixture Magento/Catalog/_files/category_attribute.php
*
* @return void
*/
public function testDispatchWithNonProductAttribute(): void
{
$categoryAttribute = $this->attributeRepository->get(
Category::ENTITY,
'test_attribute_code_666'
);
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->dispatch(sprintf($this->uri, $categoryAttribute->getAttributeId()));
$this->assertSessionMessages(
$this->equalTo([$this->escaper->escapeHtml((string)__('We can\'t delete the attribute.'))]),
MessageInterface::TYPE_ERROR
);
}
}
@@ -0,0 +1,210 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save;
use Magento\Catalog\Api\ProductAttributeOptionManagementInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Model\Entity\Attribute\AbstractAttribute;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Store\Model\Store;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Base create and assert attribute data.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class AbstractSaveAttributeTest extends AbstractBackendController
{
/** @var ProductAttributeRepositoryInterface */
protected $productAttributeRepository;
/** @var Escaper */
protected $escaper;
/** @var Json */
protected $jsonSerializer;
/** @var ProductAttributeOptionManagementInterface */
protected $productAttributeOptionManagement;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->jsonSerializer = $this->_objectManager->get(Json::class);
$this->productAttributeOptionManagement = $this->_objectManager->get(
ProductAttributeOptionManagementInterface::class
);
$this->productAttributeRepository = $this->_objectManager->get(ProductAttributeRepositoryInterface::class);
}
/**
* Create attribute via save product attribute controller and assert that attribute
* created correctly.
*
* @param array $attributeData
* @param array $checkArray
* @return void
*/
protected function createAttributeUsingDataAndAssert(array $attributeData, array $checkArray): void
{
$attributeCode = $this->getAttributeCodeFromAttributeData($attributeData);
if (isset($attributeData['serialized_options_arr'])) {
$attributeData['serialized_options'] = $this->serializeOptions($attributeData['serialized_options_arr']);
}
$this->dispatchAttributeSave($attributeData);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the product attribute.')]),
MessageInterface::TYPE_SUCCESS
);
try {
$attribute = $this->productAttributeRepository->get($attributeCode);
$this->assertAttributeData($attribute, $attributeData, $checkArray);
$this->productAttributeRepository->delete($attribute);
} catch (NoSuchEntityException $e) {
$this->fail("Attribute with code {$attributeCode} was not created.");
}
}
/**
* Create attribute via save product attribute controller and assert that we have error during save process.
*
* @param array $attributeData
* @param string $errorMessage
* @return void
*/
protected function createAttributeUsingDataWithErrorAndAssert(array $attributeData, string $errorMessage): void
{
if (isset($attributeData['serialized_options_arr'])
&& count($attributeData['serialized_options_arr'])
) {
$attributeData['serialized_options'] = $this->serializeOptions($attributeData['serialized_options_arr']);
}
$this->dispatchAttributeSave($attributeData);
$this->assertSessionMessages(
$this->equalTo([$this->escaper->escapeHtml($errorMessage)]),
MessageInterface::TYPE_ERROR
);
$attributeCode = $this->getAttributeCodeFromAttributeData($attributeData);
try {
$attribute = $this->productAttributeRepository->get($attributeCode);
$this->productAttributeRepository->delete($attribute);
} catch (NoSuchEntityException $e) {
//Attribute already deleted.
}
}
/**
* Assert that options was created.
*
* @param AttributeInterface $attribute
* @param array $optionsData
* @return void
*/
protected function assertAttributeOptions(AttributeInterface $attribute, array $optionsData): void
{
$attributeOptions = $this->productAttributeOptionManagement->getItems($attribute->getAttributeCode());
foreach ($optionsData as $optionData) {
$valueItemArr = $optionData['option']['value'];
$optionLabel = reset($valueItemArr)[1];
$optionFounded = false;
foreach ($attributeOptions as $attributeOption) {
if ($attributeOption->getLabel() === $optionLabel) {
$optionFounded = true;
break;
}
}
$this->assertTrue($optionFounded);
}
}
/**
* Compare attribute data with data which we use for create attribute.
*
* @param AttributeInterface|AbstractAttribute $attribute
* @param array $attributeData
* @param array $checkData
* @return void
*/
private function assertAttributeData(
AttributeInterface $attribute,
array $attributeData,
array $checkData
): void {
$frontendInput = $checkData['frontend_input'] ?? $attributeData['frontend_input'];
$this->assertEquals('Test attribute name', $attribute->getDefaultFrontendLabel());
$this->assertEquals($frontendInput, $attribute->getFrontendInput());
if (isset($attributeData['serialized_options'])) {
$this->assertAttributeOptions($attribute, $attributeData['serialized_options_arr']);
}
//Additional asserts
foreach ($checkData as $valueKey => $value) {
$this->assertEquals($value, $attribute->getDataUsingMethod($valueKey));
}
}
/**
* Get attribute code from attribute data. If attribute code doesn't exist in
* attribute data get attribute using default frontend label.
*
* @param array $attributeData
* @return string
*/
private function getAttributeCodeFromAttributeData(array $attributeData): string
{
$attributeCode = $attributeData['attribute_code'] ?? null;
if (!$attributeCode) {
$attributeCode = strtolower(
str_replace(' ', '_', $attributeData['frontend_label'][Store::DEFAULT_STORE_ID])
);
}
return $attributeCode;
}
/**
* Create attribute using catalog/product_attribute/save action.
*
* @param array $attributeData
* @return void
*/
private function dispatchAttributeSave(array $attributeData): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($attributeData);
$this->dispatch('backend/catalog/product_attribute/save');
}
/**
* Create serialized options string.
*
* @param array $optionsArr
* @return string
*/
private function serializeOptions(array $optionsArr): string
{
$resultArr = [];
foreach ($optionsArr as $option) {
$resultArr[] = http_build_query($option);
}
return $this->jsonSerializer->serialize($resultArr);
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\InputType;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\AbstractSaveAttributeTest;
/**
* Test cases related to create attribute with input type price.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class DecimalTest extends AbstractSaveAttributeTest
{
/**
* Test create attribute and compare attribute data and input data.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\Decimal::getAttributeDataWithCheckArray
*
* @param array $attributePostData
* @param array $checkArray
* @return void
*/
public function testCreateAttribute(array $attributePostData, array $checkArray): void
{
$this->createAttributeUsingDataAndAssert($attributePostData, $checkArray);
}
/**
* Test create attribute with error.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\Decimal::getAttributeDataWithErrorMessage
*
* @param array $attributePostData
* @param string $errorMessage
* @return void
*/
public function testCreateAttributeWithError(array $attributePostData, string $errorMessage): void
{
$this->createAttributeUsingDataWithErrorAndAssert($attributePostData, $errorMessage);
}
}
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\InputType;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\AbstractSaveAttributeTest;
/**
* Test cases related to create attribute with input type media image.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class MediaImageTest extends AbstractSaveAttributeTest
{
/**
* Test create attribute and compare attribute data and input data.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\MediaImage::getAttributeDataWithCheckArray
*
* @param array $attributePostData
* @param array $checkArray
* @return void
*/
public function testCreateAttribute(array $attributePostData, array $checkArray): void
{
$this->createAttributeUsingDataAndAssert($attributePostData, $checkArray);
}
/**
* Test create attribute with error.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\MediaImage::getAttributeDataWithErrorMessage
*
* @param array $attributePostData
* @param string $errorMessage
* @return void
*/
public function testCreateAttributeWithError(array $attributePostData, string $errorMessage): void
{
$this->createAttributeUsingDataWithErrorAndAssert($attributePostData, $errorMessage);
}
}
@@ -0,0 +1,472 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Update;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Attribute as AttributeResource;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option as OptionResource;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory as OptionCollectionFactory;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Escaper;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Eav\Model\GetAttributeGroupByName;
use Magento\TestFramework\Eav\Model\GetAttributeSetByName;
use Magento\TestFramework\Eav\Model\ResourceModel\GetEntityIdByAttributeId;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Base update and assert attribute data.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
abstract class AbstractUpdateAttributeTest extends AbstractBackendController
{
/** @var ProductAttributeRepositoryInterface */
protected $productAttributeRepository;
/** @var Escaper */
protected $escaper;
/** @var Json */
protected $jsonSerializer;
/** @var GetAttributeSetByName */
private $getAttributeSetByName;
/** @var GetAttributeGroupByName */
private $getAttributeGroupByName;
/** @var GetEntityIdByAttributeId */
private $getEntityIdByAttributeId;
/** @var StoreManagerInterface */
private $storeManager;
/** @var OptionCollectionFactory */
private $optionCollectionFactory;
/** @var OptionResource */
private $attributeOptionResource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->jsonSerializer = $this->_objectManager->get(Json::class);
$this->productAttributeRepository = $this->_objectManager->get(ProductAttributeRepositoryInterface::class);
$this->getAttributeSetByName = $this->_objectManager->get(GetAttributeSetByName::class);
$this->getAttributeGroupByName = $this->_objectManager->get(GetAttributeGroupByName::class);
$this->getEntityIdByAttributeId = $this->_objectManager->get(GetEntityIdByAttributeId::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->optionCollectionFactory = $this->_objectManager->get(OptionCollectionFactory::class);
$this->attributeOptionResource = $this->_objectManager->get(OptionResource::class);
}
/**
* Updates attribute frontend labels on stores for a given attribute type.
*
* @param string $attributeCode
* @param array $postData
* @param array $expectedData
* @return void
*/
protected function processUpdateFrontendLabelOnStores(
string $attributeCode,
array $postData,
array $expectedData
): void {
$this->setAttributeStorelabels($attributeCode);
if (is_array($postData['frontend_label'])) {
$postData['frontend_label'] = $this->prepareStoresData($postData['frontend_label']);
}
$expectedData['store_labels'] = $this->prepareStoresData($expectedData['store_labels']);
$this->_objectManager->removeSharedInstance(AttributeResource::class);
$this->updateAttributeUsingData($attributeCode, $postData);
$this->assertUpdateAttributeProcess($attributeCode, $postData, $expectedData);
}
/**
* Updates attribute options on stores for a given attribute type.
*
* @param string $attributeCode
* @param array $postData
* @return void
*/
protected function processUpdateOptionsOnStores(string $attributeCode, array $postData): void
{
$optionsData = $this->prepareStoreOptionsArray($attributeCode, $postData['options_array']);
$optionsPostData = $this->prepareStoreOptionsPostData($optionsData);
$postData['serialized_options'] = $this->serializeOptions($optionsPostData);
$expectedData = $this->prepareStoreOptionsExpectedData($optionsData);
$this->_objectManager->removeSharedInstance(AttributeResource::class);
$this->updateAttributeUsingData($attributeCode, $postData);
$this->assertUpdateAttributeProcess($attributeCode, $postData, $expectedData);
}
/**
* Prepare an array of values by store - replace store code with store identifier.
*
* @param array $storesData
* @return array
*/
protected function prepareStoresData(array $storesData): array
{
$storeIdsData = [];
foreach ($storesData as $storeId => $label) {
$store = $this->storeManager->getStore($storeId);
$storeIdsData[$store->getId()] = $label;
}
return $storeIdsData;
}
/**
* Update attribute via save product attribute controller.
*
* @param string $attributeCode
* @param array $postData
* @return void
*/
protected function updateAttributeUsingData(string $attributeCode, array $postData): void
{
$attributeId = $postData['attribute_id'] ?? $this->productAttributeRepository->get($attributeCode)->getId();
$this->dispatchAttributeSave($postData, (int)$attributeId);
}
/**
* Replace the store code with an identifier in the array of option values
*
* @param array $optionsArray
* @return array
*/
protected function replaceStoreCodeWithId(array $optionsArray): array
{
foreach ($optionsArray as $key => $option) {
$optionsArray[$key]['value'] = $this->prepareStoresData($option['value']);
}
return $optionsArray;
}
/**
* Prepare an array of attribute option values that will be saved.
*
* @param string $attributeCode
* @param array $optionsArray
* @return array
*/
protected function prepareStoreOptionsArray(string $attributeCode, array $optionsArray): array
{
$attribute = $this->productAttributeRepository->get($attributeCode);
$replacedOptionsArray = $this->replaceStoreCodeWithId($optionsArray);
$actualOptionsData = $this->getActualOptionsData($attribute->getId());
$labeledOptionsData = [];
$optionLabelIds = [];
$i = 1;
foreach ($actualOptionsData as $optionId => $optionData) {
$optionLabelIds['option_' . $i] = $optionId;
$labeledOptionsData['option_' . $i] = $optionData;
$i++;
}
$combineOptionsData = array_replace_recursive($labeledOptionsData, $replacedOptionsArray);
$optionsData = [];
foreach ($optionLabelIds as $optionLabel => $optionId) {
$optionsData[$optionId] = $combineOptionsData[$optionLabel];
}
return $optionsData;
}
/**
* Get actual attribute options data.
*
* @param string $attributeId
* @return array
*/
protected function getActualOptionsData(string $attributeId): array
{
$attributeOptions = $this->getAttributeOptions($attributeId);
$actualOptionsData = [];
foreach ($attributeOptions as $optionId => $option) {
$actualOptionsData[$optionId] = [
'order' => $option->getSortOrder(),
'value' => $this->getAttributeOptionValues($optionId),
];
}
return $actualOptionsData;
}
/**
* Prepare an array of attribute option values for sending via post parameters.
*
* @param array $optionsData
* @return array
*/
protected function prepareStoreOptionsPostData(array $optionsData): array
{
$optionsPostData = [];
foreach ($optionsData as $optionId => $option) {
$optionsPostData[$optionId]['option'] = [
'order' => [
$optionId => $option['order'],
],
'value' => [
$optionId => $option['value'],
],
'delete' => [
$optionId => $option['delete'] ?? '',
],
];
if (isset($option['default'])) {
$optionsPostData[$optionId]['default'][] = $optionId;
}
}
return $optionsPostData;
}
/**
* Prepare an array of attribute option values for verification after saving the attribute.
*
* @param array $optionsData
* @return array
*/
protected function prepareStoreOptionsExpectedData(array $optionsData): array
{
$optionsArray = [];
$defaultValue = '';
foreach ($optionsData as $optionId => $option) {
if (!empty($option['delete'])) {
continue;
}
$optionsArray[$optionId] = [
'order' => $option['order'],
'value' => $option['value'],
];
if (isset($option['default'])) {
$defaultValue = $optionId;
}
}
return [
'options_array' => $optionsArray,
'default_value' => $defaultValue,
];
}
/**
* Assert that attribute update correctly.
*
* @param string $attributeCode
* @param array $postData
* @param array $expectedData
* @return void
*/
protected function assertUpdateAttributeProcess(string $attributeCode, array $postData, array $expectedData): void
{
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the product attribute.')]),
MessageInterface::TYPE_SUCCESS
);
$updatedAttribute = $this->productAttributeRepository->get($attributeCode);
if (isset($postData['new_attribute_set_name'])) {
$this->assertUpdateAttributeSet($updatedAttribute, $postData);
} elseif (isset($postData['options_array'])) {
$this->assertUpdateAttributeOptions($updatedAttribute, $expectedData['options_array']);
unset($expectedData['options_array']);
$this->assertUpdateAttributeData($updatedAttribute, $expectedData);
} else {
$this->assertUpdateAttributeData($updatedAttribute, $expectedData);
}
}
/**
* Check that attribute property values match expected values.
*
* @param ProductAttributeInterface $attribute
* @param array $expectedData
* @return void
*/
protected function assertUpdateAttributeData(
ProductAttributeInterface $attribute,
array $expectedData
): void {
foreach ($expectedData as $key => $expectedValue) {
$this->assertEquals(
$expectedValue,
$attribute->getDataUsingMethod($key),
"Invalid expected value for $key field."
);
}
}
/**
* Checks that appropriate error message appears.
*
* @param string $errorMessage
* @return void
*/
protected function assertErrorSessionMessages(string $errorMessage): void
{
$this->assertSessionMessages(
$this->equalTo([$this->escaper->escapeHtml($errorMessage)]),
MessageInterface::TYPE_ERROR
);
}
/**
* Create or update attribute using catalog/product_attribute/save action.
*
* @param array $attributeData
* @param int|null $attributeId
* @return void
*/
private function dispatchAttributeSave(array $attributeData, ?int $attributeId = null): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($attributeData);
if ($attributeId) {
$this->getRequest()->setParam('attribute_id', $attributeId);
}
$this->dispatch('backend/catalog/product_attribute/save');
}
/**
* Create serialized options string.
*
* @param array $optionsArr
* @return string
*/
private function serializeOptions(array $optionsArr): string
{
$resultArr = [];
foreach ($optionsArr as $option) {
$resultArr[] = http_build_query($option);
}
return $this->jsonSerializer->serialize($resultArr);
}
/**
* Set default values of attribute store labels and save.
*
* @param string $attributeCode
* @return void
*/
private function setAttributeStoreLabels(string $attributeCode): void
{
$stores = $this->storeManager->getStores();
$storeLabels = [];
foreach ($stores as $storeId => $store) {
$storeLabels[$storeId] = $store->getName();
}
$attribute = $this->productAttributeRepository->get($attributeCode);
$attribute->setStoreLabels($storeLabels);
$this->productAttributeRepository->save($attribute);
}
/**
* Check that the attribute update was successful after adding it to the
* new attribute set and new attribute group.
*
* @param ProductAttributeInterface|Attribute $attribute
* @param array $postData
* @return void
*/
private function assertUpdateAttributeSet(
ProductAttributeInterface $attribute,
array $postData
): void {
$attributeSet = $this->getAttributeSetByName->execute($postData['new_attribute_set_name']);
$this->assertNotNull(
$attributeSet,
'The attribute set ' . $postData['new_attribute_set_name'] . 'was not created'
);
$attributeGroup = $this->getAttributeGroupByName->execute((int)$attributeSet->getId(), $postData['groupName']);
$this->assertNotNull(
$attributeGroup,
'The attribute group ' . $postData['groupName'] . 'was not created'
);
$entityAttributeId = $this->getEntityIdByAttributeId->execute(
(int)$attributeSet->getId(),
(int)$attribute->getId(),
(int)$attributeGroup->getId()
);
$this->assertNotNull(
$entityAttributeId,
'The attribute set and attribute group for the current attribute have not been updated.'
);
}
/**
* Check that attribute options are saved correctly.
*
* @param ProductAttributeInterface|Attribute $attribute
* @param array $expectedData
* @return void
*/
private function assertUpdateAttributeOptions(
ProductAttributeInterface $attribute,
array $expectedData
): void {
$actualOptionsData = $this->getActualOptionsData($attribute->getId());
$this->assertEquals($expectedData, $actualOptionsData, 'Expected attribute options does not match.');
}
/**
* Get attribute options by attribute id and store id.
*
* @param string $attributeId
* @param int|null $storeId
* @return array
*/
private function getAttributeOptions(string $attributeId, ?int $storeId = null): array
{
$attributeOptionCollection = $this->optionCollectionFactory->create();
$attributeOptionCollection->setAttributeFilter($attributeId);
$attributeOptionCollection->setStoreFilter($storeId);
return $attributeOptionCollection->getItems();
}
/**
* Get attribute option values by option id.
*
* @param int $optionId
* @return array
*/
private function getAttributeOptionValues(int $optionId): array
{
$connection = $this->attributeOptionResource->getConnection();
$select = $connection->select()
->from(
['main_table' => $this->attributeOptionResource->getTable('eav_attribute_option_value')],
['store_id','value']
)
->where('main_table.option_id = ?', $optionId);
return $connection->fetchPairs($select);
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Update\InputType;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Update\AbstractUpdateAttributeTest;
/**
* Test cases related to update attribute with input type price.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class DecimalTest extends AbstractUpdateAttributeTest
{
/**
* Test update attribute.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\Decimal::getUpdateProvider
* @magentoDataFixture Magento/Catalog/_files/product_decimal_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateAttribute(array $postData, array $expectedData): void
{
$this->updateAttributeUsingData('decimal_attribute', $postData);
$this->assertUpdateAttributeProcess('decimal_attribute', $postData, $expectedData);
}
/**
* Test update attribute with error.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\Decimal::getUpdateProviderWithErrorMessage
* @magentoDataFixture Magento/Catalog/_files/product_decimal_attribute.php
*
* @param array $postData
* @param string $errorMessage
* @return void
*/
public function testUpdateAttributeWithError(array $postData, string $errorMessage): void
{
$this->updateAttributeUsingData('decimal_attribute', $postData);
$this->assertErrorSessionMessages($errorMessage);
}
/**
* Test update attribute frontend labels on stores.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\Decimal::getUpdateFrontendLabelsProvider
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/Catalog/_files/product_decimal_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateFrontendLabelOnStores(array $postData, array $expectedData): void
{
$this->processUpdateFrontendLabelOnStores('decimal_attribute', $postData, $expectedData);
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute\Update\InputType;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Update\AbstractUpdateAttributeTest;
/**
* Test cases related to update attribute with input type media image.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class MediaImageTest extends AbstractUpdateAttributeTest
{
/**
* Test update attribute.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\MediaImage::getUpdateProvider
* @magentoDataFixture Magento/Catalog/_files/product_image_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateAttribute(array $postData, array $expectedData): void
{
$this->updateAttributeUsingData('image_attribute', $postData);
$this->assertUpdateAttributeProcess('image_attribute', $postData, $expectedData);
}
/**
* Test update attribute with error.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\MediaImage::getUpdateProviderWithErrorMessage
* @magentoDataFixture Magento/Catalog/_files/product_image_attribute.php
*
* @param array $postData
* @param string $errorMessage
* @return void
*/
public function testUpdateAttributeWithError(array $postData, string $errorMessage): void
{
$this->updateAttributeUsingData('image_attribute', $postData);
$this->assertErrorSessionMessages($errorMessage);
}
/**
* Test update attribute frontend labels on stores.
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Attribute\DataProvider\MediaImage::getUpdateFrontendLabelsProvider
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/Catalog/_files/product_image_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateFrontendLabelOnStores(array $postData, array $expectedData): void
{
$this->processUpdateFrontendLabelOnStores('image_attribute', $postData, $expectedData);
}
}
@@ -0,0 +1,373 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Controller\Adminhtml\Product;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\App\Request\Http as HttpRequest;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AttributeTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @return void
*/
public function testWrongFrontendInput()
{
$postData = array_merge(
$this->_getAttributeData(),
[
'attribute_id' => 100500,
'frontend_input' => 'some_input',
]
);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'catalog/product_attribute/edit/attribute_id/100500',
$this->getResponse()->getHeader('Location')->getFieldValue()
);
/** @var \Magento\Framework\Message\Collection $messages */
$messages = $this->_objectManager->create(\Magento\Framework\Message\ManagerInterface::class)->getMessages();
$this->assertEquals(1, $messages->getCountByType('error'));
$message = $messages->getItemsByType('error')[0];
$this->assertEquals('Input type "some_input" not found in the input types list.', $message->getText());
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/attribute_system_popup.php
* @return void
*/
public function testWithPopup()
{
$postData = $this->_getAttributeData() + [
'attribute_id' => 5,
'popup' => 'true',
'new_attribute_set_name' => 'new_attribute_set',
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'catalog/product/addAttribute/attribute/5',
$this->getResponse()->getHeader('Location')->getFieldValue()
);
/** @var \Magento\Framework\Message\Collection $messages */
$messages = $this->_objectManager->create(\Magento\Framework\Message\ManagerInterface::class)->getMessages();
$this->assertEquals(1, $messages->getCountByType('success'));
$message = $messages->getItemsByType('success')[0];
$this->assertEquals('You saved the product attribute.', $message->getText());
}
/**
* @return void
*/
public function testWithExceptionWhenSaveAttribute()
{
$postData = $this->_getAttributeData() + ['attribute_id' => 0, 'frontend_input' => 'boolean'];
$this->getRequest()->setPostValue($postData);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'catalog/product_attribute/edit/attribute_id/0',
$this->getResponse()->getHeader('Location')->getFieldValue()
);
/** @var \Magento\Framework\Message\Collection $messages */
$messages = $this->_objectManager->create(\Magento\Framework\Message\ManagerInterface::class)->getMessages();
$this->assertEquals(1, $messages->getCountByType('error'));
}
/**
* @return void
*/
public function testWrongAttributeId()
{
$postData = $this->_getAttributeData() + ['attribute_id' => 100500];
$this->getRequest()->setPostValue($postData);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'catalog/product_attribute/index',
$this->getResponse()->getHeader('Location')->getFieldValue()
);
/** @var \Magento\Framework\Message\Collection $messages */
$messages = $this->_objectManager->create(\Magento\Framework\Message\ManagerInterface::class)->getMessages();
$this->assertEquals(1, $messages->getCountByType('error'));
/** @var \Magento\Framework\Message\Error $message */
$message = $messages->getItemsByType('error')[0];
$this->assertEquals('This attribute no longer exists.', $message->getText());
}
/**
* @return void
*/
public function testAttributeWithoutId()
{
$postData = $this->_getAttributeData() + [
'attribute_code' => uniqid('attribute_'),
'set' => 4,
'frontend_input' => 'boolean',
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'catalog/product_attribute/index',
$this->getResponse()->getHeader('Location')->getFieldValue()
);
/** @var \Magento\Framework\Message\Collection $messages */
$messages = $this->_objectManager->create(\Magento\Framework\Message\ManagerInterface::class)->getMessages();
$this->assertEquals(1, $messages->getCountByType('success'));
/** @var \Magento\Framework\Message\Success $message */
$message = $messages->getItemsByType('success')[0];
$this->assertEquals('You saved the product attribute.', $message->getText());
}
/**
* @return void
*/
public function testAttributeWithoutEntityTypeId()
{
$postData = $this->_getAttributeData() + ['attribute_id' => '2', 'new_attribute_set_name' => ' '];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals(302, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'catalog/product_attribute/index',
$this->getResponse()->getHeader('Location')->getFieldValue()
);
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/attribute_system.php
*/
public function testSaveActionApplyToDataSystemAttribute()
{
$postData = $this->_getAttributeData() + ['attribute_id' => '2'];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$model = $this->_objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$model->load($postData['attribute_id']);
$this->assertNull($model->getData('apply_to'));
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/attribute_user_defined.php
*/
public function testSaveActionApplyToDataUserDefinedAttribute()
{
$postData = $this->_getAttributeData() + ['attribute_id' => '1'];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $model */
$model = $this->_objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$model->load($postData['attribute_id']);
$this->assertEquals('simple', $model->getData('apply_to'));
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/attribute_system_with_applyto_data.php
*/
public function testSaveActionApplyToData()
{
$postData = $this->_getAttributeData() + ['attribute_id' => '3'];
unset($postData['apply_to']);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$model = $this->_objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$model->load($postData['attribute_id']);
$this->assertEquals(['simple'], $model->getApplyTo());
}
/**
* @magentoDataFixture Magento/Translation/_files/db_translate_admin_store.php
* @magentoDataFixture Magento/Catalog/controllers/_files/attribute_user_defined.php
* @magentoAppIsolation enabled
*/
public function testSaveActionCleanAttributeLabelCache()
{
/** @var \Magento\Translation\Model\ResourceModel\StringUtils $string */
$string = $this->_objectManager->create(\Magento\Translation\Model\ResourceModel\StringUtils::class);
$this->assertEquals('predefined string translation', $this->_translate('string to translate'));
$string->saveTranslate('string to translate', 'new string translation');
$postData = $this->_getAttributeData() + ['attribute_id' => 1];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product_attribute/save');
$this->assertEquals('new string translation', $this->_translate('string to translate'));
}
/**
* Get attribute data preset.
*
* @return array
*/
private function getLargeOptionsSetAttributeData()
{
return [
'frontend_label' => [
0 => 'testdrop1',
1 => '',
2 => '',
],
'frontend_input' => 'select',
'is_required' => '0',
'update_product_preview_image' => '0',
'use_product_image_for_swatch' => '0',
'visual_swatch_validation' => '',
'visual_swatch_validation_unique' => '',
'text_swatch_validation' => '',
'text_swatch_validation_unique' => '',
'attribute_code' => 'test_many_options',
'is_global' => '0',
'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_filterable' => '0',
'is_filterable_in_search' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'swatch_input_type' => 'dropdown',
];
}
/**
* Test attribute saving with large amount of options exceeding maximum allowed by max_input_vars limit.
* @return void
*/
public function testLargeOptionsDataSet()
{
$maxInputVars = ini_get('max_input_vars');
// Each option is at least 4 variables array (order, admin value, first store view value, delete flag).
// Set options count to exceed max_input_vars by 100 options (400 variables).
$optionsCount = floor($maxInputVars / 4) + 100;
$attributeData = $this->getLargeOptionsSetAttributeData();
$optionsData = [];
$expectedOptionsLabels = [];
for ($i = 0; $i < $optionsCount; $i++) {
$expectedOptionLabelOnStoreView = 'value_' . $i . '_store_1';
$expectedOptionsLabels[$i+1] = $expectedOptionLabelOnStoreView;
$optionId = 'option_' . $i;
$optionRowData = [];
$optionRowData['option']['order'][$optionId] = $i + 1;
$optionRowData['option']['value'][$optionId][0] = 'value_' . $i . '_admin';
$optionRowData['option']['value'][$optionId][1] = $expectedOptionLabelOnStoreView;
$optionRowData['option']['delete'][$optionId] = '';
$optionsData[] = http_build_query($optionRowData);
}
$attributeData['serialized_options'] = json_encode($optionsData);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($attributeData);
$this->dispatch('backend/catalog/product_attribute/save');
$entityTypeId = $this->_objectManager->create(
\Magento\Eav\Model\Entity::class
)->setType(
\Magento\Catalog\Model\Product::ENTITY
)->getTypeId();
/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$attribute = $this->_objectManager->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
)->setEntityTypeId(
$entityTypeId
);
try {
$attribute->loadByCode($entityTypeId, 'test_many_options');
$options = $attribute->getOptions();
// assert that all options are saved without truncation
$this->assertEquals(
$optionsCount + 1,
count($options),
'Expected options count does not match (regarding first empty option for non-required attribute)'
);
foreach ($expectedOptionsLabels as $optionOrderNum => $label) {
$this->assertEquals(
$label,
$options[$optionOrderNum]->getLabel(),
"Label for option #{$optionOrderNum} does not match expected."
);
}
} catch (LocalizedException $e) {
$this->fail('Test failed with exception on attribute model load: ' . $e);
}
}
/**
* Return translation for a string literal belonging to backend area
*
* @param string $string
* @return string
*/
protected function _translate($string)
{
// emulate admin store and design
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\DesignInterface::class
)->setDesignTheme(
1
);
/** @var \Magento\Framework\TranslateInterface $translate */
$translate = $this->_objectManager->get(\Magento\Framework\TranslateInterface::class);
$translate->loadData(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, true);
return __($string);
}
/**
* Get attribute data for post
*
* @return array
*/
protected function _getAttributeData()
{
return [
'is_global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
'default_value_text' => '0',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '0',
'is_required' => '1',
'frontend_class' => '',
'frontend_input' => 'select',
'is_searchable' => '0',
'is_visible_in_advanced_search' => '0',
'is_comparable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '0',
'is_visible_on_front' => '0',
'used_in_product_listing' => '1',
'used_for_sort_by' => '0',
'apply_to' => ['simple'],
'frontend_label' => [\Magento\Store\Model\Store::DEFAULT_STORE_ID => 'string to translate'],
];
}
}
@@ -0,0 +1,122 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test class for Product duplicate action
*
* @magentoAppArea adminhtml
* @see \Magento\Catalog\Controller\Adminhtml\Product\Duplicate
*/
class DuplicateTest extends AbstractBackendController
{
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var string
*/
private $duplicatedProductSku;
/**
* @var array
*/
private $dataKeys = ['name', 'description', 'short_description', 'price', 'weight', 'attribute_set_id'];
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
try {
$this->productRepository->deleteById($this->duplicatedProductSku);
} catch (NoSuchEntityException $e) {
// product already deleted
}
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*
* @return void
*/
public function testDuplicateAction(): void
{
$product = $this->productRepository->get('simple');
$this->getRequest()->setMethod(HttpRequest::METHOD_GET);
$this->getRequest()->setParams(
[
'id' => $product->getId(),
'attribute_set_id' => $product->getAttributeSetId(),
]
);
$this->dispatch('backend/catalog/product/duplicate');
$this->assertSessionMessages(
$this->containsEqual((string)__('You duplicated the product.')),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('catalog/product/edit/'));
$productId = $this->getIdFromRedirectedUrl();
$this->assertNotEmpty($productId, 'Id not found');
$duplicatedProduct = $this->productRepository->getById((int)$productId);
$this->duplicatedProductSku = $duplicatedProduct->getSku();
$this->assertProductDuplicated($product, $duplicatedProduct);
}
/**
* Get id value from redirected url
*
* @return string
*/
private function getIdFromRedirectedUrl(): string
{
$url = $this->getResponse()
->getHeader('Location')
->getFieldValue();
$pattern = '!/id/(.*?)/!';
$result = preg_match($pattern, $url, $matches);
return $result ? $matches[1] : '';
}
/**
* Checks that duplicate product was created from the first product
*
* @param ProductInterface $product
* @param ProductInterface $duplicatedProduct
* @return void
*/
private function assertProductDuplicated(ProductInterface $product, ProductInterface $duplicatedProduct): void
{
foreach ($this->dataKeys as $key) {
$this->assertEquals($product->getData($key), $duplicatedProduct->getData($key));
}
}
}
@@ -0,0 +1,291 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Gallery;
use Magento\Catalog\Model\Product\Media\Config;
use Magento\Framework\App\Filesystem\DirectoryList as AppDirectoryList;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Provide tests for admin product upload image action.
*
* @magentoAppArea adminhtml
*/
class UploadTest extends AbstractBackendController
{
/**
* @var string
*/
protected $resource = 'Magento_Catalog::products';
/**
* @var string
*/
protected $uri = 'backend/catalog/product_gallery/upload';
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Json
*/
private $serializer;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var Config
*/
private $config;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->httpMethod = HttpRequest::METHOD_POST;
$this->filesystem = $this->_objectManager->get(Filesystem::class);
$this->serializer = $this->_objectManager->get(Json::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(AppDirectoryList::MEDIA);
$this->config = $this->_objectManager->get(Config::class);
}
/**
* Test upload image on admin product page.
*
* @dataProvider uploadActionDataProvider
* @magentoDbIsolation enabled
* @param array $file
* @param array $expectation
* @return void
*/
public function testUploadAction(array $file, array $expectation): void
{
$this->copyFileToSysTmpDir($file);
$this->getRequest()->setMethod($this->httpMethod);
$this->dispatch($this->uri);
$jsonBody = $this->serializer->unserialize($this->getResponse()->getBody());
$this->assertEquals($jsonBody['name'], $expectation['name']);
$this->assertEquals($jsonBody['type'], $expectation['type']);
$this->assertEquals($jsonBody['file'], $expectation['file']);
$this->assertEquals($jsonBody['url'], $expectation['url']);
$this->assertArrayNotHasKey('error', $jsonBody);
$this->assertArrayNotHasKey('errorcode', $jsonBody);
$this->assertTrue($this->mediaDirectory->isExist(
$this->getFileAbsolutePath($expectation['tmp_media_path'])
));
}
/**
* @return array
*/
public function uploadActionDataProvider(): array
{
return [
'upload_image_with_type_jpg' => [
'file' => [
'name' => 'magento_image.jpg',
'type' => 'image/jpeg',
'current_path' => '/../../../../_files',
],
'expectation' => [
'name' => 'magento_image.jpg',
'type' => 'image/jpeg',
'file' => '/m/a/magento_image.jpg.tmp',
'url' => 'http://localhost/media/tmp/catalog/product/m/a/magento_image.jpg',
'tmp_media_path' => '/m/a/magento_image.jpg',
],
],
'upload_image_with_type_png' => [
'file' => [
'name' => 'product_image.png',
'type' => 'image/png',
'current_path' => '/../../../../controllers/_files',
],
'expectation' => [
'name' => 'product_image.png',
'type' => 'image/png',
'file' => '/p/r/product_image.png.tmp',
'url' => 'http://localhost/media/tmp/catalog/product/p/r/product_image.png',
'tmp_media_path' => '/p/r/product_image.png',
],
],
'upload_image_with_type_gif' => [
'file' => [
'name' => 'magento_image.gif',
'type' => 'image/gif',
'current_path' => '/../../../../_files',
],
'expectation' => [
'name' => 'magento_image.gif',
'type' => 'image/gif',
'file' => '/m/a/magento_image.gif.tmp',
'url' => 'http://localhost/media/tmp/catalog/product/m/a/magento_image.gif',
'tmp_media_path' => '/m/a/magento_image.gif',
],
],
];
}
/**
* Test upload image on admin product page.
*
* @dataProvider uploadActionWithErrorsDataProvider
* @magentoDbIsolation enabled
* @param array $file
* @param array $expectation
* @return void
*/
public function testUploadActionWithErrors(array $file, array $expectation): void
{
if (!empty($file['create_file'])) {
$this->createFileInSysTmpDir($file['name']);
} elseif (!empty($file['copy_file'])) {
$this->copyFileToSysTmpDir($file);
}
$this->getRequest()->setMethod($this->httpMethod);
$this->dispatch($this->uri);
$jsonBody = $this->serializer->unserialize($this->getResponse()->getBody());
$this->assertEquals($expectation['message'], $jsonBody['error']);
$this->assertEquals($expectation['errorcode'], $jsonBody['errorcode']);
if (!empty($expectation['tmp_media_path'])) {
$this->assertFileDoesNotExist(
$this->getFileAbsolutePath($expectation['tmp_media_path'])
);
}
}
/**
* @return array
*/
public function uploadActionWithErrorsDataProvider(): array
{
return [
'upload_image_with_invalid_type' => [
'file' => [
'create_file' => true,
'name' => 'invalid_file.txt',
],
'expectation' => [
'message' => 'Disallowed file type.',
'errorcode' => 0,
'tmp_media_path' => '/i/n/invalid_file.txt',
],
],
'upload_empty_image' => [
'file' => [
'copy_file' => true,
'name' => 'magento_empty.jpg',
'type' => 'image/jpeg',
'current_path' => '/../../../../_files',
],
'expectation' => [
'message' => 'Something went wrong while saving the file(s).',
'errorcode' => 0,
'tmp_media_path' => '/m/a/magento_empty.jpg',
],
],
'upload_without_image' => [
'file' => [],
'expectation' => [
'message' => 'Something went wrong while saving the file(s).',
'errorcode' => 0,
],
],
'upload_wrong_png' => [
'file' => [
'copy_file' => true,
'name' => 'magento_wrong.png',
'type' => 'image/png',
'current_path' => '/../../../../_files',
],
'expectation' => [
'message' => 'Something went wrong while saving the file(s).',
'errorcode' => 0,
'tmp_media_path' => '/m/w/magento_wrong.png',
],
]
];
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$_FILES = [];
$this->mediaDirectory->delete('tmp');
parent::tearDown();
}
/**
* Copies file to tmp dir.
*
* @param array $file
* @return void
*/
private function copyFileToSysTmpDir(array $file): void
{
if (!empty($file)) {
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$fixtureDir = realpath(__DIR__ . $file['current_path']);
$filePath = $tmpDirectory->getAbsolutePath($file['name']);
copy($fixtureDir . DIRECTORY_SEPARATOR . $file['name'], $filePath);
$_FILES['image'] = [
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $filePath,
];
}
}
/**
* Creates txt file with given name and copies to tmp dir.
*
* @param string $name
* @return void
*/
private function createFileInSysTmpDir(string $name): void
{
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($name);
$file = fopen($filePath, "wb");
fwrite($file, 'some text');
$_FILES['image'] = [
'name' => $name,
'type' => 'text/plain',
'tmp_name' => $filePath,
];
}
/**
* Returns absolute path to file in media tmp dir.
*
* @param string $tmpPath
* @return string
*/
private function getFileAbsolutePath(string $tmpPath): string
{
return $this->mediaDirectory->getAbsolutePath($this->config->getBaseTmpMediaPath() . $tmpPath);
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
/**
* @magentoAppArea adminhtml
*/
class GetSelectedTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testExecute() : void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get('simple');
$this->getRequest()
->setPostValue('productId', $product->getId());
$this->dispatch('backend/catalog/product/getSelected');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString(
'{"value":"1","label":"Simple Product","is_active":1,"path":"simple"}',
$responseBody
);
}
public function testExecuteNonExistingSearchKey() : void
{
$this->getRequest()
->setPostValue('productId', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
$this->dispatch('backend/catalog/product/getSelected');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('[]', $responseBody);
}
}
@@ -0,0 +1,169 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\ObjectManagerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\Store;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\Catalog\Model\ResourceModel\Product\Gallery;
/**
* Test for mass product deleting.
*
* @see \Magento\Catalog\Controller\Adminhtml\Product\MassDelete
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class MassDeleteTest extends AbstractBackendController
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/** @var ProductRepositoryInterface */
protected $productRepository;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var Gallery
*/
private $galleryResource;
/**
* @var int
*/
private $mediaAttributeId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$this->productResource = $this->objectManager->create(ProductResource::class);
$this->galleryResource = $this->objectManager->create(Gallery::class);
$this->mediaAttributeId = (int)$this->productResource->getAttribute('media_gallery')->getAttributeId();
$this->productRepository->cleanCache();
}
/**
* @magentoDataFixture Magento/Catalog/_files/multiple_products.php
*
* @return void
*/
public function testDeleteSimpleProductViaMassAction(): void
{
$productIds = [10, 11, 12];
$this->dispatchMassDeleteAction($productIds);
$this->assertSuccessfulDeleteProducts(count($productIds));
}
/**
* Tests image remove during product delete.
*
* @magentoDataFixture Magento/Catalog/_files/product_with_media_gallery.php
*
* @return void
* @throws NoSuchEntityException
*/
public function testDeleteSimpleProductWithImageViaMassAction(): void
{
$productIds = [812];
$product = $this->productRepository->get(
'simple_product_with_media',
false,
Store::DEFAULT_STORE_ID,
true
);
$this->dispatchMassDeleteAction($productIds);
$this->assertSuccessfulDeleteProducts(count($productIds));
$productImages = $this->galleryResource->loadProductGalleryByAttributeId($product, $this->mediaAttributeId);
$this->assertCount(0, $productImages);
}
/**
* @return void
*/
public function testDeleteNotExistingProductViaMassAction(): void
{
$this->dispatchMassDeleteAction([989]);
$this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_ERROR);
$this->assertRedirect($this->stringContains('backend/catalog/product/index'));
}
/**
* @return void
*/
public function testMassDeleteWithoutProductIds(): void
{
$this->markTestSkipped('Test is blocked by issue MC-34495');
$this->dispatchMassDeleteAction();
$this->assertSessionMessages(
$this->equalTo('An item needs to be selected. Select and try again.'),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('backend/catalog/product/index'));
}
/**
* Assert successful delete products.
*
* @param int $productCount
* @return void
*/
protected function assertSuccessfulDeleteProducts(int $productCount): void
{
$this->assertSessionMessages(
$this->equalTo([(string)__('A total of %1 record(s) have been deleted.', $productCount)]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('backend/catalog/product/index'));
}
/**
* Dispatch mass delete action.
*
* @param array $productIds
* @return void
*/
protected function dispatchMassDeleteAction(array $productIds = []): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams(['selected' => $productIds, 'namespace' => 'product_listing']);
$this->dispatch('backend/catalog/product/massDelete/');
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,33 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Controller\Adminhtml\Product;
/**
* @magentoAppArea adminhtml
*/
class ReviewTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @magentoDataFixture Magento/Review/_files/review_xss.php
*/
public function testEditActionProductNameXss()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get('product-with-xss');
$reviewId = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Review\Model\Review::class
)->load(
$product->getId(),
'entity_pk_value'
)->getId();
$this->dispatch('backend/review/product/edit/id/' . $reviewId);
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('&lt;script&gt;alert(&quot;xss&quot;);&lt;/script&gt;', $responseBody);
$this->assertStringNotContainsString('<script>alert("xss");</script>', $responseBody);
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\Data\GroupInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test cases for set advanced price to product.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class AdvancedPricingTest extends AbstractBackendController
{
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
}
/**
* Assert that special price correctly saved to product.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options.php
*
* @return void
*/
public function testAddSpecialPriceToProduct(): void
{
$product = $this->productRepository->get('simple');
$postData = [
'product' => [
'special_price' => 8,
],
];
$this->assertNull($product->getSpecialPrice());
$this->dispatchWithData((int)$product->getEntityId(), $postData);
$product = $this->productRepository->get('simple', false, null, true);
$this->assertEquals(8, $product->getSpecialPrice());
}
/**
* Assert that tier price correctly saved to product.
*
* @magentoDataFixture Magento/Catalog/_files/product_without_options.php
*
* @return void
*/
public function testAddTierPriceToProduct(): void
{
$product = $this->productRepository->get('simple');
$postData = [
'product' => [
'tier_price' => [
[
'website_id' => '0',
'cust_group' => GroupInterface::CUST_GROUP_ALL,
'price_qty' => '100',
'price' => 5,
'value_type' => 'fixed',
]
],
],
];
$this->assertEquals(10, $product->getTierPrice(100));
$this->dispatchWithData((int)$product->getEntityId(), $postData);
$product = $this->productRepository->get('simple', false, null, true);
$this->assertEquals(5, $product->getTierPrice(100));
}
/**
* Dispatch product save with data.
*
* @param int $productId
* @param array $productPostData
* @return void
*/
private function dispatchWithData(int $productId, array $productPostData): void
{
$this->getRequest()->setPostValue($productPostData);
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $productId);
$this->assertSessionMessages(
$this->containsEqual('You saved the product.'),
MessageInterface::TYPE_SUCCESS
);
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\DefaultCategory;
use Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\App\Request\Http;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Message\MessageInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Checks category product index in cases when category unassigned from product
*
* @magentoDataFixture Magento/Catalog/_files/category_product_assigned_to_website.php
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class CategoryIndexTest extends AbstractBackendController
{
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var ProductInterface */
private $product;
/** @var TableMaintainer */
private $tableMaintainer;
/** @var ProductResource */
private $productResource;
/** @var AdapterInterface */
private $connection;
/** @var DefaultCategory */
private $defaultCategoryHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$this->product = $this->productRepository->get('product_with_category');
$this->tableMaintainer = $this->_objectManager->create(TableMaintainer::class);
$this->productResource = $this->_objectManager->get(ProductResource::class);
$this->connection = $this->productResource->getConnection();
$this->defaultCategoryHelper = $this->_objectManager->get(DefaultCategory::class);
}
/**
* @return void
*/
public function testUnassignCategory(): void
{
$postData = $this->preparePostData();
$this->dispatchSaveProductRequest($postData);
$this->assertEmpty($this->fetchIndexData());
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_product_assigned_to_website.php
* @magentoDataFixture Magento/Catalog/_files/category.php
*
* @return void
*/
public function testReassignCategory(): void
{
$postData = $this->preparePostData(333);
$this->dispatchSaveProductRequest($postData);
$result = $this->fetchIndexData();
$this->assertNotEmpty($result);
$this->assertEquals(333, reset($result)['category_id']);
}
/**
* Perform request
*
* @param array $postData
* @return void
*/
private function dispatchSaveProductRequest(array $postData): void
{
$this->getRequest()->setPostValue($postData);
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $this->product->getEntityId());
$this->assertSessionMessages($this->equalTo(['You saved the product.']), MessageInterface::TYPE_SUCCESS);
}
/**
* Prepare data to request
*
* @param int|null $newCategoryId
* @return array
*/
private function preparePostData(?int $newCategoryId = null): array
{
$this->product->getWebsiteIds();
$data = $this->product->getData();
unset($data['entity_id'], $data['category_ids']);
if ($newCategoryId) {
$data['category_ids'] = [$newCategoryId];
}
return ['product' => $data];
}
/**
* Fetch data from category product index table
*
* @return array
*/
private function fetchIndexData(): array
{
$tableName = $this->tableMaintainer->getMainTable(Store::DISTRO_STORE_ID);
$select = $this->connection->select();
$select->from(['index_table' => $tableName], 'index_table.category_id')
->where('index_table.product_id = ?', $this->product->getId())
->where('index_table.category_id != ?', $this->defaultCategoryHelper->getId());
return $this->connection->fetchAll($select);
}
}
@@ -0,0 +1,272 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Base test cases for product custom options with type "field".
* Option add via dispatch product controller action save with options data in POST data.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_without_options.php
*/
class CreateCustomOptionsTest extends AbstractBackendController
{
/**
* @var string
*/
protected $productSku = 'simple';
/**
* Test add to product custom option with type "field".
*
* @dataProvider productWithNewOptionsDataProvider
*
* @param array $productPostData
*
* @magentoDbIsolation enabled
*/
public function testSaveCustomOptionWithTypeField(array $productPostData): void
{
$this->getRequest()->setPostValue($productPostData);
$product = $this->_objectManager->get(ProductRepositoryInterface::class)->get($this->productSku);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertSessionMessages(
$this->containsEqual('You saved the product.'),
MessageInterface::TYPE_SUCCESS
);
$productOptions = $this->_objectManager->get(ProductCustomOptionRepositoryInterface::class)
->getProductOptions($product);
$this->assertCount(2, $productOptions);
foreach ($productOptions as $customOption) {
$postOptionData = $productPostData['product']['options'][$customOption->getTitle()] ?? null;
$this->assertNotNull($postOptionData);
$this->assertEquals($postOptionData['title'], $customOption->getTitle());
$this->assertEquals($postOptionData['type'], $customOption->getType());
$this->assertEquals($postOptionData['is_require'], $customOption->getIsRequire());
$this->assertEquals($postOptionData['sku'], $customOption->getSku());
$this->assertEquals($postOptionData['price'], $customOption->getPrice());
$this->assertEquals($postOptionData['price_type'], $customOption->getPriceType());
$maxCharacters = $postOptionData['max_characters'] ?? 0;
$this->assertEquals($maxCharacters, $customOption->getMaxCharacters());
}
}
/**
* Return all data for add option to product for all cases.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
* @return array
*/
public function productWithNewOptionsDataProvider(): array
{
return [
'required_options' => [
[
'product' => [
'options' => [
'Test option title 1' => [
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
'Test option title 2' => [
'record_id' => 1,
'sort_order' => 2,
'is_require' => 1,
'sku' => 'test-option-title-2',
'max_characters' => 50,
'title' => 'Test option title 2',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
],
],
],
],
'not_required_options' => [
[
'product' => [
'options' => [
'Test option title 1' => [
'record_id' => 0,
'sort_order' => 1,
'is_require' => 0,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
'Test option title 2' => [
'record_id' => 1,
'sort_order' => 2,
'is_require' => 0,
'sku' => 'test-option-title-2',
'max_characters' => 50,
'title' => 'Test option title 2',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
],
],
],
],
'options_with_fixed_price' => [
[
'product' => [
'options' => [
'Test option title 1' => [
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
'Test option title 2' => [
'record_id' => 1,
'sort_order' => 2,
'is_require' => 1,
'sku' => 'test-option-title-2',
'max_characters' => 50,
'title' => 'Test option title 2',
'type' => 'field',
'price' => 10,
'price_type' => 'percent',
],
],
],
],
],
'options_with_percent_price' => [
[
'product' => [
'options' => [
'Test option title 1' => [
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 50,
'title' => 'Test option title 1',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
'Test option title 2' => [
'record_id' => 1,
'sort_order' => 2,
'is_require' => 1,
'sku' => 'test-option-title-2',
'max_characters' => 50,
'title' => 'Test option title 2',
'type' => 'field',
'price' => 20,
'price_type' => 'percent',
],
],
],
],
],
'options_with_max_charters_configuration' => [
[
'product' => [
'options' => [
'Test option title 1' => [
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'max_characters' => 30,
'title' => 'Test option title 1',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
'Test option title 2' => [
'record_id' => 1,
'sort_order' => 2,
'is_require' => 1,
'sku' => 'test-option-title-2',
'max_characters' => 50,
'title' => 'Test option title 2',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
],
],
],
],
'options_without_max_charters_configuration' => [
[
'product' => [
'options' => [
'Test option title 1' => [
'record_id' => 0,
'sort_order' => 1,
'is_require' => 1,
'sku' => 'test-option-title-1',
'title' => 'Test option title 1',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
'Test option title 2' => [
'record_id' => 1,
'sort_order' => 2,
'is_require' => 1,
'sku' => 'test-option-title-2',
'title' => 'Test option title 2',
'type' => 'field',
'price' => 10,
'price_type' => 'fixed',
],
],
],
],
],
];
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory;
use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Base test cases for delete product custom option with type "field".
* Option deleting via product controller action save.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_without_options.php
*/
class DeleteCustomOptionsTest extends AbstractBackendController
{
/**
* @var string
*/
protected $productSku = 'simple';
/**
* Test delete custom option with type "field".
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\Field::getDataForCreateOptions
*
* @param array $optionData
* @return void
*/
public function testDeleteCustomOptionWithTypeField(array $optionData): void
{
$productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get($this->productSku);
/** @var ProductCustomOptionInterface $option */
$option = $this->_objectManager->get(ProductCustomOptionInterfaceFactory::class)
->create(['data' => $optionData]);
$option->setProductSku($product->getSku());
$product->setOptions([$option]);
$productRepository->save($product);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the product.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertCount(
0,
$this->_objectManager->get(ProductCustomOptionRepositoryInterface::class)
->getProductOptions($product)
);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,147 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Media\Config;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Provide tests for admin product save action with images.
*
* @magentoAppArea adminhtml
*/
class ImagesTest extends AbstractBackendController
{
/**
* @var Config
*/
private $config;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->config = $this->_objectManager->get(Config::class);
$this->mediaDirectory = $this->_objectManager->get(Filesystem::class)->getDirectoryWrite(DirectoryList::MEDIA);
$this->productRepository = $this->_objectManager->create(ProductRepositoryInterface::class);
}
/**
* Test save product with default image.
*
* @dataProvider simpleProductImagesDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @magentoDbIsolation enabled
* @param array $postData
* @param array $expectation
* @return void
*/
public function testSaveSimpleProductDefaultImage(array $postData, array $expectation): void
{
$product = $this->productRepository->get('simple');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertSessionMessages(
$this->equalTo(['You saved the product.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertSuccessfulImageSave($expectation);
}
/**
* @return array
*/
public function simpleProductImagesDataProvider(): array
{
return [
'simple_product_with_jpg_image' => [
'post_data' => [
'product' => [
'media_gallery' => [
'images' => [
'lrwuv5ukisn' => [
'position' => '1',
'media_type' => 'image',
'video_provider' => '',
'file' => '/m/a//magento_image.jpg.tmp',
'value_id' => '',
'label' => '',
'disabled' => '0',
'removed' => '',
'role' => '',
],
],
],
'image' => '/m/a//magento_image.jpg.tmp',
'small_image' => '/m/a//magento_image.jpg.tmp',
'thumbnail' => '/m/a//magento_image.jpg.tmp',
'swatch_image' => '/m/a//magento_image.jpg.tmp',
],
],
'expectation' => [
'media_gallery_image' => [
'position' => '1',
'media_type' => 'image',
'file' => '/m/a/magento_image.jpg',
'label' => '',
'disabled' => '0',
],
'image' => '/m/a/magento_image.jpg',
'small_image' => '/m/a/magento_image.jpg',
'thumbnail' => '/m/a/magento_image.jpg',
'swatch_image' => '/m/a/magento_image.jpg',
]
]
];
}
/**
* @param array $expectation
* @return void
*/
private function assertSuccessfulImageSave(array $expectation): void
{
$product = $this->productRepository->get('simple', false, null, true);
$galleryImage = reset($product->getData('media_gallery')['images']);
$expectedGalleryImage = $expectation['media_gallery_image'];
$this->assertEquals($expectedGalleryImage['position'], $galleryImage['position']);
$this->assertEquals($expectedGalleryImage['media_type'], $galleryImage['media_type']);
$this->assertEquals($expectedGalleryImage['label'], $galleryImage['label']);
$this->assertEquals($expectedGalleryImage['disabled'], $galleryImage['disabled']);
$this->assertEquals($expectedGalleryImage['file'], $galleryImage['file']);
$this->assertEquals($expectation['image'], $product->getData('image'));
$this->assertEquals($expectation['small_image'], $product->getData('small_image'));
$this->assertEquals($expectation['thumbnail'], $product->getData('thumbnail'));
$this->assertEquals($expectation['swatch_image'], $product->getData('swatch_image'));
$this->assertTrue(
$this->mediaDirectory->isExist(
$this->mediaDirectory->getAbsolutePath($this->config->getBaseMediaPath() . $expectation['image'])
)
);
}
}
@@ -0,0 +1,144 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Saving product with linked products
*
* @magentoAppArea adminhtml
*/
class LinksTest extends AbstractBackendController
{
/** @var array */
private $linkTypes = [
'upsell',
'crosssell',
'related',
];
/** @var ProductRepositoryInterface $productRepository */
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = $this->_objectManager->create(ProductRepositoryInterface::class);
}
/**
* Test add simple related, up-sells, cross-sells product
*
* @magentoDataFixture Magento/Catalog/_files/multiple_products.php
* @magentoDbIsolation enabled
* @return void
*/
public function testAddRelatedUpSellCrossSellProducts(): void
{
$postData = $this->getPostData();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product/save');
$this->assertSessionMessages(
$this->equalTo(['You saved the product.']),
MessageInterface::TYPE_SUCCESS
);
$product = $this->productRepository->get('simple');
$this->assertEquals(
$this->getExpectedLinks($postData['links']),
$this->getActualLinks($product),
"Expected linked products do not match actual linked products!"
);
}
/**
* Get post data for the request
*
* @return array
*/
private function getPostData(): array
{
return [
'product' => [
'attribute_set_id' => '4',
'status' => '1',
'name' => 'Simple Product',
'sku' => 'simple',
'url_key' => 'simple-product',
'type_id' => \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE
],
'links' => [
'upsell' => [
['id' => '10'],
],
'crosssell' => [
['id' => '11'],
],
'related' => [
['id' => '12'],
],
]
];
}
/**
* Set an array of expected related, up-sells, cross-sells product identifiers
*
* @param array $links
* @return array
*/
private function getExpectedLinks(array $links): array
{
$expectedLinks = [];
foreach ($this->linkTypes as $linkType) {
$expectedLinks[$linkType] = [];
foreach ($links[$linkType] as $productData) {
$expectedLinks[$linkType][] = $productData['id'];
}
}
return $expectedLinks;
}
/**
* Get an array of received related, up-sells, cross-sells products
*
* @param ProductInterface|Product $product
* @return array
*/
private function getActualLinks(ProductInterface $product): array
{
$actualLinks = [];
foreach ($this->linkTypes as $linkType) {
$ids = [];
switch ($linkType) {
case 'upsell':
$ids = $product->getUpSellProductIds();
break;
case 'crosssell':
$ids = $product->getCrossSellProductIds();
break;
case 'related':
$ids = $product->getRelatedProductIds();
break;
}
$actualLinks[$linkType] = $ids;
}
return $actualLinks;
}
}
@@ -0,0 +1,125 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Save;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Api\Data\ProductCustomOptionInterfaceFactory;
use Magento\Catalog\Api\ProductCustomOptionRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Option;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Base test cases for update product custom options with type "field".
* Option updating via dispatch product controller action save with updated options data in POST data.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/product_without_options.php
*/
class UpdateCustomOptionsTest extends AbstractBackendController
{
/**
* @var string
*/
protected $productSku = 'simple';
/**
* Test add to product custom option with type "field".
*
* @dataProvider \Magento\TestFramework\Catalog\Model\Product\Option\DataProvider\Type\Field::getDataForUpdateOptions
*
* @param array $optionData
* @param array $updateData
* @return void
*/
public function testUpdateCustomOptionWithTypeField(array $optionData, array $updateData): void
{
$productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$optionRepository = $this->_objectManager->get(ProductCustomOptionRepositoryInterface::class);
$product = $productRepository->get($this->productSku);
/** @var ProductCustomOptionInterface|Option $option */
$option = $this->_objectManager->get(ProductCustomOptionInterfaceFactory::class)
->create(['data' => $optionData]);
$option->setProductSku($product->getSku());
$product->setOptions([$option]);
$productRepository->save($product);
$currentProductOptions = $optionRepository->getProductOptions($product);
$this->assertCount(1, $currentProductOptions);
/** @var ProductCustomOptionInterface $currentOption */
$currentOption = reset($currentProductOptions);
$postData = [
'product' => [
'options' => [
[
'option_id' => $currentOption->getOptionId(),
'product_id' => $product->getId(),
'type' => $currentOption->getType(),
'is_require' => $currentOption->getIsRequire(),
'sku' => $currentOption->getSku(),
'max_characters' => $currentOption->getMaxCharacters(),
'title' => $currentOption->getTitle(),
'sort_order' => $currentOption->getSortOrder(),
'price' => $currentOption->getPrice(),
'price_type' => $currentOption->getPriceType(),
'is_use_default' => false,
],
],
],
];
foreach ($updateData as $methodKey => $newValue) {
$postData = array_replace_recursive(
$postData,
[
'product' => [
'options' => [
0 => [
$methodKey => $newValue,
],
],
],
]
);
$this->getRequest()->setPostValue($postData);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertSessionMessages(
$this->containsEqual('You saved the product.'),
MessageInterface::TYPE_SUCCESS
);
$updatedOptions = $optionRepository->getProductOptions($product);
$this->assertCount(1, $updatedOptions);
/** @var ProductCustomOptionInterface|Option $updatedOption */
$updatedOption = reset($updatedOptions);
$this->assertEquals($newValue, $updatedOption->getDataUsingMethod($methodKey));
$this->assertEquals($option->getOptionId(), $updatedOption->getOptionId());
$this->assertNotEquals(
$option->getDataUsingMethod($methodKey),
$updatedOption->getDataUsingMethod($methodKey)
);
}
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$reflection = new \ReflectionObject($this);
foreach ($reflection->getProperties() as $property) {
if (!$property->isStatic() && 0 !== strpos($property->getDeclaringClass()->getName(), 'PHPUnit')) {
$property->setAccessible(true);
$property->setValue($this, null);
}
}
}
}
@@ -0,0 +1,81 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
/**
* @magentoAppArea adminhtml
*/
class SearchTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testExecute() : void
{
$this->getRequest()
->setPostValue('searchKey', 'simple')
->setPostValue('page', 1)
->setPostValue('limit', 50);
$this->dispatch('backend/catalog/product/search');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString(
'"options":{"1":{"value":"1","label":"Simple Product","is_active":1,"path":"simple","optgroup":false}',
$responseBody
);
}
public function testExecuteNonExistingSearchKey() : void
{
$this->getRequest()
->setPostValue('searchKey', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
->setPostValue('page', 1)
->setPostValue('limit', 50);
$this->dispatch('backend/catalog/product/search');
$responseBody = $this->getResponse()->getBody();
$jsonResponse = json_decode($responseBody, true);
$this->assertEmpty($jsonResponse['options']);
}
/**
* @magentoDataFixture Magento/Catalog/_files/categories.php
*/
public function testExecuteNotVisibleIndividuallyProducts() : void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get('simple-3');
$this->assertEquals('simple-3', $product->getSku());
$this->getRequest()
->setPostValue('searchKey', 'simple-3')
->setPostValue('page', 1)
->setPostValue('limit', 50);
$this->dispatch('backend/catalog/product/search');
$responseBody = $this->getResponse()->getBody();
$jsonResponse = json_decode($responseBody, true);
$this->assertEquals(1, $jsonResponse['total']);
$this->assertCount(1, $jsonResponse['options']);
}
/**
* @magentoDataFixture Magento/Catalog/_files/multiple_mixed_products.php
*/
public function testExecuteEnabledAndDisabledProducts() : void
{
$this->getRequest()
->setPostValue('searchKey', 'simple')
->setPostValue('page', 1)
->setPostValue('limit', 50);
$this->dispatch('backend/catalog/product/search');
$responseBody = $this->getResponse()->getBody();
$jsonResponse = json_decode($responseBody, true);
$this->assertEquals(6, $jsonResponse['total']);
$this->assertCount(6, $jsonResponse['options']);
}
}
@@ -0,0 +1,148 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Set;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Eav\Api\AttributeSetRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Eav\Model\GetAttributeSetByName;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test for attribute set deleting.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class DeleteTest extends AbstractBackendController
{
/**
* @var GetAttributeSetByName
*/
private $getAttributeSetByName;
/**
* @var ProductInterface|Product
*/
private $product;
/**
* @var AttributeSetRepositoryInterface
*/
private $attributeSetRepository;
/**
* @var Escaper
*/
private $escaper;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->getAttributeSetByName = $this->_objectManager->get(GetAttributeSetByName::class);
$this->product = $this->_objectManager->get(ProductInterface::class);
$this->attributeSetRepository = $this->_objectManager->get(AttributeSetRepositoryInterface::class);
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
}
/**
* Assert that default attribute set is not deleted.
*
* @return void
*/
public function testDefaultAttributeSetIsNotDeleted(): void
{
$productDefaultAttrSetId = (int)$this->product->getDefaultAttributeSetId();
$this->performDeleteAttributeSetRequest($productDefaultAttrSetId);
$expectedSessionMessage = $this->escaper->escapeHtml((string)__('We can\'t delete this set right now.'));
$this->assertSessionMessages(
$this->equalTo([$expectedSessionMessage]),
MessageInterface::TYPE_ERROR
);
try {
$this->attributeSetRepository->get($productDefaultAttrSetId);
} catch (NoSuchEntityException $e) {
$this->fail(sprintf('Default attribute set was deleted. Message: %s', $e->getMessage()));
}
}
/**
* Assert that custom attribute set deleting properly.
*
* @magentoDataFixture Magento/Eav/_files/empty_attribute_set.php
*
* @return void
*/
public function testDeleteCustomAttributeSetById(): void
{
$this->deleteAttributeSetByNameAndAssert('empty_attribute_set');
}
/**
* Assert that product will be deleted if delete attribute set which the product is attached.
*
* @magentoDataFixture Magento/Catalog/_files/product_with_test_attribute_set.php
*
* @return void
*/
public function testProductIsDeletedAfterDeleteItsAttributeSet(): void
{
$this->deleteAttributeSetByNameAndAssert('new_attribute_set');
$this->expectExceptionObject(
new NoSuchEntityException(
__('The product that was requested doesn\'t exist. Verify the product and try again.')
)
);
$this->productRepository->get('simple');
}
/**
* Perform request to delete attribute set and assert that attribute set is deleted.
*
* @param string $attributeSetName
* @return void
*/
private function deleteAttributeSetByNameAndAssert(string $attributeSetName): void
{
$attributeSet = $this->getAttributeSetByName->execute($attributeSetName);
$this->performDeleteAttributeSetRequest((int)$attributeSet->getAttributeSetId());
$this->assertSessionMessages(
$this->equalTo([(string)__('The attribute set has been removed.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertNull($this->getAttributeSetByName->execute($attributeSetName));
}
/**
* Perform "catalog/product_set/delete" controller dispatch.
*
* @param int $attributeSetId
* @return void
*/
private function performDeleteAttributeSetRequest(int $attributeSetId): void
{
$this->getRequest()
->setParam('id', $attributeSetId)
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product_set/delete/');
}
}
@@ -0,0 +1,371 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Set;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Repository;
use Magento\Developer\Model\Logger\Handler\Syslog;
use Magento\Eav\Api\AttributeManagementInterface;
use Magento\Eav\Api\AttributeSetRepositoryInterface;
use Magento\Eav\Api\Data\AttributeSetInterface;
use Magento\Eav\Model\Config;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Logger\Handler\System;
use Magento\Framework\Logger\Monolog;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Psr\Log\LoggerInterface;
/**
* Testing for saving an existing or creating a new attribute set.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
*/
class SaveTest extends AbstractBackendController
{
/**
* @var string
*/
private $systemLogPath = '';
/**
* @var Monolog
*/
private $logger;
/**
* @var Syslog
*/
private $syslogHandler;
/**
* @var AttributeManagementInterface
*/
private $attributeManagement;
/**
* @var DataObjectHelper
*/
private $dataObjectHelper;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var Repository
*/
private $attributeRepository;
/**
* @var AttributeSetRepositoryInterface
*/
private $attributeSetRepository;
/**
* @var Config
*/
private $eavConfig;
/**
* @var Json
*/
private $json;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->logger = $this->_objectManager->get(LoggerInterface::class);
$this->syslogHandler = $this->_objectManager->create(
Syslog::class,
[
'filePath' => Bootstrap::getInstance()->getAppTempDir(),
]
);
$this->attributeManagement = $this->_objectManager->get(AttributeManagementInterface::class);
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$this->attributeRepository = $this->_objectManager->get(Repository::class);
$this->dataObjectHelper = $this->_objectManager->get(DataObjectHelper::class);
$this->attributeSetRepository = $this->_objectManager->get(AttributeSetRepositoryInterface::class);
$this->eavConfig = $this->_objectManager->get(Config::class);
$this->json = $this->_objectManager->get(Json::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->attributeRepository->get('country_of_manufacture')->setIsUserDefined(false);
parent::tearDown();
}
/**
* Test that new attribute set based on default attribute set will be successfully created.
*
* @magentoDbIsolation enabled
*
* @return void
*/
public function testCreateNewAttributeSetBasedOnDefaultAttributeSet(): void
{
$this->createAttributeSetBySkeletonAndAssert(
'Attribute set name for test',
$this->getCatalogProductDefaultAttributeSetId()
);
}
/**
* Test that new attribute set based on custom attribute set will be successfully created.
*
* @magentoDataFixture Magento/Catalog/_files/attribute_set_with_renamed_group.php
*
* @magentoDbIsolation enabled
*
* @return void
*/
public function testCreateNewAttributeSetBasedOnCustomAttributeSet(): void
{
$existCustomAttributeSet = $this->getAttributeSetByName('attribute_set_test');
$this->createAttributeSetBySkeletonAndAssert(
'Attribute set name for test',
(int)$existCustomAttributeSet->getAttributeSetId()
);
}
/**
* Test that new attribute set based on custom attribute set will be successfully created.
*
* @magentoDbIsolation enabled
*
* @return void
*/
public function testGotErrorDuringCreateAttributeSetWithoutName(): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'gotoEdit' => '1',
'skeleton_set' => $this->getCatalogProductDefaultAttributeSetId(),
'attribute_set_name' => ''
]
);
$this->dispatch('backend/catalog/product_set/save/');
$this->assertSessionMessages(
$this->equalTo([(string)__('The attribute set name is empty. Enter the name and try again.')]),
MessageInterface::TYPE_ERROR
);
}
/**
* Test that exception throws during save attribute set name process if name of attribute set already exists.
*
* @magentoDataFixture Magento/Catalog/_files/attribute_set_with_renamed_group.php
* @return void
*/
public function testAlreadyExistsExceptionProcessingWhenGroupCodeIsDuplicated(): void
{
$attributeSet = $this->getAttributeSetByName('attribute_set_test');
$this->assertNotEmpty($attributeSet, 'Attribute set with name "attribute_set_test" is missed');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
'data',
$this->json->serialize(
[
'attribute_set_name' => 'attribute_set_test',
'groups' => [
['ynode-418', 'attribute-group-name', 1],
],
'attributes' => [
['9999', 'ynode-418', 1, null]
],
'not_attributes' => [],
'removeGroups' => [],
]
)
);
$this->dispatch('backend/catalog/product_set/save/id/' . $attributeSet->getAttributeSetId());
$jsonResponse = $this->json->unserialize($this->getResponse()->getBody());
$this->assertNotNull($jsonResponse);
$this->assertEquals(1, $jsonResponse['error']);
$this->assertStringContainsString(
(string)__(
'Attribute group with same code already exist.'
. ' Please rename &quot;attribute-group-name&quot; group'
),
$jsonResponse['message']
);
}
/**
* Test behavior when attribute set was changed to a new set
* with deleted attribute from the previous set.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Catalog/_files/attribute_set_based_on_default.php
* @magentoDbIsolation disabled
* @return void
*/
public function testRemoveAttributeFromAttributeSet(): void
{
$message = 'Attempt to load value of nonexistent EAV attribute';
$this->removeSyslog();
$attributeSet = $this->getAttributeSetByName('new_attribute_set');
$product = $this->productRepository->get('simple');
$this->attributeRepository->get('country_of_manufacture')->setIsUserDefined(true);
$this->attributeManagement->unassign($attributeSet->getId(), 'country_of_manufacture');
$productData = [
'country_of_manufacture' => 'Angola'
];
$this->dataObjectHelper->populateWithArray($product, $productData, ProductInterface::class);
$this->productRepository->save($product);
$product->setAttributeSetId($attributeSet->getId());
$product = $this->productRepository->save($product);
$this->dispatch('backend/catalog/product/edit/id/' . $product->getEntityId());
$syslogPath = $this->getSyslogPath();
$syslogContent = file_exists($syslogPath) ? file_get_contents($syslogPath) : '';
$this->assertStringNotContainsString($message, $syslogContent);
}
/**
* Retrieve system.log file path.
*
* @return string
*/
private function getSyslogPath(): string
{
if (!$this->systemLogPath) {
foreach ($this->logger->getHandlers() as $handler) {
if ($handler instanceof System) {
$this->systemLogPath = $handler->getUrl();
}
}
}
return $this->systemLogPath;
}
/**
* Remove system.log file
*
* @return void
*/
private function removeSyslog(): void
{
$this->syslogHandler->close();
if (file_exists($this->getSyslogPath())) {
unlink($this->getSyslogPath());
}
}
/**
* Search and return attribute set by name.
*
* @param string $attributeSetName
* @return AttributeSetInterface|null
*/
private function getAttributeSetByName(string $attributeSetName): ?AttributeSetInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$searchCriteriaBuilder->addFilter('attribute_set_name', $attributeSetName);
$result = $this->attributeSetRepository->getList($searchCriteriaBuilder->create());
$items = $result->getItems();
return array_pop($items);
}
/**
* Create attribute set by skeleton attribute set id and assert that attribute set
* created successfully and attributes from skeleton attribute set and created attribute set are equals.
*
* @param string $attributeSetName
* @param int $skeletonAttributeSetId
* @return void
*/
private function createAttributeSetBySkeletonAndAssert(
string $attributeSetName,
int $skeletonAttributeSetId
): void {
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'attribute_set_name' => $attributeSetName,
'gotoEdit' => '1',
'skeleton_set' => $skeletonAttributeSetId,
]
);
$this->dispatch('backend/catalog/product_set/save/');
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the attribute set.')]),
MessageInterface::TYPE_SUCCESS
);
$createdAttributeSet = $this->getAttributeSetByName($attributeSetName);
$existAttributeSet = $this->attributeSetRepository->get($skeletonAttributeSetId);
$this->assertNotNull($createdAttributeSet);
$this->assertEquals($attributeSetName, $createdAttributeSet->getAttributeSetName());
$this->assertAttributeSetsAttributesAreEquals($createdAttributeSet, $existAttributeSet);
}
/**
* Assert that both attribute sets contains identical attributes by attribute ids.
*
* @param AttributeSetInterface $createdAttributeSet
* @param AttributeSetInterface $existAttributeSet
* @return void
*/
private function assertAttributeSetsAttributesAreEquals(
AttributeSetInterface $createdAttributeSet,
AttributeSetInterface $existAttributeSet
): void {
$expectedAttributeIds = array_keys(
$this->attributeManagement->getAttributes(
ProductAttributeInterface::ENTITY_TYPE_CODE,
$existAttributeSet->getAttributeSetId()
)
);
sort($expectedAttributeIds);
$actualAttributeIds = array_keys(
$this->attributeManagement->getAttributes(
ProductAttributeInterface::ENTITY_TYPE_CODE,
$createdAttributeSet->getAttributeSetId()
)
);
sort($actualAttributeIds);
$this->assertSame($expectedAttributeIds, $actualAttributeIds);
}
/**
* Retrieve default catalog product attribute set ID.
*
* @return int
*/
private function getCatalogProductDefaultAttributeSetId(): int
{
return (int)$this->eavConfig
->getEntityType(ProductAttributeInterface::ENTITY_TYPE_CODE)
->getDefaultAttributeSetId();
}
}
@@ -0,0 +1,238 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product\Set;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Eav\Api\AttributeManagementInterface;
use Magento\Eav\Api\AttributeSetRepositoryInterface;
use Magento\Eav\Api\Data\AttributeGroupInterface;
use Magento\Eav\Api\Data\AttributeSetInterface;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\Collection;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\TestFramework\Eav\Model\GetAttributeSetByName;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test update attribute set.
*/
class UpdateTest extends AbstractBackendController
{
/**
* @var Json
*/
private $json;
/**
* @var AttributeSetRepositoryInterface
*/
private $attributeSetRepository;
/**
* @var AttributeManagementInterface
*/
private $attributeManagement;
/**
* @var CollectionFactory
*/
private $attributeGroupCollectionFactory;
/**
* @var GetAttributeSetByName
*/
private $getAttributeSetByName;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->json = $this->_objectManager->get(Json::class);
$this->attributeSetRepository = $this->_objectManager->get(AttributeSetRepositoryInterface::class);
$this->attributeManagement = $this->_objectManager->get(AttributeManagementInterface::class);
$this->attributeGroupCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
$this->getAttributeSetByName = $this->_objectManager->get(GetAttributeSetByName::class);
}
/**
* Test that name of attribute set will update/change correctly.
*
* @magentoDataFixture Magento/Catalog/_files/attribute_set_based_on_default.php
*
* @magentoDbIsolation disabled
*
* @return void
*/
public function testUpdateAttributeSetName(): void
{
$attributeSet = $this->getAttributeSetByName->execute('new_attribute_set');
$currentAttrSetName = $attributeSet->getAttributeSetName();
$this->assertNotNull($attributeSet);
$postData = $this->prepareDataToRequest($attributeSet);
$updateName = 'New attribute set name';
$postData['attribute_set_name'] = $updateName;
$this->performRequest((int)$attributeSet->getAttributeSetId(), $postData);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the attribute set.')]),
MessageInterface::TYPE_SUCCESS
);
$updatedAttributeSet = $this->attributeSetRepository->get((int)$attributeSet->getAttributeSetId());
$this->assertEquals($updateName, $updatedAttributeSet->getAttributeSetName());
$updatedAttributeSet->setAttributeSetName($currentAttrSetName);
$this->attributeSetRepository->save($updatedAttributeSet);
}
/**
* Test add new group to custom attribute set.
*
* @magentoDataFixture Magento/Catalog/_files/attribute_set_based_on_default.php
*
* @magentoDbIsolation disabled
*
* @return void
*/
public function testUpdateAttributeSetWithNewGroup(): void
{
$currentAttrSet = $this->getAttributeSetByName->execute('new_attribute_set');
$this->assertNotNull($currentAttrSet);
$attrSetId = (int)$currentAttrSet->getAttributeSetId();
$currentAttrGroups = $this->getAttributeSetGroupCollection($attrSetId)->getItems();
$newGroupName = 'Test attribute group name';
$newGroupSortOrder = 11;
$postData = $this->prepareDataToRequest($currentAttrSet);
$postData['groups'][] = [
null,
$newGroupName,
$newGroupSortOrder,
];
$this->performRequest($attrSetId, $postData);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the attribute set.')]),
MessageInterface::TYPE_SUCCESS
);
$updatedAttrGroups = $this->getAttributeSetGroupCollection($attrSetId)->getItems();
$diffGroups = array_diff_key($updatedAttrGroups, $currentAttrGroups);
$this->assertCount(1, $diffGroups);
/** @var AttributeGroupInterface $newGroup */
$newGroup = reset($diffGroups);
$this->assertEquals($newGroupName, $newGroup->getAttributeGroupName());
$this->assertEquals($newGroupSortOrder, $newGroup->getSortOrder());
}
/**
* Test delete custom group from custom attribute set.
*
* @magentoDataFixture Magento/Catalog/_files/attribute_set_based_on_default_with_custom_group.php
*
* @magentoDbIsolation disabled
*
* @return void
*/
public function testDeleteCustomGroupFromCustomAttributeSet(): void
{
$testGroupName = 'Test attribute group name';
$currentAttrSet = $this->getAttributeSetByName->execute('new_attribute_set');
$this->assertNotNull($currentAttrSet);
$attrSetId = (int)$currentAttrSet->getAttributeSetId();
$currentAttrGroupsCollection = $this->getAttributeSetGroupCollection($attrSetId);
$customGroup = $currentAttrGroupsCollection->getItemByColumnValue(
AttributeGroupInterface::GROUP_NAME,
$testGroupName
);
$this->assertNotNull($customGroup);
$postData = $this->prepareDataToRequest($currentAttrSet);
$postData['removeGroups'] = [
$customGroup->getAttributeGroupId()
];
$this->performRequest($attrSetId, $postData);
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the attribute set.')]),
MessageInterface::TYPE_SUCCESS
);
$updatedAttrGroups = $this->getAttributeSetGroupCollection($attrSetId)->getItems();
$diffGroups = array_diff_key($currentAttrGroupsCollection->getItems(), $updatedAttrGroups);
$this->assertCount(1, $diffGroups);
/** @var AttributeGroupInterface $deletedGroup */
$deletedGroup = reset($diffGroups);
$this->assertEquals($testGroupName, $deletedGroup->getAttributeGroupName());
}
/**
* Process attribute set save request.
*
* @param int $attributeSetId
* @param array $postData
* @return void
*/
private function performRequest(int $attributeSetId, array $postData = []): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
'data',
$this->json->serialize($postData)
);
$this->dispatch('backend/catalog/product_set/save/id/' . $attributeSetId);
}
/**
* Prepare default data to request from attribute set.
*
* @param AttributeSetInterface $attributeSet
* @return array
*/
private function prepareDataToRequest(AttributeSetInterface $attributeSet): array
{
$result = [
'attribute_set_name' => $attributeSet->getAttributeSetName(),
'removeGroups' => [],
'not_attributes' => [],
];
$groups = $attributes = [];
/** @var AttributeGroupInterface $group */
foreach ($this->getAttributeSetGroupCollection((int)$attributeSet->getAttributeSetId()) as $group) {
$groups[] = [
$group->getAttributeGroupId(),
$group->getAttributeGroupName(),
$group->getSortOrder(),
];
}
$attributeSetAttributes = $this->attributeManagement->getAttributes(
ProductAttributeInterface::ENTITY_TYPE_CODE,
$attributeSet->getAttributeSetId()
);
foreach ($attributeSetAttributes as $attribute) {
$attributes[] = [
$attribute->getAttributeId(),
$attribute->getAttributeGroupId(),
$attribute->getSortOrder(),
];
}
$result['groups'] = $groups;
$result['attributes'] = $attributes;
return $result;
}
/**
* Build attribute set groups collection by attribute set id.
*
* @param int $attributeSetId
* @return Collection
*/
private function getAttributeSetGroupCollection(int $attributeSetId): Collection
{
$groupCollection = $this->attributeGroupCollectionFactory->create();
$groupCollection->setAttributeSetFilter($attributeSetId);
return $groupCollection;
}
}
@@ -0,0 +1,60 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml\Product;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Catalog\Model\Product\Type;
/**
* @magentoAppArea adminhtml
*/
class ValidateTest extends AbstractBackendController
{
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testNotUniqueUrlKey()
{
$this->getRequest()
->setMethod(HttpRequest::METHOD_POST);
$postData = [
'product' => [
'attribute_set_id' => '4',
'status' => '1',
'name' => 'Simple product',
'sku' => 'simple',
'type_id' => Type::TYPE_SIMPLE,
'quantity_and_stock_status' => [
'qty' => '10',
'is_in_stock' => '1',
],
'website_ids' => [
1 => '1',
],
'price' => '100',
],
];
$this->getRequest()
->setPostValue($postData);
$this->dispatch('backend/catalog/product/validate/');
$responseBody = $this->getResponse()
->getBody();
$message = __('The value specified in the URL Key field would generate a URL that already exists.');
$additionalInfo = __('To resolve this conflict, you can either change the value of the URL Key field '
. '(located in the Search Engine Optimization section) to a unique value, or change the Request Path fields'
. ' in all locations listed below:');
$this->assertStringContainsString((string)$message, $responseBody);
$this->assertStringContainsString((string)$additionalInfo, $responseBody);
}
}
@@ -0,0 +1,733 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Adminhtml;
use Magento\Catalog\Model\Product\Attribute\Backend\LayoutUpdate;
use Magento\Framework\Acl\Builder;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Message\Manager;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Catalog\Model\ProductRepository;
use Magento\Catalog\Model\ProductRepositoryFactory;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Catalog\Model\ProductLayoutUpdateManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Catalog\Model\Product;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\Catalog\Model\Product\Attribute\LayoutUpdateManager;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product\Attribute\Repository as ProductAttributeRepository;
/**
* Test class for Product adminhtml actions
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProductTest extends AbstractBackendController
{
/**
* @var Builder
*/
private $aclBuilder;
/**
* @var ProductRepositoryFactory
*/
private $repositoryFactory;
/**
* @var ProductResource
*/
private $resourceModel;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritDoc
*/
protected function setUp(): void
{
Bootstrap::getObjectManager()->configure([
'preferences' => [
LayoutUpdateManager::class =>
ProductLayoutUpdateManager::class
]
]);
parent::setUp();
$this->aclBuilder = Bootstrap::getObjectManager()->get(Builder::class);
$this->repositoryFactory = Bootstrap::getObjectManager()->get(ProductRepositoryFactory::class);
$this->resourceModel = Bootstrap::getObjectManager()->get(ProductResource::class);
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
}
/**
* Test calling save with invalid product's ID.
*/
public function testSaveActionWithDangerRequest()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(['product' => ['entity_id' => 15]]);
$this->dispatch('backend/catalog/product/save');
$this->assertSessionMessages(
$this->equalTo(['The product was unable to be saved. Please try again.']),
MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('/backend/catalog/product/new'));
}
/**
* Test saving existing product and specifying that we want redirect to new product form.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testSaveActionAndNew()
{
$this->getRequest()->setPostValue(['back' => 'new']);
/** @var ProductRepository $repository */
$repository = $this->repositoryFactory->create();
$product = $repository->get('simple');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertRedirect($this->stringStartsWith('http://localhost/index.php/backend/catalog/product/new/'));
$this->assertSessionMessages(
$this->containsEqual('You saved the product.'),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Test saving existing product and specifying that
* we want redirect to new product form with saved product's data applied.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testSaveActionAndDuplicate()
{
$this->getRequest()->setPostValue(['back' => 'duplicate']);
/** @var ProductRepository $repository */
$repository = $this->repositoryFactory->create();
$product = $repository->get('simple');
$this->assertSaveAndDuplicateAction($product);
$this->assertRedirect($this->stringStartsWith('http://localhost/index.php/backend/catalog/product/edit/'));
$this->assertRedirect(
$this->logicalNot(
$this->stringStartsWith(
'http://localhost/index.php/backend/catalog/product/edit/id/' . $product->getEntityId() . '/'
)
)
);
}
/**
* Tests of saving and duplicating existing product after the script execution.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testSaveActionAndDuplicateWithUrlPathAttribute()
{
/** @var ProductRepository $repository */
$repository = $this->repositoryFactory->create();
/** @var Product $product */
$product = $repository->get('simple');
// set url_path attribute and check it
$product->setData('url_path', $product->getSku());
$repository->save($product);
$urlPathAttribute = $product->getCustomAttribute('url_path');
$this->assertEquals($urlPathAttribute->getValue(), $product->getSku());
// dispatch Save&Duplicate action and check it
$this->assertSaveAndDuplicateAction($product);
}
/**
* Testing Add Product button showing.
*/
public function testIndexAction()
{
$this->dispatch('backend/catalog/product');
$body = $this->getResponse()->getBody();
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="add_new_product"]',
$body
),
'"Add Product" button container should be present on Manage Products page, if the limit is not reached'
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="add_new_product-button"]',
$body
),
'"Add Product" button should be present on Manage Products page, if the limit is not reached'
);
$this->assertEquals(
0,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="add_new_product-button" and contains(@class,"disabled")]',
$body
),
'"Add Product" button should be enabled on Manage Products page, if the limit is not reached'
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="add_new_product"]/*[contains(@class,"action-toggle")]',
$body
),
'"Add Product" button split should be present on Manage Products page, if the limit is not reached'
);
}
/**
* Testing existing product edit page.
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testEditAction()
{
/** @var ProductRepository $repository */
$repository = $this->repositoryFactory->create();
$product = $repository->get('simple');
$this->dispatch('backend/catalog/product/edit/id/' . $product->getEntityId());
$body = $this->getResponse()->getBody();
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="save-button"]',
$body
),
'"Save" button isn\'t present on Edit Product page'
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="save_and_new"]',
$body
),
'"Save & New" button isn\'t present on Edit Product page'
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="save_and_duplicate"]',
$body
),
'"Save & Duplicate" button isn\'t present on Edit Product page'
);
}
/**
* Testing product short description has Wysiwyg after creating category short_description attribute.
* @magentoDataFixture Magento/Catalog/_files/category_custom_short_description_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testProductShortDescriptionHasWysiwygEditor()
{
/** @var ProductRepository $repository */
$repository = $this->repositoryFactory->create();
$product = $repository->get('simple');
$this->dispatch('backend/catalog/product/edit/id/' . $product->getEntityId());
$body = $this->getResponse()->getBody();
$this->assertMatchesRegularExpression('/editorproduct_form_short_description/', $body);
$this->assertMatchesRegularExpression('/buttonsproduct_form_short_description/', $body);
}
/**
* Test create product with already existing url key.
*
* @dataProvider saveActionWithAlreadyExistingUrlKeyDataProvider
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation disabled
* @param array $postData
* @return void
*/
public function testSaveActionWithAlreadyExistingUrlKey(array $postData)
{
$this->getRequest()->setPostValue($postData);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save');
/** @var Manager $messageManager */
$messageManager = $this->_objectManager->get(Manager::class);
$messages = $messageManager->getMessages();
$errors = $messages->getItemsByType('error');
$this->assertNotEmpty($errors);
$message = array_shift($errors);
$this->assertSame('URL key for specified store already exists.', $message->getText());
$this->assertRedirect($this->stringContains('/backend/catalog/product/new'));
/** @var DataPersistorInterface $dataPersistor */
$dataPersistor = $this->_objectManager->get(DataPersistorInterface::class);
$productData = $dataPersistor->get('catalog_product')['product'];
$image = array_shift($productData['media_gallery']['images']);
$this->assertStringEndsNotWith('.tmp', $image['file']);
$this->assertStringEndsNotWith('.tmp', $productData['image']);
$this->assertStringEndsNotWith('.tmp', $productData['small_image']);
$this->assertStringEndsNotWith('.tmp', $productData['thumbnail']);
$this->assertStringEndsNotWith('.tmp', $productData['swatch_image']);
}
/**
* Provide test data for testSaveActionWithAlreadyExistingUrlKey().
*
* @return array
*/
public function saveActionWithAlreadyExistingUrlKeyDataProvider()
{
return [
[
'post_data' => [
'product' =>
[
'attribute_set_id' => '4',
'status' => '1',
'name' => 's2',
'url_key' => 'simple-product',
'quantity_and_stock_status' =>
[
'qty' => '10',
'is_in_stock' => '1',
],
'website_ids' =>
[
1 => '1',
],
'sku' => 's2',
'price' => '3',
'tax_class_id' => '2',
'product_has_weight' => '0',
'visibility' => '4',
'media_gallery' =>
[
'images' =>
[
'h17hftqohrd' =>
[
'position' => '1',
'media_type' => 'image',
'video_provider' => '',
'file' => '/m/a//magento_image.jpg.tmp',
'value_id' => '',
'label' => '',
'disabled' => '0',
'removed' => '',
'role' => '',
],
],
],
'image' => '/m/a//magento_image.jpg.tmp',
'small_image' => '/m/a//magento_image.jpg.tmp',
'thumbnail' => '/m/a//magento_image.jpg.tmp',
'swatch_image' => '/m/a//magento_image.jpg.tmp',
],
]
]
];
}
/**
* Test product save with selected tier price
*
* @dataProvider saveActionTierPriceDataProvider
* @param array $postData
* @param array $tierPrice
* @magentoDataFixture Magento/Catalog/_files/product_has_tier_price_show_as_low_as.php
* @magentoConfigFixture current_store catalog/price/scope 1
*/
public function testSaveActionTierPrice(array $postData, array $tierPrice)
{
$postData['product'] = $this->getProductData($tierPrice);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/catalog/product/save/id/' . $postData['id']);
$this->assertSessionMessages(
$this->containsEqual('You saved the product.'),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Provide test data for testSaveActionWithAlreadyExistingUrlKey().
*
* @return array
*/
public function saveActionTierPriceDataProvider()
{
return [
[
'post_data' => [
'id' => '1',
'type' => 'simple',
'store' => '0',
'set' => '4',
'back' => 'edit',
'product' => [],
'is_downloadable' => '0',
'affect_configurable_product_attributes' => '1',
'new_variation_attribute_set_id' => '4',
'use_default' => [
'gift_message_available' => '0',
'gift_wrapping_available' => '0'
],
'configurable_matrix_serialized' => '[]',
'associated_product_ids_serialized' => '[]'
],
'tier_price_for_request' => [
[
'price_id' => '1',
'website_id' => '0',
'cust_group' => '32000',
'price' => '111.00',
'price_qty' => '100',
'website_price' => '111.0000',
'initialize' => 'true',
'record_id' => '1',
'value_type' => 'fixed'
],
[
'price_id' => '2',
'website_id' => '1',
'cust_group' => '32000',
'price' => '222.00',
'price_qty' => '200',
'website_price' => '111.0000',
'initialize' => 'true',
'record_id' => '2',
'value_type' => 'fixed'
],
[
'price_id' => '3',
'website_id' => '1',
'cust_group' => '32000',
'price' => '333.00',
'price_qty' => '300',
'website_price' => '111.0000',
'initialize' => 'true',
'record_id' => '3',
'value_type' => 'fixed'
]
]
]
];
}
/**
* Return product data for test without entity_id for further save
*
* @param array $tierPrice
* @return array
*/
private function getProductData(array $tierPrice)
{
/** @var ProductRepository $repo */
$repo = $this->repositoryFactory->create();
$product = $repo->get('tier_prices')->getData();
$product['tier_price'] = $tierPrice;
$product['entity_id'] = null;
/** @phpstan-ignore-next-line */
unset($product['entity_id']);
return $product;
}
/**
* Check whether additional authorization is required for the design fields.
*
* @magentoDbIsolation enabled
* @throws \Throwable
* @return void
*/
public function testSaveDesign(): void
{
$requestData = [
'product' => [
'type' => 'simple',
'sku' => 'simple',
'store' => '0',
'set' => '4',
'back' => 'edit',
'type_id' => Type::TYPE_SIMPLE,
'product' => [],
'is_downloadable' => '0',
'affect_configurable_product_attributes' => '1',
'new_variation_attribute_set_id' => '4',
'use_default' => [
'gift_message_available' => '0',
'gift_wrapping_available' => '0'
],
'configurable_matrix_serialized' => '[]',
'associated_product_ids_serialized' => '[]'
]
];
$uri = 'backend/catalog/product/save';
//Trying to update product's design settings without proper permissions.
//Expected list of sessions messages collected throughout the controller calls.
$sessionMessages = ['Not allowed to edit the product\'s design attributes'];
$this->aclBuilder->getAcl()->deny(
\Magento\TestFramework\Bootstrap::ADMIN_ROLE_ID,
'Magento_Catalog::edit_product_design'
);
$requestData['product']['custom_design'] = '1';
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($uri);
$this->assertSessionMessages(
self::equalTo($sessionMessages),
MessageInterface::TYPE_ERROR
);
//Trying again with the permissions.
$this->aclBuilder->getAcl()->allow(
\Magento\TestFramework\Bootstrap::ADMIN_ROLE_ID,
['Magento_Catalog::products', 'Magento_Catalog::edit_product_design']
);
$this->getRequest()->setDispatched(false);
$this->dispatch($uri);
/** @var ProductRepository $repo */
$repo = $this->repositoryFactory->create();
$product = $repo->get('simple');
$this->assertNotEmpty($product->getCustomDesign());
$this->assertEquals(1, $product->getCustomDesign());
//No new error messages
$this->assertSessionMessages(
self::equalTo($sessionMessages),
MessageInterface::TYPE_ERROR
);
}
/**
* Save design without the permissions but with default values.
*
* @magentoDbIsolation enabled
* @throws \Throwable
* @return void
*/
public function testSaveDesignWithDefaults(): void
{
$optionsContainerDefault = $this->resourceModel->getAttribute('options_container')->getDefaultValue();
$requestData = [
'product' => [
'type' => 'simple',
'sku' => 'simple',
'store' => '0',
'set' => '4',
'back' => 'edit',
'product' => [],
'type_id' => Type::TYPE_SIMPLE,
'is_downloadable' => '0',
'affect_configurable_product_attributes' => '1',
'new_variation_attribute_set_id' => '4',
'use_default' => [
'gift_message_available' => '0',
'gift_wrapping_available' => '0'
],
'configurable_matrix_serialized' => '[]',
'associated_product_ids_serialized' => '[]',
'options_container' => $optionsContainerDefault
]
];
$uri = 'backend/catalog/product/save';
//Updating product's design settings without proper permissions.
$this->aclBuilder->getAcl()->deny(
\Magento\TestFramework\Bootstrap::ADMIN_ROLE_ID,
'Magento_Catalog::edit_product_design'
);
//Testing that special "No Update" value is treated as no change.
$requestData['product']['custom_layout_update_file'] = LayoutUpdate::VALUE_NO_UPDATE;
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($uri);
//Validating saved entity.
/** @var ProductRepository $repo */
$repo = $this->repositoryFactory->create();
$product = $repo->get('simple');
$this->assertNotNull($product->getData('options_container'));
$this->assertEquals($optionsContainerDefault, $product->getData('options_container'));
}
/**
* Test custom update files functionality.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation disabled
* @throws \Throwable
* @return void
*/
public function testSaveCustomLayout(): void
{
$file = 'test_file';
/** @var ProductRepository $repo */
$repo = $this->repositoryFactory->create();
$product = $repo->get('simple');
/** @var ProductLayoutUpdateManager $layoutManager */
$layoutManager = Bootstrap::getObjectManager()->get(ProductLayoutUpdateManager::class);
$layoutManager->setFakeFiles((int)$product->getId(), [$file]);
$productData = $product->getData();
unset($productData['options']);
unset($productData[$product->getIdFieldName()]);
$requestData = [
'product' => $productData
];
$uri = 'backend/catalog/product/save';
//Saving a wrong file
$requestData['product']['custom_layout_update_file'] = $file . 'INVALID';
$this->getRequest()->setDispatched(false);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->getRequest()->setParam('id', $product->getId());
$this->dispatch($uri);
$this->assertSessionMessages(
self::equalTo(['Selected layout update is not available']),
MessageInterface::TYPE_ERROR
);
//Checking that the value is not saved
/** @var ProductRepository $repo */
$repo = $this->repositoryFactory->create();
$product = $repo->get('simple');
$this->assertEmpty($product->getData('custom_layout_update_file'));
//Saving the correct file
$requestData['product']['custom_layout_update_file'] = $file;
$this->getRequest()->setDispatched(false);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->getRequest()->setParam('id', $product->getId());
$this->dispatch($uri);
//Checking that the value is saved
/** @var ProductRepository $repo */
$repo = $this->repositoryFactory->create();
$product = $repo->get('simple');
$this->assertEquals($file, $product->getData('custom_layout_update_file'));
}
/**
* Dispatch Save&Duplicate action and check it
*
* @param Product $product
*/
private function assertSaveAndDuplicateAction(Product $product)
{
$this->getRequest()->setPostValue(['back' => 'duplicate']);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertSessionMessages(
$this->containsEqual('You saved the product.'),
MessageInterface::TYPE_SUCCESS
);
$this->assertSessionMessages(
$this->containsEqual('You duplicated the product.'),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Provide test data for testSaveActionWithInvalidUrlKey()
*
* @return array
*/
public function saveActionWithInvalidUrlKeyDataProvider()
{
return [
[
'post_data' => [
'product' =>
[
'attribute_set_id' => '4',
'status' => '1',
'name' => 'simple_with_invalid_url',
'url_key' => 'graphql',
'quantity_and_stock_status' =>
[
'qty' => '10',
'is_in_stock' => '1',
],
'website_ids' =>
[
1 => '1',
],
'sku' => 'simple_with_invalid_url',
'price' => '3',
'tax_class_id' => '2',
'product_has_weight' => '0',
'visibility' => '4',
],
],
]
];
}
/**
* Test create product with invalid existing url key.
*
* @dataProvider saveActionWithInvalidUrlKeyDataProvider
* @magentoDbIsolation disabled
* @param array $postData
* @return void
*/
public function testSaveActionWithInvalidUrlKey(array $postData)
{
$identifier = 'graphql';
$reservedWords = 'admin, soap, rest, graphql, standard';
$this->getRequest()->setPostValue($postData);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save');
/** @var Manager $messageManager */
$messageManager = $this->_objectManager->get(Manager::class);
$messages = $messageManager->getMessages();
$errors = $messages->getItemsByType('error');
$this->assertNotEmpty($errors);
$message = array_shift($errors);
$this->assertSame(
sprintf(
'URL key "%s" matches a reserved endpoint name (%s). Use another URL key.',
$identifier,
$reservedWords
),
$message->getText()
);
$this->assertRedirect($this->stringContains('/backend/catalog/product/new'));
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_product.php
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
*/
public function testSaveProductWithDeletedCategory(): void
{
$category = $this->_objectManager->get(Category::class);
$category->load(333);
$category->delete();
$product = $this->productRepository->get('simple333');
$this->productRepository->save($product);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/catalog/product/save/id/' . $product->getEntityId());
$this->assertSessionMessages(
$this->equalTo([(string)__('You saved the product.')]),
MessageInterface::TYPE_SUCCESS
);
}
}
@@ -0,0 +1,199 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Category;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Layer\Category;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Catalog\Model\Session as CatalogSession;
use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Response\Http;
use Magento\Framework\Registry;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Request;
use Magento\TestFramework\Response;
use Magento\TestFramework\Store\ExecuteInStoreContext;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Checks category availability on storefront by url rewrite
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @magentoDbIsolation enabled
*/
class CategoryUrlRewriteTest extends AbstractController
{
/** @var Registry */
private $registry;
/** @var ScopeConfigInterface */
private $config;
/** @var string */
private $categoryUrlSuffix;
/** @var StoreManagerInterface */
private $storeManager;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var CatalogSession */
private $catalogSession;
/** @var ExecuteInStoreContext */
private $executeInStoreContext;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->config = $this->_objectManager->get(ScopeConfigInterface::class);
$this->registry = $this->_objectManager->get(Registry::class);
$this->categoryUrlSuffix = $this->config->getValue(
CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX,
ScopeInterface::SCOPE_STORE
);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->categoryRepository = $this->_objectManager->get(CategoryRepositoryInterface::class);
$this->catalogSession = $this->_objectManager->get(CatalogSession::class);
$this->executeInStoreContext = $this->_objectManager->get(ExecuteInStoreContext::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @dataProvider categoryRewriteProvider
* @param int $categoryId
* @param string $urlPath
* @return void
*/
public function testCategoryUrlRewrite(int $categoryId, string $urlPath): void
{
$this->dispatch(sprintf($urlPath, $this->categoryUrlSuffix));
$currentCategory = $this->registry->registry('current_category');
$response = $this->getResponse();
$this->assertEquals(
Http::STATUS_CODE_200,
$response->getHttpResponseCode(),
'Response code does not match expected value'
);
$this->assertNotNull($currentCategory);
$this->assertEquals($categoryId, $currentCategory->getId());
}
/**
* @return array
*/
public function categoryRewriteProvider(): array
{
return [
[
'category_id' => 400,
'url_path' => '/category-1%s',
],
[
'category_id' => 401,
'url_path' => '/category-1/category-1-1%s',
],
[
'category_id' => 402,
'url_path' => '/category-1/category-1-1/category-1-1-1%s',
],
];
}
/**
* Test category url on different store view
*
* @magentoDataFixture Magento/Catalog/_files/category.php
* @magentoDataFixture Magento/Store/_files/store.php
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @return void
*/
public function testCategoryUrlOnStoreView(): void
{
$id = 333;
$secondStoreUrlKey = 'category-1-second';
$currentStore = $this->storeManager->getStore();
$secondStore = $this->storeManager->getStore('test');
$this->executeInStoreContext->execute(
$secondStore,
[$this, 'updateCategoryUrlKey'],
$id,
(int)$secondStore->getId(),
$secondStoreUrlKey
);
$url = sprintf('/' . $secondStoreUrlKey . '%s', $this->categoryUrlSuffix);
$this->executeInStoreContext->execute($secondStore, [$this, 'dispatch'], $url);
$this->assertCategoryIsVisible();
$this->assertEquals(
$secondStoreUrlKey,
$this->categoryRepository->get($id, (int)$secondStore->getId())->getUrlKey(),
'Wrong category is registered'
);
$this->cleanUpCachedObjects();
$defaultStoreUrlKey = $this->categoryRepository->get($id, $currentStore->getId())->getUrlKey();
$this->dispatch(sprintf($defaultStoreUrlKey . '%s', $this->categoryUrlSuffix));
$this->assertCategoryIsVisible();
}
/**
* Assert that category is available in storefront
*
* @return void
*/
private function assertCategoryIsVisible(): void
{
$this->assertEquals(
Response::STATUS_CODE_200,
$this->getResponse()->getHttpResponseCode(),
'Wrong response code is returned'
);
$this->assertNotNull((int)$this->catalogSession->getData('last_viewed_category_id'));
}
/**
* Clean up cached objects
*
* @return void
*/
private function cleanUpCachedObjects(): void
{
$this->catalogSession->clearStorage();
$this->registry->unregister('current_category');
$this->registry->unregister('category');
$this->_objectManager->removeSharedInstance(Request::class);
$this->_objectManager->removeSharedInstance(Response::class);
$this->_objectManager->removeSharedInstance(Resolver::class);
$this->_objectManager->removeSharedInstance(Category::class);
$this->_objectManager->removeSharedInstance('categoryFilterList');
$this->_response = null;
$this->_request = null;
}
/**
* Update category url key
*
* @param int $id
* @param int $storeId
* @param string $categoryUrlKey
* @return void
*/
public function updateCategoryUrlKey(int $id, int $storeId, string $categoryUrlKey): void
{
$category = $this->categoryRepository->get($id, $storeId);
$category->setUrlKey($categoryUrlKey);
$this->categoryRepository->save($category);
}
}
@@ -0,0 +1,293 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Category\Attribute\LayoutUpdateManager;
use Magento\Catalog\Model\Product\ProductList\Toolbar as ToolbarModel;
use Magento\Catalog\Model\ResourceModel\Category\Collection;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Catalog\Model\Session;
use Magento\Framework\App\Http\Context;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\Catalog\Model\CategoryLayoutUpdateManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Responsible for testing category view action on strorefront.
*
* @see \Magento\Catalog\Controller\Category\View
* @magentoAppArea frontend
*/
class CategoryTest extends AbstractController
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Registry
*/
private $registry;
/**
* @var Session
*/
private $session;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var Context
*/
private $httpContext;
/**
* @var CollectionFactory
*/
private $categoryCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->configure([
'preferences' => [LayoutUpdateManager::class => CategoryLayoutUpdateManager::class]
]);
$this->categoryCollectionFactory = $this->objectManager->create(CollectionFactory::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->session = $this->objectManager->get(Session::class);
$this->httpContext = $this->objectManager->get(Context::class);
}
/**
* @inheritdoc
*/
public function assert404NotFound()
{
parent::assert404NotFound();
$this->assertNull($this->registry->registry('current_category'));
}
/**
* @return array
*/
public function getViewActionDataProvider(): array
{
return [
'category without children' => [
'categoryId' => 5,
['catalog_category_view_type_layered', 'catalog_category_view_type_layered_without_children'],
[
'%acategorypath-category-1-category-1-1-category-1-1-1%a',
'%acategory-category-1-1-1%a',
'%a<title>Category 1.1.1 - Category 1.1 - Category 1</title>%a',
'%a<h1%a>%SCategory 1.1.1%S</h1>%a',
'%aSimple Product Two%a',
'%a$45.67%a'
],
],
'anchor category' => [
'categoryId' => 4,
['catalog_category_view_type_layered'],
[
'%acategorypath-category-1-category-1-1%a',
'%acategory-category-1-1%a',
'%a<title>Category 1.1 - Category 1</title>%a',
'%a<h1%a>%SCategory 1.1%S</h1>%a',
'%aSimple Product%a',
'%a$10.00%a',
'%aSimple Product Two%a',
'%a$45.67%a'
],
]
];
}
/**
* @dataProvider getViewActionDataProvider
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_product_ids.php
* @magentoDbIsolation disabled
* @param int $categoryId
* @param array $expectedHandles
* @param array $expectedContent
* @return void
*/
public function testViewAction(int $categoryId, array $expectedHandles, array $expectedContent): void
{
$this->dispatch("catalog/category/view/id/{$categoryId}");
/** @var $currentCategory Category */
$currentCategory = $this->registry->registry('current_category');
$this->assertInstanceOf(Category::class, $currentCategory);
$this->assertEquals($categoryId, $currentCategory->getId(), 'Category in registry.');
$lastCategoryId = $this->session->getLastVisitedCategoryId();
$this->assertEquals($categoryId, $lastCategoryId, 'Last visited category.');
/* Layout updates */
$handles = $this->layout->getUpdate()->getHandles();
foreach ($expectedHandles as $expectedHandleName) {
$this->assertContains($expectedHandleName, $handles);
}
$responseBody = $this->getResponse()->getBody();
/* Response content */
foreach ($expectedContent as $expectedText) {
$this->assertStringMatchesFormat($expectedText, $responseBody);
}
}
/**
* @return void
*/
public function testViewActionNoCategoryId(): void
{
$this->dispatch('catalog/category/view/');
$this->assert404NotFound();
}
/**
* @return void
*/
public function testViewActionNotExistingCategory(): void
{
$this->dispatch('catalog/category/view/id/8');
$this->assert404NotFound();
}
/**
* Checks that disabled category is not available in storefront
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Catalog/_files/inactive_category.php
* @return void
*/
public function testViewActionDisabledCategory(): void
{
$this->dispatch('catalog/category/view/id/111');
$this->assert404NotFound();
}
/**
* Check that custom layout update files is employed.
*
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_product_ids.php
* @return void
*/
public function testViewWithCustomUpdate(): void
{
//Setting a fake file for the category.
$file = 'test-file';
$categoryId = 5;
/** @var CategoryLayoutUpdateManager $layoutManager */
$layoutManager = Bootstrap::getObjectManager()->get(CategoryLayoutUpdateManager::class);
$layoutManager->setCategoryFakeFiles($categoryId, [$file]);
/** @var CategoryRepositoryInterface $categoryRepo */
$categoryRepo = Bootstrap::getObjectManager()->create(CategoryRepositoryInterface::class);
$category = $categoryRepo->get($categoryId);
//Updating the custom attribute.
$category->setCustomAttribute('custom_layout_update_file', $file);
$categoryRepo->save($category);
//Viewing the category
$this->dispatch("catalog/category/view/id/$categoryId");
//Layout handles must contain the file.
$handles = Bootstrap::getObjectManager()->get(\Magento\Framework\View\LayoutInterface::class)
->getUpdate()
->getHandles();
$this->assertContains("catalog_category_view_selectable_{$categoryId}_{$file}", $handles);
}
/**
* Checks that pagination value can be changed to a new one if remember pagination enabled and already have saved
* some value
*
* @magentoDataFixture Magento/Catalog/_files/category.php
* @magentoConfigFixture default/catalog/frontend/remember_pagination 1
*
* @return void
*/
public function testViewWithRememberPaginationAndPreviousValue(): void
{
$this->session->setData(ToolbarModel::LIMIT_PARAM_NAME, 16);
$newPaginationValue = 24;
$this->getRequest()->setParams([ToolbarModel::LIMIT_PARAM_NAME => $newPaginationValue]);
$this->dispatch("catalog/category/view/id/333");
$block = $this->layout->getBlock('product_list_toolbar');
$this->assertNotFalse($block);
$this->assertEquals($newPaginationValue, $block->getLimit());
$this->assertEquals($newPaginationValue, $this->session->getData(ToolbarModel::LIMIT_PARAM_NAME));
$this->assertEquals($newPaginationValue, $this->httpContext->getValue(ToolbarModel::LIMIT_PARAM_NAME));
}
/**
* Test to generate category page without duplicate html element ids
*
* @magentoDataFixture Magento/Catalog/_files/category_with_three_products.php
* @magentoDataFixture Magento/Catalog/_files/catalog_category_product_reindex_all.php
* @magentoDataFixture Magento/Catalog/_files/catalog_product_category_reindex_all.php
* @magentoDbIsolation disabled
*/
public function testViewWithoutDuplicateHmlElementIds(): void
{
$category = $this->loadCategory('Category 999', Store::DEFAULT_STORE_ID);
$this->dispatch('catalog/category/view/id/' . $category->getId());
$responseHtml = $this->getResponse()->getBody();
$htmlElementIds = ['modes-label', 'mode-list', 'toolbar-amount', 'sorter', 'limiter'];
foreach ($htmlElementIds as $elementId) {
$matches = [];
$idAttribute = "id=\"$elementId\"";
preg_match_all("/$idAttribute/mx", $responseHtml, $matches);
$this->assertCount(1, $matches[0]);
$this->assertEquals($idAttribute, $matches[0][0]);
}
}
/**
* Loads category by id
*
* @param string $categoryName
* @param int $storeId
* @return CategoryInterface
*/
private function loadCategory(string $categoryName, int $storeId): CategoryInterface
{
/** @var Collection $categoryCollection */
$categoryCollection = $this->categoryCollectionFactory->create();
/** @var CategoryInterface $category */
$category = $categoryCollection->setStoreId($storeId)
->addAttributeToSelect('display_mode', 'left')
->addAttributeToFilter(CategoryInterface::KEY_NAME, $categoryName)
->setPageSize(1)
->getFirstItem();
$category->setStoreId($storeId);
return $category;
}
}
@@ -0,0 +1,20 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Test class for \Magento\Catalog\Controller\Index.
*/
namespace Magento\Catalog\Controller;
class IndexTest extends \Magento\TestFramework\TestCase\AbstractController
{
public function testIndexAction()
{
$this->dispatch('catalog/index');
$this->assertRedirect();
}
}
@@ -0,0 +1,543 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Controller\Product;
use Laminas\Stdlib\ParametersFactory;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Visitor;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Test compare product.
*
* @magentoDataFixture Magento/Catalog/controllers/_files/products.php
* @magentoDbIsolation disabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CompareTest extends AbstractController
{
/** @var ProductRepository */
protected $productRepository;
/** @var FormKey */
private $formKey;
/** @var Session */
private $customerSession;
/** @var Visitor */
private $visitor;
/** @var ParametersFactory */
private $parametersFactory;
/** @var Registry */
private $registry;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->formKey = $this->_objectManager->get(FormKey::class);
$this->productRepository = $this->_objectManager->get(ProductRepository::class);
$this->customerSession = $this->_objectManager->get(Session::class);
$this->visitor = $this->_objectManager->get(Visitor::class);
$this->parametersFactory = $this->_objectManager->get(ParametersFactory::class);
$this->registry = $this->_objectManager->get(Registry::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->customerSession->logout();
$this->visitor->setId(null);
parent::tearDown();
}
/**
* Test adding product to compare list.
*
* @return void
*/
public function testAddAction(): void
{
$this->_requireVisitorWithNoProducts();
$product = $this->productRepository->get('simple_product_1');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch(
sprintf(
'catalog/product_compare/add/product/%s/form_key/%s?nocookie=1',
$product->getEntityId(),
$this->formKey->getFormKey()
)
);
$this->assertSessionMessages(
$this->equalTo(
[
'You added product Simple Product 1 Name to the ' .
'<a href="http://localhost/index.php/catalog/product_compare/">comparison list</a>.'
]
),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect();
$this->_assertCompareListEquals([$product->getEntityId()]);
}
/**
* Test adding disabled product to compare list.
*
* @return void
*/
public function testAddActionForDisabledProduct(): void
{
$this->_requireVisitorWithNoProducts();
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->setProductDisabled('simple_product_1');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch(
sprintf(
'catalog/product_compare/add/product/%s/form_key/%s?nocookie=1',
$product->getEntityId(),
$this->formKey->getFormKey()
)
);
$this->assertRedirect();
$this->_assertCompareListEquals([]);
}
/**
* Test removing a product from compare list.
*
* @return void
*/
public function testRemoveAction(): void
{
$this->_requireVisitorWithTwoProducts();
$product = $this->productRepository->get('simple_product_2');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('catalog/product_compare/remove/product/' . $product->getEntityId());
$this->assertSessionMessages(
$this->equalTo(['You removed product Simple Product 2 Name from the comparison list.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect();
$restProduct = $this->productRepository->get('simple_product_1');
$this->_assertCompareListEquals([$restProduct->getEntityId()]);
}
/**
* Test removing a disabled product from compare list.
*
* @return void
*/
public function testRemoveActionForDisabledProduct(): void
{
$this->_requireVisitorWithTwoProducts();
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->setProductDisabled('simple_product_1');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('catalog/product_compare/remove/product/' . $product->getEntityId());
$this->assertRedirect();
$restProduct = $this->productRepository->get('simple_product_2');
$this->_assertCompareListEquals([$product->getEntityId(), $restProduct->getEntityId()]);
}
/**
* Test removing a product from compare list of a registered customer.
*
* @return void
*/
public function testRemoveActionWithSession(): void
{
$this->_requireCustomerWithTwoProducts();
$product = $this->productRepository->get('simple_product_1');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('catalog/product_compare/remove/product/' . $product->getEntityId());
$secondProduct = $this->productRepository->get('simple_product_2');
$this->assertSessionMessages(
$this->equalTo(['You removed product Simple Product 1 Name from the comparison list.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect();
$this->_assertCompareListEquals([$secondProduct->getEntityId()]);
}
/**
* Test getting a list of compared product.
*
* @return void
*/
public function testIndexActionDisplay(): void
{
$this->_requireVisitorWithTwoProducts();
$layout = $this->_objectManager->get(\Magento\Framework\View\LayoutInterface::class);
$layout->setIsCacheable(false);
$this->dispatch('catalog/product_compare/index');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('Products Comparison List', $responseBody);
$this->assertStringContainsString('simple_product_1', $responseBody);
$this->assertStringContainsString('Simple Product 1 Name', $responseBody);
$this->assertStringContainsString('Simple Product 1 Full Description', $responseBody);
$this->assertStringContainsString('Simple Product 1 Short Description', $responseBody);
$this->assertStringContainsString('$1,234.56', $responseBody);
$this->assertStringContainsString('simple_product_2', $responseBody);
$this->assertStringContainsString('Simple Product 2 Name', $responseBody);
$this->assertStringContainsString('Simple Product 2 Full Description', $responseBody);
$this->assertStringContainsString('Simple Product 2 Short Description', $responseBody);
$this->assertStringContainsString('$987.65', $responseBody);
}
/**
* Test clearing a list of compared products.
*
* @return void
*/
public function testClearAction(): void
{
$this->_requireVisitorWithTwoProducts();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('catalog/product_compare/clear');
$this->assertSessionMessages(
$this->equalTo(['You cleared the comparison list.']),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect();
$this->_assertCompareListEquals([]);
}
/**
* Test escaping a session message.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_xss.php
* @return void
*/
public function testRemoveActionProductNameXss(): void
{
$this->_prepareCompareListWithProductNameXss();
$product = $this->productRepository->get('product-with-xss');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('catalog/product_compare/remove/product/' . $product->getEntityId() . '?nocookie=1');
$this->assertSessionMessages(
$this->equalTo(
['You removed product &lt;script&gt;alert(&quot;xss&quot;);&lt;/script&gt; from the comparison list.']
),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Test removing a product wich does not exist from compare list.
*
* @return void
*/
public function testRemoveActionWithNonExistentProduct(): void
{
$this->_requireVisitorWithTwoProducts();
$removedProduct = $this->productRepository->get('simple_product_1');
$redirectUrl = 'http://localhost/index.php/catalog/product_compare/index';
$this->assertTrue($this->deleteProduct($removedProduct), "The product must be removed.");
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams(['product' => $removedProduct->getId()]);
$server = $this->getRequest()->getServer();
$server['HTTP_REFERER'] = $redirectUrl;
$this->getRequest()->setServer($server);
$this->dispatch('catalog/product_compare/remove/');
$this->assertSessionMessages($this->isEmpty());
$this->assertRedirect($this->equalTo($redirectUrl));
$restProduct = $this->productRepository->get('simple_product_2');
$this->_assertCompareListEquals([$restProduct->getId()]);
}
/**
* Add not existing product to list of compared.
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Customer/_files/customer.php
* @return void
*/
public function testAddNotExistingProductToCompareList(): void
{
$this->customerSession->loginById(1);
$this->prepareReferer();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams(['product' => 787586534]);
$this->dispatch('catalog/product_compare/add/');
$this->assertSessionMessages($this->isEmpty());
$this->_assertCompareListEquals([]);
$this->assertRedirect($this->stringContains('not_existing'));
}
/**
* Prepare referer to test.
*
* @return void
*/
private function prepareReferer(): void
{
$parameters = $this->parametersFactory->create();
$parameters->set('HTTP_REFERER', 'http://localhost/not_existing');
$this->getRequest()->setServer($parameters);
}
/**
* Set product status disabled.
*
* @param string $sku
* @return \Magento\Catalog\Api\Data\ProductInterface
*/
private function setProductDisabled(string $sku): \Magento\Catalog\Api\Data\ProductInterface
{
$product = $this->productRepository->get($sku);
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED)
->save();
return $product;
}
/**
* Preparing compare list.
*
* @return void
*/
protected function _prepareCompareListWithProductNameXss(): void
{
/** @var $visitor \Magento\Customer\Model\Visitor */
$visitor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Visitor::class);
/** @var \Magento\Framework\Stdlib\DateTime $dateTime */
// phpcs:ignore
$visitor->setSessionId(md5(time()) . md5(microtime()))
->setLastVisitAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT))
->save();
/** @var $item \Magento\Catalog\Model\Product\Compare\Item */
$item = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product\Compare\Item::class
);
$firstProductEntityId = $this->productRepository->get('product-with-xss')->getEntityId();
$item->setVisitorId($visitor->getId())->setProductId($firstProductEntityId)->save();
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Customer\Model\Visitor::class
)->load(
$visitor->getId()
);
}
/**
* Preparing compare list.
*
* @return void
*/
protected function _requireVisitorWithNoProducts(): void
{
/** @var $visitor \Magento\Customer\Model\Visitor */
$visitor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Visitor::class);
// phpcs:ignore
$visitor->setSessionId(md5(time()) . md5(microtime()))
->setLastVisitAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT))
->save();
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Customer\Model\Visitor::class
)->load(
$visitor->getId()
);
$this->_assertCompareListEquals([]);
}
/**
* Preparing compare list.
*
* @return void
*/
protected function _requireVisitorWithTwoProducts(): void
{
/** @var $visitor \Magento\Customer\Model\Visitor */
$visitor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Visitor::class);
// phpcs:ignore
$visitor->setSessionId(md5(time()) . md5(microtime()))
->setLastVisitAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT))
->save();
/** @var $item \Magento\Catalog\Model\Product\Compare\Item */
$item = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product\Compare\Item::class
);
$firstProductEntityId = $this->productRepository->get('simple_product_1')->getEntityId();
$secondProductEntityId = $this->productRepository->get('simple_product_2')->getEntityId();
$item->setVisitorId($visitor->getId())->setProductId($firstProductEntityId)->save();
/** @var $item \Magento\Catalog\Model\Product\Compare\Item */
$item = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product\Compare\Item::class
);
$item->setVisitorId($visitor->getId())->setProductId($secondProductEntityId)->save();
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Customer\Model\Visitor::class
)->load(
$visitor->getId()
);
$this->_assertCompareListEquals([$firstProductEntityId, $secondProductEntityId]);
}
/**
* Preparing a compare list.
*
* @return void
*/
protected function _requireCustomerWithTwoProducts(): void
{
$customer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Customer::class);
/** @var \Magento\Customer\Model\Customer $customer */
$customer
->setWebsiteId(1)
->setId(1)
->setEntityTypeId(1)
->setAttributeSetId(1)
->setEmail('customer@example.com')
->setPassword('password')
->setGroupId(1)
->setStoreId(1)
->setIsActive(1)
->setFirstname('Firstname')
->setLastname('Lastname')
->setDefaultBilling(1)
->setDefaultShipping(1);
$customer->isObjectNew(true);
$customer->save();
/** @var $session \Magento\Customer\Model\Session */
$session = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Customer\Model\Session::class);
$session->setCustomerId(1);
/** @var $visitor \Magento\Customer\Model\Visitor */
$visitor = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Customer\Model\Visitor::class);
// phpcs:ignore
$visitor->setSessionId(md5(time()) . md5(microtime()))
->setLastVisitAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT))
->save();
$firstProductEntityId = $this->productRepository->get('simple_product_1')->getEntityId();
$secondProductEntityId = $this->productRepository->get('simple_product_2')->getEntityId();
/** @var $item \Magento\Catalog\Model\Product\Compare\Item */
$item = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Catalog\Model\Product\Compare\Item::class);
$item->setVisitorId($visitor->getId())
->setCustomerId(1)
->setProductId($firstProductEntityId)
->save();
/** @var $item \Magento\Catalog\Model\Product\Compare\Item */
$item = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Catalog\Model\Product\Compare\Item::class);
$item->setVisitorId($visitor->getId())
->setProductId($secondProductEntityId)
->save();
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Customer\Model\Visitor::class)
->load($visitor->getId());
$this->_assertCompareListEquals([$firstProductEntityId, $secondProductEntityId]);
}
/**
* Assert that current visitor has exactly expected products in compare list
*
* @param array $expectedProductIds
* @return void
*/
protected function _assertCompareListEquals(array $expectedProductIds): void
{
/** @var $compareItems \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\Collection */
$compareItems = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\ResourceModel\Product\Compare\Item\Collection::class
);
$compareItems->useProductItem();
// important
$compareItems->setVisitorId(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Customer\Model\Visitor::class
)->getId()
);
$actualProductIds = [];
foreach ($compareItems as $compareItem) {
/** @var $compareItem \Magento\Catalog\Model\Product\Compare\Item */
$actualProductIds[] = $compareItem->getProductId();
}
$this->assertEquals($expectedProductIds, $actualProductIds, "Products in current visitor's compare list.");
}
/**
* Delete product in secure area
*
* @param ProductInterface $product
* @return bool
*/
private function deleteProduct(ProductInterface $product): bool
{
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
try {
$result = $this->productRepository->delete($product);
} catch (\Exception $e) {
$result = false;
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
return $result;
}
}
@@ -0,0 +1,209 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Product;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Registry;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Request;
use Magento\TestFramework\Response;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Checks product availability on storefront by url rewrite
*
* @magentoDbIsolation enabled
*/
class ProductUrlRewriteTest extends AbstractController
{
/** @var ScopeConfigInterface */
private $config;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Registry */
private $registry;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var StoreManagerInterface */
private $storeManager;
/** @var string */
private $urlSuffix;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->config = $this->_objectManager->get(ScopeConfigInterface::class);
$this->productRepository = $this->_objectManager->create(ProductRepositoryInterface::class);
$this->registry = $this->_objectManager->get(Registry::class);
$this->categoryRepository = $this->_objectManager->create(CategoryRepositoryInterface::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->urlSuffix = $this->config->getValue(
ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX,
ScopeInterface::SCOPE_STORE
);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testProductUrlRewrite(): void
{
$product = $this->productRepository->get('simple2');
$url = $this->prepareUrl($product->getUrlKey());
$this->dispatch($url);
$this->assertProductIsVisible($product);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/category_product.php
* @return void
*/
public function testCategoryProductUrlRewrite(): void
{
$category = $this->categoryRepository->get(333);
$product = $this->productRepository->get('simple333');
$url = $this->prepareUrl($category->getUrlKey(), false) . $this->prepareUrl($product->getUrlKey());
$this->dispatch($url);
$this->assertProductIsVisible($product);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testProductRedirect(): void
{
$product = $this->productRepository->get('simple2');
$oldUrl = $this->prepareUrl($product->getUrlKey());
$data = [
'url_key' => 'new-url-key',
'url_key_create_redirect' => $product->getUrlKey(),
'save_rewrites_history' => true,
];
$this->updateProduct($product, $data);
$this->dispatch($oldUrl);
$this->assertRedirect($this->stringContains($this->prepareUrl('new-url-key')));
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testMultistoreProductUrlRewrite(): void
{
$currentStore = $this->storeManager->getStore();
$product = $this->productRepository->get('simple2');
$firstStoreUrl = $this->prepareUrl($product->getUrlKey());
$secondStoreId = $this->storeManager->getStore('fixturestore')->getId();
$this->storeManager->setCurrentStore($secondStoreId);
try {
$product = $this->updateProduct($product, ['url_key' => 'second-store-url-key']);
$this->assertEquals('second-store-url-key', $product->getUrlKey());
$secondStoreUrl = $this->prepareUrl($product->getUrlKey());
$this->dispatch($secondStoreUrl);
$this->assertProductIsVisible($product);
$this->cleanUpCachedObjects();
} finally {
$this->storeManager->setCurrentStore($currentStore);
}
$this->dispatch($firstStoreUrl);
$this->assertProductIsVisible($product);
}
/**
* Update product
*
* @param ProductInterface $product
* @param array $data
* @return ProductInterface
*/
private function updateProduct(ProductInterface $product, array $data): ProductInterface
{
$product->addData($data);
return $this->productRepository->save($product);
}
/**
* Clean up cached objects
*
* @return void
*/
private function cleanUpCachedObjects(): void
{
$this->registry->unregister('current_product');
$this->registry->unregister('product');
$this->_objectManager->removeSharedInstance(Request::class);
$this->_objectManager->removeSharedInstance(Response::class);
$this->_response = null;
$this->_request = null;
}
/**
* Prepare url to dispatch
*
* @param string $urlKey
* @param bool $addSuffix
* @return string
*/
private function prepareUrl(string $urlKey, bool $addSuffix = true): string
{
$url = $addSuffix ? '/' . $urlKey . $this->urlSuffix : '/' . $urlKey;
return $url;
}
/**
* Assert that product is available in storefront
*
* @param ProductInterface $product
* @return void
*/
private function assertProductIsVisible(ProductInterface $product): void
{
$this->assertEquals(
Response::STATUS_CODE_200,
$this->getResponse()->getHttpResponseCode(),
'Wrong response code is returned'
);
$currentProduct = $this->registry->registry('current_product');
$this->assertNotNull($currentProduct);
$this->assertEquals(
$product->getSku(),
$currentProduct->getSku(),
'Wrong product is registered'
);
}
}
@@ -0,0 +1,450 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller\Product;
use Magento\Catalog\Api\AttributeSetRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Eav\Model\Entity\Type;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Cache\Manager;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Http;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Registry;
use Magento\Framework\Url\EncoderInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Eav\Model\GetAttributeSetByName;
use Magento\TestFramework\Fixture\Cache;
use Magento\TestFramework\Request;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\TestFramework\Response;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Integration test for product view front action.
*
* @magentoAppIsolation enabled
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ViewTest extends AbstractController
{
/**
* @var ProductRepositoryInterface $productRepository
*/
private $productRepository;
/**
* @var AttributeSetRepositoryInterface $attributeSetRepository
*/
private $attributeSetRepository;
/**
* @var ProductAttributeRepositoryInterface $attributeSetRepository
*/
private $attributeRepository;
/**
* @var Type $productEntityType
*/
private $productEntityType;
/** @var Registry */
private $registry;
/** @var StoreManagerInterface */
private $storeManager;
/** @var GetAttributeSetByName */
private $getAttributeSetByName;
/** @var EncoderInterface */
private $urlEncoder;
/** @var ScopeConfigInterface */
private $config;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = $this->_objectManager->create(ProductRepositoryInterface::class);
$this->attributeSetRepository = $this->_objectManager->create(AttributeSetRepositoryInterface::class);
$this->attributeRepository = $this->_objectManager->create(ProductAttributeRepositoryInterface::class);
$this->productEntityType = $this->_objectManager->create(Type::class)
->loadByCode(Product::ENTITY);
$this->registry = $this->_objectManager->get(Registry::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->getAttributeSetByName = $this->_objectManager->get(GetAttributeSetByName::class);
$this->urlEncoder = $this->_objectManager->get(EncoderInterface::class);
$this->config = $this->_objectManager->get(ScopeConfigInterface::class);
}
/**
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Catalog/controllers/_files/products.php
* @magentoConfigFixture current_store catalog/seo/product_canonical_tag 1
* @return void
*/
public function testViewActionWithCanonicalTag(): void
{
$this->markTestSkipped(
'MAGETWO-40724: Canonical url from tests sometimes does not equal canonical url from action'
);
$this->dispatch('catalog/product/view/id/1/');
$this->assertContains(
'<link rel="canonical" href="http://localhost/index.php/catalog/product/view/_ignore_category/1/id/1/" />',
$this->getResponse()->getBody()
);
}
/**
* View product with custom attribute when attribute removed from it.
*
* It tests that after changing product attribute set from Default to Custom
* there are no warning messages in log in case Custom not contains attribute from Default.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_country_of_manufacture.php
* @magentoDataFixture Magento/Catalog/_files/attribute_set_based_on_default_without_country_of_manufacture.php
* @return void
*/
public function testViewActionCustomAttributeSetWithoutCountryOfManufacture(): void
{
/** @var MockObject|LoggerInterface $logger */
$logger = $this->setupLoggerMock();
$product = $this->productRepository->get('simple_with_com');
$attributeSetCustom = $this->getAttributeSetByName->execute('custom_attribute_set_wout_com');
$product->setAttributeSetId($attributeSetCustom->getAttributeSetId());
$this->productRepository->save($product);
/** @var ProductAttributeInterface $attributeCountryOfManufacture */
$attributeCountryOfManufacture = $this->attributeRepository->get('country_of_manufacture');
$logger->expects($this->never())
->method('warning')
->with(
"Attempt to load value of nonexistent EAV attribute",
[
'attribute_id' => $attributeCountryOfManufacture->getAttributeId(),
'entity_type' => ProductInterface::class,
]
);
$this->dispatch(sprintf('catalog/product/view/id/%s/', $product->getId()));
}
/**
* @magentoDataFixture Magento/Quote/_files/is_not_salable_product.php
* @return void
*/
public function testDisabledProductInvisibility(): void
{
$product = $this->productRepository->get('simple-99');
$this->dispatch(sprintf('catalog/product/view/id/%s/', $product->getId()));
$this->assert404NotFound();
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @dataProvider productVisibilityDataProvider
* @param int $visibility
* @return void
*/
public function testProductVisibility(int $visibility): void
{
$product = $this->updateProductVisibility('simple2', $visibility);
$this->dispatch(sprintf('catalog/product/view/id/%s/', $product->getId()));
$this->assertProductIsVisible($product);
}
/**
* @return array
*/
public function productVisibilityDataProvider(): array
{
return [
'catalog_search' => [Visibility::VISIBILITY_BOTH],
'search' => [Visibility::VISIBILITY_IN_SEARCH],
'catalog' => [Visibility::VISIBILITY_IN_CATALOG],
];
}
/**
* @magentoDataFixture Magento/Catalog/_files/simple_products_not_visible_individually.php
*/
public function testProductNotVisibleIndividually(): void
{
$product = $this->updateProductVisibility('simple_not_visible_1', Visibility::VISIBILITY_NOT_VISIBLE);
$this->dispatch(sprintf('catalog/product/view/id/%s/', $product->getId()));
$this->assert404NotFound();
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_two_websites.php
* @magentoDbIsolation disabled
* @return void
*/
public function testProductVisibleOnTwoWebsites(): void
{
$currentStore = $this->storeManager->getStore();
$product = $this->productRepository->get('simple-on-two-websites');
$secondStoreId = $this->storeManager->getStore('fixture_second_store')->getId();
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assertProductIsVisible($product);
$this->cleanUpCachedObjects();
try {
$this->storeManager->setCurrentStore($secondStoreId);
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assertProductIsVisible($product);
} finally {
$this->storeManager->setCurrentStore($currentStore);
}
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_two_websites.php
* @magentoDbIsolation disabled
* @return void
*/
public function testRemoveProductFromOneWebsiteVisibility(): void
{
$websiteId = $this->storeManager->getWebsite('test')->getId();
$currentStore = $this->storeManager->getStore();
$secondStoreId = $this->storeManager->getStore('fixture_second_store')->getId();
$product = $this->updateProduct('simple-on-two-websites', ['website_ids' => [$websiteId]]);
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assert404NotFound();
$this->cleanUpCachedObjects();
try {
$this->storeManager->setCurrentStore($secondStoreId);
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assertProductIsVisible($product);
} finally {
$this->storeManager->setCurrentStore($currentStore->getId());
}
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_two_websites.php
* @magentoDbIsolation disabled
* @return void
*/
public function testProductAttributeByStores(): void
{
$secondStoreId = $this->storeManager->getStore('fixture_second_store')->getId();
$product = $this->productRepository->get('simple-on-two-websites');
$currentStoreId = $this->storeManager->getStore()->getId();
try {
$this->storeManager->setCurrentStore($secondStoreId);
$product = $this->updateProduct($product, ['status' => 2]);
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assert404NotFound();
$this->cleanUpCachedObjects();
$this->storeManager->setCurrentStore($currentStoreId);
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assertProductIsVisible($product);
} finally {
$this->storeManager->setCurrentStore($currentStoreId);
}
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testProductWithoutWebsite(): void
{
$product = $this->updateProduct('simple2', ['website_ids' => []]);
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$this->assert404NotFound();
}
/**
* Test that 404 page has product tag if product is not visible
*
* @magentoDataFixture Magento/Quote/_files/is_not_salable_product.php
* @return void
*/
#[
Cache('full_page', true)
]
public function test404NotFoundPageCacheTags(): void
{
$cache = $this->_objectManager->get(Manager::class);
$cache->clean(['full_page']);
$product = $this->productRepository->get('simple-99');
$this->dispatch(sprintf('catalog/product/view/id/%s/', $product->getId()));
$this->assert404NotFound();
$pTag = Product::CACHE_TAG . '_' . $product->getId();
$hTags = $this->getResponse()->getHeader('X-Magento-Tags');
$tags = $hTags && $hTags->getFieldValue() ? explode(',', $hTags->getFieldValue()) : [];
$this->assertContains(
$pTag,
$tags,
"Failed asserting that X-Magento-Tags: {$hTags->getFieldValue()} contains \"$pTag\""
);
}
/**
* @return void
*/
public function testViewUnexistedProduct(): void
{
$url = '/catalog/product/view/id/999/';
$this->getRequest()->setParams([
ActionInterface::PARAM_NAME_URL_ENCODED => $this->urlEncoder->encode($url),
])->setMethod(HttpRequest::METHOD_POST);
$this->dispatch($url);
$this->assert404NotFound();
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*
* @return void
*/
public function testViewWithRedirect(): void
{
$product = $this->productRepository->get('simple2');
$url = rtrim($this->config->getValue(Store::XML_PATH_UNSECURE_BASE_LINK_URL), '/');
$this->getRequest()
->setParams([
ActionInterface::PARAM_NAME_URL_ENCODED => $this->urlEncoder->encode($url),
])
->setMethod(HttpRequest::METHOD_POST);
$this->dispatch(sprintf('/catalog/product/view/id/%s/', $product->getId()));
$this->assertRedirect($this->stringContains($url));
}
/**
* @param string|ProductInterface $product
* @param array $data
* @return ProductInterface
*/
public function updateProduct($product, array $data): ProductInterface
{
$product = is_string($product) ? $this->productRepository->get($product) : $product;
$product->addData($data);
return $this->productRepository->save($product);
}
/**
* @inheritdoc
*/
public function assert404NotFound()
{
parent::assert404NotFound();
$this->assertNull($this->registry->registry('current_product'));
}
/**
* Assert that product is available in storefront
*
* @param ProductInterface $product
* @return void
*/
private function assertProductIsVisible(ProductInterface $product): void
{
$this->assertEquals(
Response::STATUS_CODE_200,
$this->getResponse()->getHttpResponseCode(),
'Wrong response code is returned'
);
$currentProduct = $this->registry->registry('current_product');
$this->assertNotNull($currentProduct);
$this->assertEquals(
$product->getSku(),
$currentProduct->getSku(),
'Wrong product is registered'
);
}
/**
* Clean up cached objects.
*
* @return void
*/
private function cleanUpCachedObjects(): void
{
$this->_objectManager->removeSharedInstance(Http::class);
$this->_objectManager->removeSharedInstance(Request::class);
$this->_objectManager->removeSharedInstance(Response::class);
$this->_request = null;
$this->_response = null;
}
/**
* Setup logger mock to check there are no warning messages logged.
*
* @return MockObject
*/
private function setupLoggerMock(): MockObject
{
$logger = $this->getMockBuilder(LoggerInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$this->_objectManager->addSharedInstance($logger, LoggerInterface::class, true);
return $logger;
}
/**
* Update product visibility
*
* @param string $sku
* @param int $visibility
* @return ProductInterface
*/
private function updateProductVisibility(string $sku, int $visibility): ProductInterface
{
$product = $this->productRepository->get($sku);
$product->setVisibility($visibility);
return $this->productRepository->save($product);
}
/**
* Test product details block as active on load
*
* @magentoDataFixture Magento/Catalog/_files/product_simple_without_custom_options.php
* @return void
*/
public function testProductDetailsBlock(): void
{
$product = $this->productRepository->get('simple-2');
$this->dispatch(sprintf('catalog/product/view/id/%s/', $product->getId()));
$content = $this->getResponse()->getContent();
$this->assertStringContainsString(
'<div class="data item title active"
data-role="collapsible" id="tab-label-description">',
$content
);
}
}
@@ -0,0 +1,344 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Catalog\Controller;
use Magento\Bundle\Test\Fixture\Link as BundleSelectionFixture;
use Magento\Bundle\Test\Fixture\Option as BundleOptionFixture;
use Magento\Bundle\Test\Fixture\Product as BundleProductFixture;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Test\Fixture\Attribute as AttributeFixture;
use Magento\ConfigurableProduct\Test\Fixture\Product as ConfigurableProductFixture;
use Magento\Catalog\Model\Session;
use Magento\Catalog\Test\Fixture\Category;
use Magento\Catalog\Test\Fixture\Product;
use Magento\Framework\Registry;
use Magento\TestFramework\Catalog\Model\ProductLayoutUpdateManager;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Helper\Xpath;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Checks product view on storefront
*
* @see \Magento\Catalog\Controller\Product
*
* @magentoDbIsolation enabled
*/
class ProductTest extends AbstractController
{
/** @var Registry */
private $registry;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Session */
private $session;
/**
* @var DataFixtureStorage
*/
private $fixture;
/**
* @inheritdoc
*/
protected function setUp(): void
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Randomly fails due to known HHVM bug (DOMText mixed with DOMElement)');
}
Bootstrap::getObjectManager()->configure([
'preferences' => [
\Magento\Catalog\Model\Product\Attribute\LayoutUpdateManager::class =>
\Magento\TestFramework\Catalog\Model\ProductLayoutUpdateManager::class
]
]);
parent::setUp();
$this->registry = $this->_objectManager->get(Registry::class);
$this->productRepository = $this->_objectManager->get(ProductRepositoryInterface::class);
$this->session = $this->_objectManager->get(Session::class);
$this->fixture = DataFixtureStorageManager::getStorage();
}
/**
* @inheritdoc
*/
public function assert404NotFound()
{
parent::assert404NotFound();
$this->assertNull($this->registry->registry('current_product'));
}
/**
* Get product image file
*
* @return string
*/
protected function getProductImageFile(): string
{
$product = $this->productRepository->get('simple_product_1');
$images = $product->getMediaGalleryImages()->getItems();
$image = reset($images);
return $image['file'];
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/products.php
* @magentoAppArea frontend
* @return void
*/
public function testViewAction(): void
{
$product = $this->productRepository->get('simple_product_1');
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getEntityId()));
$currentProduct = $this->registry->registry('current_product');
$this->assertInstanceOf(ProductInterface::class, $currentProduct);
$this->assertEquals($product->getEntityId(), $currentProduct->getEntityId());
$this->assertEquals($product->getEntityId(), $this->session->getLastViewedProductId());
$responseBody = $this->getResponse()->getBody();
/* Product info */
$this->assertStringContainsString($product->getName(), $responseBody);
$this->assertStringContainsString($product->getDescription(), $responseBody);
$this->assertStringContainsString($product->getShortDescription(), $responseBody);
$this->assertStringContainsString($product->getSku(), $responseBody);
/* Stock info */
$this->assertStringContainsString('$1,234.56', $responseBody);
$this->assertStringContainsString('In stock', $responseBody);
$this->assertStringContainsString((string)__('Add to Cart'), $responseBody);
/* Meta info */
$this->assertStringContainsString('<title>Simple Product 1 Meta Title</title>', $responseBody);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
'//meta[@name="keywords" and @content="Simple Product 1 Meta Keyword"]',
$responseBody
)
);
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
'//meta[@name="description" and @content="Simple Product 1 Meta Description"]',
$responseBody
)
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @return void
*/
public function testViewActionConfigurable(): void
{
$product = $this->productRepository->get('simple');
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getEntityId()));
$html = $this->getResponse()->getBody();
$this->assertEquals(
1,
Xpath::getElementsCountForXpath(
'//*[@id="product-options-wrapper"]',
$html
)
);
}
/**
* @return void
*/
public function testViewActionNoProductId(): void
{
$this->dispatch('catalog/product/view/id/');
$this->assert404NotFound();
}
/**
* @return void
*/
public function testViewActionRedirect(): void
{
$this->dispatch('catalog/product/view/?store=default');
$this->assertRedirect();
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/products.php
* @return void
*/
public function testGalleryAction(): void
{
$product = $this->productRepository->get('simple_product_1');
$this->dispatch(sprintf('catalog/product/gallery/id/%s', $product->getEntityId()));
$this->assertStringContainsString(
'http://localhost/media/catalog/product/',
$this->getResponse()->getBody()
);
$this->assertStringContainsString($this->getProductImageFile(), $this->getResponse()->getBody());
}
/**
* @return void
*/
public function testGalleryActionRedirect(): void
{
$this->dispatch('catalog/product/gallery/?store=default');
$this->assertRedirect();
}
/**
* @return void
*/
public function testGalleryActionNoProduct(): void
{
$this->dispatch('catalog/product/gallery/id/');
$this->assert404NotFound();
}
/**
* @magentoDataFixture Magento/Catalog/controllers/_files/products.php
* @return void
*/
public function testImageAction(): void
{
$this->markTestSkipped("All logic has been cut to avoid possible malicious usage of the method");
ob_start();
/* Preceding slash in URL is required in this case */
$this->dispatch('/catalog/product/image' . $this->getProductImageFile());
$imageContent = ob_get_clean();
/**
* Check against PNG file signature.
*
* @link http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature
*/
$this->assertStringStartsWith(sprintf("%cPNG\r\n%c\n", 137, 26), $imageContent);
}
/**
* @return void
*/
public function testImageActionNoImage(): void
{
$this->dispatch('catalog/product/image/');
$this->assert404NotFound();
}
/**
* Check that custom layout update files is employed.
*
* @magentoDataFixture Magento/Catalog/controllers/_files/products.php
* @return void
*/
public function testViewWithCustomUpdate(): void
{
//Setting a fake file for the product.
$file = 'test-file';
/** @var ProductRepositoryInterface $repository */
$repository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);
$sku = 'simple_product_1';
$product = $repository->get($sku);
$productId = $product->getId();
/** @var ProductLayoutUpdateManager $layoutManager */
$layoutManager = Bootstrap::getObjectManager()->get(ProductLayoutUpdateManager::class);
$layoutManager->setFakeFiles((int)$productId, [$file]);
//Updating the custom attribute.
$product->setCustomAttribute('custom_layout_update_file', $file);
$repository->save($product);
//Viewing the product
$this->dispatch("catalog/product/view/id/$productId");
//Layout handles must contain the file.
$handles = Bootstrap::getObjectManager()->get(\Magento\Framework\View\LayoutInterface::class)
->getUpdate()
->getHandles();
$this->assertContains("catalog_product_view_selectable_{$sku}_{$file}", $handles);
}
/**
* Validate itemprop generation on different product types' page
*
* @return void
*/
#[
DataFixture(Category::class, as: 'category'),
DataFixture(
Product::class,
['category_ids' => ['$category.id$'], 'short_description' => 'Product Short Description'],
as: 'sp'
),
DataFixture(AttributeFixture::class, ['options' => [['label' => 'option1', 'sort_order' => 0]]], as: 'attr'),
DataFixture(
ConfigurableProductFixture::class,
[
'short_description' => 'Configurable Product Short Description',
'_options' => ['$attr$'],
'_links' => ['$sp$']
],
as: 'cp'
),
DataFixture(BundleSelectionFixture::class, ['sku' => '$sp.sku$'], 'link1'),
DataFixture(BundleOptionFixture::class, ['product_links' => ['$link1$']], 'opt1'),
DataFixture(
BundleProductFixture::class,
[
'short_description' => 'Bundle Product Short Description',
'sku' => 'bundle1',
'_options' => ['$opt1$']
],
as:'bp'
),
]
public function testItempropOnProductPage()
{
$product = $this->fixture->get('sp');
$this->checkItemProp($product);
$bundleProduct = $this->fixture->get('bp');
$this->checkItemProp($bundleProduct);
$configurableProduct = $this->fixture->get('cp');
$this->checkItemProp($configurableProduct);
}
/**
* Validate presence of itemprop for image and description
*
* @param ProductInterface $product
* @return void
*/
private function checkItemProp(ProductInterface $product)
{
$this->dispatch(sprintf('catalog/product/view/id/%s', $product->getId()));
$html = $this->getResponse()->getBody();
$this->assertNotEmpty(
Xpath::getElementsCountForXpath(
'//*[@itemprop="image"]',
$html
),
'itemprop image doesn\'t match for product type '.$product->getTypeId()
);
$this->assertNotEmpty(
Xpath::getElementsCountForXpath(
'//*[@itemprop="description"]',
$html
),
'itemprop description doesn\'t match for product type '.$product->getTypeId()
);
}
}