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,120 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Downloadable\Model\File;
use Magento\Downloadable\Api\Data\File\ContentInterface;
use Magento\Downloadable\Api\Data\File\ContentInterfaceFactory;
use Magento\Downloadable\Model\Link;
use Magento\Downloadable\Model\Sample;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\MediaStorage\Helper\File\Storage;
use Magento\MediaStorage\Helper\File\Storage\Database;
use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Integration test for \Magento\Downloadable\Model\File\ContentUploader class
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ContentUploaderTest extends TestCase
{
/**
* @var ContentInterface
*/
private $fileContent;
/**
* @var string
*/
private $filePath;
/**
* @var ContentUploader
*/
private $model;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->fileContent = $this->objectManager->create(ContentInterfaceFactory::class)->create();
$fixtureDir = realpath(__DIR__ . '/../../_files');
$this->filePath = $fixtureDir . DIRECTORY_SEPARATOR . 'test_image.jpg';
$this->fileContent->setFileData(base64_encode(file_get_contents($this->filePath)));
$this->fileContent->setName('test_image.jpg');
$database = $this->getMockBuilder(Database::class)
->disableOriginalConstructor()
->getMock();
$storage = $this->getMockBuilder(Storage::class)
->disableOriginalConstructor()
->getMock();
$validator = $this->getMockBuilder(NotProtectedExtension::class)
->disableOriginalConstructor()
->getMock();
$filesystem = $this->getMockBuilder(Filesystem::class)
->disableOriginalConstructor()
->onlyMethods(['getDirectoryWrite'])
->getMock();
$systemTmpDirectory = $this->getMockForAbstractClass(
WriteInterface::class,
[],
'',
false,
true,
true,
['writeFile']
);
$systemTmpDirectory->expects($this->once())->method('writeFile')->willReturn(1);
$systemTmpDirectory->method('getAbsolutePath')->willReturn($this->filePath);
$filesystem->method('getDirectoryWrite')->willReturn($systemTmpDirectory);
$link = $this->getMockBuilder(Link::class)
->disableOriginalConstructor()
->getMock();
$sampleConfig = $this->getMockBuilder(Sample::class)
->disableOriginalConstructor()
->getMock();
$this->model = $this->getMockForAbstractClass(
ContentUploader::class,
[$database, $storage, $validator, $filesystem, $link, $sampleConfig],
'',
true,
true,
true,
['save']
);
}
public function testUploadWithSuccessSave()
{
$data = ['path' => $this->filePath, 'file' => 'test_image.jpg'];
$this->model->expects($this->once())->method('save')->willReturn($data);
$result = $this->model->upload($this->fileContent, 'sample');
$this->assertIsArray($result);
$this->assertArrayHasKey('status', $result);
$this->assertArrayHasKey('name', $result);
}
public function testUploadWithFalseSave()
{
$this->model->expects($this->once())->method('save')->willReturn(false);
$this->assertFalse($this->model->upload($this->fileContent, 'sample'));
}
}
@@ -0,0 +1,102 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Downloadable\Model\Observer;
use Magento\Downloadable\Model\Link\Purchased\Item;
use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection;
use Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item as OrderItem;
use Magento\Sales\Model\Order\ItemRepository;
use Magento\Store\Model\ScopeInterface;
use Magento\TestFramework\Downloadable\Model\RemoveLinkPurchasedByOrderIncrementId;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test for case, when customer is able to download downloadable product.
*/
class SaveDownloadableOrderItemObserverTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* Initialization of dependencies
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* Asserting, that links status is 'Available' when order is in processing state,
* and 'Order Item Status to Enable Downloads' is 'Invoiced'.
*
* @magentoDataFixture Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php
* @magentoDataFixture Magento/Downloadable/_files/customer_order_with_invoice_downloadable_product.php
*/
public function testOrderStateIsProcessingAndInvoicedOrderItemLinkIsDownloadable()
{
$orderIncremetId = '100000001';
/** @var Order $order */
$order = $this->objectManager->create(Order::class);
$order->loadByIncrementId($orderIncremetId);
/** @var OrderItem $orderItem */
$orderItem = current($order->getAllItems());
$config = $this->objectManager->get(ScopeConfigInterface::class);
$orderItemStatusToEnableDownload = $config->getValue(
\Magento\Downloadable\Model\Link\Purchased\Item::XML_PATH_ORDER_ITEM_STATUS,
ScopeInterface::SCOPE_STORE,
$orderItem->getStoreId()
);
/** Remove downloadable links from order item to create them from scratch */
$removeLinkPurchasedByOrderIncrementId = $this->objectManager->get(
RemoveLinkPurchasedByOrderIncrementId::class
);
$removeLinkPurchasedByOrderIncrementId->execute($orderIncremetId);
$this->assertEquals(Order::STATE_PROCESSING, $order->getState());
$this->assertEquals(OrderItem::STATUS_INVOICED, $orderItem->getStatusId());
$this->assertEquals(OrderItem::STATUS_INVOICED, $orderItemStatusToEnableDownload);
/** Save order item to trigger observers */
$orderItemRepository = $this->objectManager->get(ItemRepository::class);
$orderItemRepository->save($orderItem);
$this->assertOrderItemLinkStatus((int)$orderItem->getId(), Item::LINK_STATUS_AVAILABLE);
}
/**
* Assert that order item link status is expected.
*
* @param int $orderItemId
* @param string $linkStatus
* @return void
*/
public function assertOrderItemLinkStatus(int $orderItemId, string $linkStatus): void
{
/** @var Collection $linkCollection */
$linkCollection = $this->objectManager->create(CollectionFactory::class)->create();
$linkCollection->addFieldToFilter('order_item_id', $orderItemId);
/** Assert there are items in linkCollection to avoid false-positive test result. */
$this->assertGreaterThan(0, $linkCollection->count());
/** @var Item $linkItem */
foreach ($linkCollection->getItems() as $linkItem) {
$this->assertEquals(
$linkStatus,
$linkItem->getStatus()
);
}
}
}
@@ -0,0 +1,69 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Downloadable\Model\Observer;
/**
* Integration test for case, when customer is able to download
* downloadable product, after order was canceled.
*/
class SetLinkStatusObserverTest extends \PHPUnit\Framework\TestCase
{
/**
* Object manager
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* Initialization of dependencies
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* Asserting, that links status is expired after canceling of order.
* This test relates to the GitHub issue magento/magento2#8515.
*
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable.php
* @magentoDataFixture Magento/Downloadable/_files/order_with_downloadable_product.php
* @magentoDbIsolation disabled
*/
public function testCheckStatusOnOrderCancel()
{
/** @var \Magento\Sales\Model\Order $order */
$order = $this->objectManager->create(\Magento\Sales\Model\Order::class);
$order->loadByIncrementId('100000001');
$orderItems = $order->getAllItems();
$items = array_values($orderItems);
/** @var \Magento\Sales\Model\Order\Item $orderItem */
$orderItem = array_shift($items);
/** Canceling order to reproduce test case */
$order->setState(\Magento\Sales\Model\Order::STATE_CANCELED);
$order->save();
/** @var \Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\Collection $linkCollection */
$linkCollection = $this->objectManager->create(
\Magento\Downloadable\Model\ResourceModel\Link\Purchased\Item\CollectionFactory::class
)->create();
$linkCollection->addFieldToFilter('order_item_id', $orderItem->getId());
/** Assert there are items in linkCollection to avoid false-positive test result. */
$this->assertGreaterThan(0, $linkCollection->count());
/** @var \Magento\Downloadable\Model\Link\Purchased\Item $linkItem */
foreach ($linkCollection->getItems() as $linkItem) {
$this->assertEquals(
\Magento\Downloadable\Model\Link\Purchased\Item::LINK_STATUS_EXPIRED,
$linkItem->getStatus()
);
}
}
}
@@ -0,0 +1,258 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Test class for \Magento\Downloadable\Model\Product\Type
*/
namespace Magento\Downloadable\Model\Product;
/**
* Test for \Magento\Downloadable\Model\Product\Type
*/
class TypeTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Downloadable\Model\Product\Type
*/
protected $_model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $this->objectManager->create(
\Magento\Downloadable\Model\Product\Type::class
);
}
/**
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
* @magentoAppArea adminhtml
*/
public function testDeleteTypeSpecificData()
{
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
);
$product->load(1);
$product->setOrigData();
$downloadableData = [];
$links = $this->_model->getLinks($product);
$this->assertNotEmpty($links);
$samples = $this->_model->getSamples($product);
$this->assertNotEmpty($samples->getData());
/** @var \Magento\Downloadable\Model\Link $link */
foreach ($links as $link) {
$data = $link->getData();
$data['title'] = 'UPDATED . ' . $data['title'];
$downloadableData['link'][] = $data;
}
foreach ($samples as $sample) {
$downloadableData['sample'][] = $sample->getData();
}
$product->setDownloadableData($downloadableData);
$this->_model->deleteTypeSpecificData($product);
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
);
$product->load(1);
$links = $this->_model->getLinks($product);
$this->assertEmpty($links);
$samples = $this->_model->getSamples($product);
$this->assertEmpty($samples->getData());
}
/**
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function testSaveTypeSpecificData()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
);
$product->load(1);
$product->setOrigData();
$downloadableData = [];
$links = $this->_model->getLinks($product);
$this->assertNotEmpty($links);
$samples = $this->_model->getSamples($product);
$this->assertNotEmpty($samples->getData());
$i=0;
foreach ($links as $link) {
$i++;
$linkData = $link->getData();
$linkData['is_delete'] = 0;
$linkData['type'] = \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE;
$linkData['title'] = 'Updated downloadable link #' . $i;
$downloadableData['link'][] = $linkData;
}
$i=0;
foreach ($samples as $sample) {
$i++;
$sampleData = $sample->getData();
$sampleData['is_delete'] = 0;
$sampleData['type'] = \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE;
$sampleData['title'] = 'Updated downloadable sample #' . $i;
$downloadableData['sample'][] = $sampleData;
}
$product->setDownloadableData($downloadableData);
$sampleFactory = $objectManager->create(\Magento\Downloadable\Api\Data\SampleInterfaceFactory::class);
$linkFactory = $objectManager->create(\Magento\Downloadable\Api\Data\LinkInterfaceFactory::class);
$extension = $product->getExtensionAttributes();
$expectedLink = [
'is_shareable' => '2',
'link_type' => 'file',
'link_file' => '/j/e/jellyfish_2_4.jpg',
'number_of_downloads' => '15',
'price' => 15,
'sample_type' => 'file',
'sort_order' => '1',
'title' => 'Updated downloadable link #1',
];
$links = [];
foreach ($downloadableData['link'] as $linkData) {
if (!$linkData || (isset($linkData['is_delete']) && (bool)$linkData['is_delete'])) {
continue;
} else {
$link = $linkFactory->create(['data' => $linkData]);
$link->setId($linkData['link_id']);
if (isset($linkData['sample'])) {
$link->setSampleType($linkData['sample']['type']);
$link->setSampleFileData($linkData['sample']['file']);
$expectedLink['sample_file'] = $linkData['sample']['file'];
$link->setSampleUrl($linkData['sample']['url']);
}
$link->setLinkType($linkData['type']);
$link->setStoreId($product->getStoreId());
$link->setWebsiteId($product->getStore()->getWebsiteId());
$link->setProductWebsiteIds($product->getWebsiteIds());
if (!$link->getSortOrder()) {
$link->setSortOrder(1);
}
if (null === $link->getPrice()) {
$link->setPrice(0);
}
if ($link->getIsUnlimited()) {
$link->setNumberOfDownloads(0);
}
$links[] = $link;
}
}
$extension->setDownloadableProductLinks($links);
if (isset($downloadableData['sample']) && is_array($downloadableData['sample'])) {
$samples = [];
foreach ($downloadableData['sample'] as $sampleData) {
if (!$sampleData || (isset($sampleData['is_delete']) && (bool)$sampleData['is_delete'])) {
continue;
} else {
$sample = $sampleFactory->create(['data' => $sampleData]);
$sample->setId($sampleData['sample_id']);
$sample->setStoreId($product->getStoreId());
$sample->setSampleType($sampleData['type']);
$sample->setSampleUrl($sampleData['sample_url']);
if (!$sample->getSortOrder()) {
$sample->setSortOrder(1);
}
$samples[] = $sample;
}
}
$extension->setDownloadableProductSamples($samples);
}
$product->setExtensionAttributes($extension);
if ($product->getLinksPurchasedSeparately()) {
$product->setTypeHasRequiredOptions(true)->setRequiredOptions(true);
} else {
$product->setTypeHasRequiredOptions(false)->setRequiredOptions(false);
}
$product->save();
/** @var \Magento\Catalog\Model\Product $product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\Product::class
);
$product->load(1);
$links = $product->getExtensionAttributes()->getDownloadableProductLinks();
$this->assertNotEmpty($links);
$this->assertCount(1, $links);
/** @var \Magento\Downloadable\Model\Link $link */
$link = reset($links);
foreach ($expectedLink as $key => $value) {
$this->assertTrue($link->hasData($key), 'Key ' . $key . ' not exist!');
$this->assertArrayHasKey($key, $link);
$this->assertEquals($value, $link->getData($key));
}
$expectedSample = [
'sample_type' => 'file',
'sort_order' => '1',
'title' => 'Updated downloadable sample #1',
];
$samples = $product->getExtensionAttributes()->getDownloadableProductSamples();
$sample = reset($samples);
$this->assertNotEmpty($sample->getData());
$this->assertCount(1, $samples);
/** @var \Magento\Downloadable\Model\Sample $sample */
$sample = $sample->getData();
/** @var \Magento\User\Api\Data\UserInterface $testAttribute */
foreach ($expectedSample as $key => $value) {
$this->assertArrayHasKey($key, $sample);
$this->assertEquals($value, $sample[$key]);
}
}
/**
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable.php
* @covers \Magento\Downloadable\Model\Product\Type::checkProductBuyState()
*/
public function testCheckProductBuyState()
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository =$this->objectManager->create(
\Magento\Catalog\Api\ProductRepositoryInterface::class
);
$product = $productRepository->get('downloadable-product');
$product->setLinksPurchasedSeparately(false);
$productRepository->save($product);
/** @var \Magento\Quote\Model\Quote\Item\Option $option */
$option = $this->objectManager->create(
\Magento\Quote\Model\Quote\Item\Option::class,
['data' => ['code' => 'info_buyRequest', 'value' => '{"qty":23}']]
);
$option->setProduct($product);
$product->setCustomOptions(['info_buyRequest' => $option]);
$this->_model->checkProductBuyState($product);
$linksFactory = $this->objectManager
->get(\Magento\Downloadable\Model\ResourceModel\Link\CollectionFactory::class);
$allLinksIds = $linksFactory->create()->addProductToFilter($product->getEntityId())->getAllIds();
$this->assertEquals(
'{"qty":23,"links":["' . implode('","', $allLinksIds) . '"]}',
$product->getCustomOption('info_buyRequest')->getValue()
);
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Downloadable\Model\ResourceModel\Indexer;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
class PriceTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Catalog\Model\Indexer\Product\Price\Processor
*/
private $indexer;
/**
* @var \Magento\Catalog\Model\ProductRepository
*/
private $productRepository;
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\Collection
*/
private $productCollectionFactory;
protected function setUp(): void
{
$this->indexer = Bootstrap::getObjectManager()->get(
\Magento\Catalog\Model\Indexer\Product\Price\Processor::class
);
$this->productCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class);
$this->productRepository = Bootstrap::getObjectManager()->get(\Magento\Catalog\Model\ProductRepository::class);
}
/**
* Steps:
* 1. Add custom tier prices to the product from fixture.
* 2. Run reindexing.
* 3. Load the product again and check all the prices.
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
*/
public function testReindexEntity()
{
$specialPrice = 7.90;
$product = $this->productRepository->get('downloadable-product');
$tierData = [
['website_id' => 0, 'cust_group' => 1, 'price_qty' => 11, 'price' => 8.20],
['website_id' => 0, 'cust_group' => 1, 'price_qty' => 21, 'price' => 7.55],
];
$product->setData('tier_price', $tierData);
$product->setData('special_price', $specialPrice);
$this->productRepository->save($product);
$this->indexer->reindexAll();
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $this->productCollectionFactory->create();
$collection->addPriceData()->addFieldToFilter('sku', 'downloadable-product');
/** @var \Magento\Catalog\Model\Product $product */
$product = $collection->getFirstItem();
$this->assertEquals(10, $product->getPrice(), 'Wrong downloadable product price');
$this->assertEquals($specialPrice, $product->getMinimalPrice());
$resultTiers = $product->getTierPrices();
$this->assertIsArray($resultTiers, 'Tiers not found');
$this->assertEquals(count($tierData), count($resultTiers), 'Incorrect number of result tiers');
for ($i = 0; $i < count($tierData); $i++) {
$this->assertEquals($tierData[$i]['price_qty'], $resultTiers[$i]->getQty(), 'Wrong tier price quantity');
$this->assertEquals($tierData[$i]['price'], $resultTiers[$i]->getValue(), 'Wrong tier price value');
}
}
}
@@ -0,0 +1,182 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Downloadable\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Downloadable\Api\Data\SampleInterfaceFactory;
/**
* Test class for \Magento\Downloadable\Model\SampleRepository
*/
class SampleRepositoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Downloadable\Model\Product\Type
*/
private $model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(\Magento\Downloadable\Model\Product\Type::class);
}
/**
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable.php
*/
public function testCreateSavesProvidedUrls()
{
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $this->getTargetProduct(false);
$links = $this->model->getLinks($product);
$this->assertNotEmpty($links);
$samples = $this->model->getSamples($product);
$this->assertEmpty($samples->getData());
$downloadableSampleData = [
'title' => 'Sample with URL resource',
'sort_order' => 1,
'sample_url' => 'http://www.sample.example.com/',
'sample_type' => 'url',
];
$sampleFactory = $this->objectManager->create(SampleInterfaceFactory::class);
$extension = $product->getExtensionAttributes();
$sample = $sampleFactory->create(['data' => $downloadableSampleData]);
$sample->setStoreId($product->getStoreId());
$sample->setSampleType($downloadableSampleData['sample_type']);
$sample->setSampleUrl($downloadableSampleData['sample_url']);
if (!$sample->getSortOrder()) {
$sample->setSortOrder(1);
}
$extension->setDownloadableProductSamples([$sample]);
$product->setExtensionAttributes($extension);
$productRepository->save($product);
$samples = $this->getTargetProduct(false)->getExtensionAttributes()->getDownloadableProductSamples();
$sample = reset($samples);
$this->assertNotEmpty($sample->getData());
$this->assertCount(1, $samples);
/** @var \Magento\Downloadable\Model\Sample $sample */
$sampleData = $sample->getData();
/** @var \Magento\User\Api\Data\UserInterface $testAttribute */
foreach ($downloadableSampleData as $key => $value) {
$this->assertArrayHasKey($key, $sampleData);
$this->assertEquals($value, $sampleData[$key]);
}
}
/**
* @magentoDataFixture Magento/Downloadable/_files/product_downloadable.php
*/
public function testCreateSavesTitleInStoreViewScope(): void
{
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$product = $this->getTargetProduct(false);
$links = $this->model->getLinks($product);
$this->assertNotEmpty($links);
$samples = $this->model->getSamples($product);
$this->assertEmpty($samples->getData());
$downloadableSampleData = [
'title' => 'Store View Title',
'sort_order' => 1,
'sample_url' => 'http://www.sample.example.com/',
'sample_type' => 'url'
];
$sampleFactory = $this->objectManager->create(SampleInterfaceFactory::class);
$extension = $product->getExtensionAttributes();
$sample = $sampleFactory->create(['data' => $downloadableSampleData]);
$sample->setStoreId($product->getStoreId());
$sample->setSampleType($downloadableSampleData['sample_type']);
$sample->setSampleUrl($downloadableSampleData['sample_url']);
if (!$sample->getSortOrder()) {
$sample->setSortOrder(1);
}
$extension->setDownloadableProductSamples([$sample]);
$product->setExtensionAttributes($extension);
$productRepository->save($product);
$samples = $this->getTargetProduct(false)->getExtensionAttributes()->getDownloadableProductSamples();
$sample = reset($samples);
$this->assertNotEmpty($sample->getData());
$this->assertCount(1, $samples);
/** @var \Magento\Downloadable\Model\Sample $sample */
$sampleData = $sample->getData();
/** @var \Magento\User\Api\Data\UserInterface $testAttribute */
foreach ($downloadableSampleData as $key => $value) {
$this->assertArrayHasKey($key, $sampleData);
$this->assertEquals($value, $sampleData[$key]);
}
$globalScopeSample = $this->getTargetSample(
$this->getTargetProduct(true),
(int)$sampleData['sample_id']
);
$this->assertEmpty($globalScopeSample->getTitle());
}
/**
* Retrieve product that was updated by test
*
* @param bool $isScopeGlobal if true product store ID will be set to 0
* @return Product
*/
private function getTargetProduct(bool $isScopeGlobal): Product
{
if ($isScopeGlobal) {
$product = $this->objectManager->get(ProductFactory::class)
->create()->setStoreId(0)->load(1);
} else {
$product = $this->objectManager->get(ProductFactory::class)
->create()
->load(1);
}
return $product;
}
/**
* Retrieve product sample by its ID (or first sample if ID is not specified)
*
* @param Product $product
* @param int|null $sampleId
* @return Sample|null
*/
private function getTargetSample(Product $product, int $sampleId = null): ?Sample
{
$samples = $product->getExtensionAttributes()->getDownloadableProductSamples();
if ($sampleId) {
if ($samples) {
foreach ($samples as $sample) {
if ((int)$sample->getId() === $sampleId) {
return $sample;
}
}
}
return null;
}
return $samples[0];
}
}
@@ -0,0 +1,98 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Downloadable\Model\Url;
use Magento\Downloadable\Model\DomainManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\DeploymentConfig;
/**
* Test for Magento\Downloadable\Model\Url\DomainValidator
*/
class DomainValidatorTest extends \PHPUnit\Framework\TestCase
{
/**
* @var DomainValidator
*/
private $model;
/**
* @var DeploymentConfig|\PHPUnit\Framework\MockObject\MockObject
*/
private $deploymentConfig;
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->deploymentConfig = $this->createPartialMock(
DeploymentConfig::class,
['get']
);
$domainManager = $objectManager->create(
DomainManager::class,
['deploymentConfig' => $this->deploymentConfig]
);
$this->model = $objectManager->create(
DomainValidator::class,
['domainManager' => $domainManager]
);
}
/**
* @param string $urlInput
* @param array $envDomainWhitelist
* @param bool $isValid
*
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoConfigFixture current_store web/unsecure/base_url http://example.com/
* @magentoConfigFixture current_store web/secure/base_url https://secure.example.com/
* @magentoConfigFixture fixture_second_store_store web/unsecure/base_url http://example2.com/
* @magentoConfigFixture fixture_second_store_store web/secure/base_url https://secure.example2.com/
* @dataProvider isValidDataProvider
*/
public function testIsValid(string $urlInput, array $envDomainWhitelist, bool $isValid)
{
$this->deploymentConfig
->method('get')
->with(DomainValidator::PARAM_DOWNLOADABLE_DOMAINS)
->willReturn($envDomainWhitelist);
$this->assertEquals(
$isValid,
$this->model->isValid($urlInput),
'Failed asserting is ' . ($isValid ? 'valid' : 'not valid') . ': ' . $urlInput .
PHP_EOL .
'Domain whitelist: ' . implode(', ', $envDomainWhitelist)
);
}
public function isValidDataProvider()
{
return [
['http://example.com', ['example.co'], false],
[' http://example.com ', ['example.com'], false],
['http://example.com', ['example.com'], true],
['https://example.com', ['example.com'], true],
['https://example.com/downloadable.pdf', ['example.com'], true],
['https://example.com:8080/downloadable.pdf', ['example.com'], true],
['http://secure.example.com', ['secure.example.com'], true],
['https://secure.example.com', ['secure.example.com'], true],
['https://ultra.secure.example.com', ['secure.example.com'], false],
['http://example2.com', ['example2.com'], true],
['https://example2.com', ['example2.com'], true],
['http://subdomain.example2.com', ['example2.com'], false],
['https://adobe.com', ['adobe.com'], true],
['https://subdomain.adobe.com', ['adobe.com'], false],
['https://ADOBE.COm', ['adobe.com'], true],
['https://adobe.com', ['ADOBE.COm'], true],
['http://127.0.0.1', ['127.0.0.1'], false],
['http://[::1]', ['::1'], false],
];
}
}