AsyncScheduleCustomRouteTest.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\WebapiAsync\Model;
  8. use Magento\Catalog\Api\Data\ProductInterface;
  9. use Magento\Framework\Exception\NotFoundException;
  10. use Magento\TestFramework\MessageQueue\PreconditionFailedException;
  11. use Magento\TestFramework\MessageQueue\PublisherConsumerController;
  12. use Magento\TestFramework\MessageQueue\EnvironmentPreconditionException;
  13. use Magento\TestFramework\TestCase\WebapiAbstract;
  14. use Magento\TestFramework\Helper\Bootstrap;
  15. use Magento\Catalog\Model\ResourceModel\Product\Collection;
  16. use Magento\Framework\Phrase;
  17. use Magento\Framework\Registry;
  18. use Magento\Framework\Webapi\Exception;
  19. use Magento\Catalog\Api\ProductRepositoryInterface;
  20. /**
  21. * Check async request for product creation service using custom route, scheduling bulk to rabbitmq
  22. * running consumers and check async.operation.add consumer
  23. * check if product was created by async requests
  24. *
  25. * @magentoAppIsolation enabled
  26. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  27. */
  28. class AsyncScheduleCustomRouteTest extends WebapiAbstract
  29. {
  30. const ASYNC_RESOURCE_CUSTOM_PATH = '/asyncProducts';
  31. const ASYNC_CONSUMER_NAME = 'async.operations.all';
  32. const KEY_TIER_PRICES = 'tier_prices';
  33. const KEY_SPECIAL_PRICE = 'special_price';
  34. const KEY_CATEGORY_LINKS = 'category_links';
  35. const BULK_UUID_KEY = 'bulk_uuid';
  36. protected $consumers = [
  37. self::ASYNC_CONSUMER_NAME,
  38. ];
  39. /**
  40. * @var string[]
  41. */
  42. private $skus = [];
  43. /**
  44. * @var PublisherConsumerController
  45. */
  46. private $publisherConsumerController;
  47. /**
  48. * @var ProductRepositoryInterface
  49. */
  50. private $productRepository;
  51. /**
  52. * @var \Magento\Framework\ObjectManagerInterface
  53. */
  54. private $objectManager;
  55. /**
  56. * @var Registry
  57. */
  58. private $registry;
  59. protected function setUp()
  60. {
  61. $this->objectManager = Bootstrap::getObjectManager();
  62. $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt";
  63. $this->registry = $this->objectManager->get(Registry::class);
  64. $params = array_merge_recursive(
  65. \Magento\TestFramework\Helper\Bootstrap::getInstance()->getAppInitParams(),
  66. ['MAGE_DIRS' => ['cache' => ['path' => TESTS_TEMP_DIR . '/cache']]]
  67. );
  68. /** @var PublisherConsumerController publisherConsumerController */
  69. $this->publisherConsumerController = $this->objectManager->create(PublisherConsumerController::class, [
  70. 'consumers' => $this->consumers,
  71. 'logFilePath' => $this->logFilePath,
  72. 'appInitParams' => $params,
  73. ]);
  74. $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
  75. try {
  76. $this->publisherConsumerController->initialize();
  77. } catch (EnvironmentPreconditionException $e) {
  78. $this->markTestSkipped($e->getMessage());
  79. } catch (PreconditionFailedException $e) {
  80. $this->fail(
  81. $e->getMessage()
  82. );
  83. }
  84. parent::setUp();
  85. }
  86. /**
  87. * @dataProvider productCreationProvider
  88. */
  89. public function testAsyncScheduleBulkByCustomRoute($product)
  90. {
  91. $this->_markTestAsRestOnly();
  92. $this->skus[] = $product['product'][ProductInterface::SKU];
  93. $this->clearProducts();
  94. $response = $this->saveProductByCustomRoute($product);
  95. $this->assertArrayHasKey(self::BULK_UUID_KEY, $response);
  96. $this->assertNotNull($response[self::BULK_UUID_KEY]);
  97. $this->assertCount(1, $response['request_items']);
  98. $this->assertEquals('accepted', $response['request_items'][0]['status']);
  99. $this->assertFalse($response['errors']);
  100. //assert one products is created
  101. try {
  102. $this->publisherConsumerController->waitForAsynchronousResult(
  103. [$this, 'assertProductCreation'],
  104. [$product]
  105. );
  106. } catch (PreconditionFailedException $e) {
  107. $this->fail("Not all products were created");
  108. }
  109. }
  110. public function tearDown()
  111. {
  112. $this->clearProducts();
  113. $this->publisherConsumerController->stopConsumers();
  114. parent::tearDown();
  115. }
  116. private function clearProducts()
  117. {
  118. $size = $this->objectManager->create(Collection::class)
  119. ->addAttributeToFilter('sku', ['in' => $this->skus])
  120. ->load()
  121. ->getSize();
  122. if ($size == 0) {
  123. return;
  124. }
  125. $this->registry->unregister('isSecureArea');
  126. $this->registry->register('isSecureArea', true);
  127. try {
  128. foreach ($this->skus as $sku) {
  129. $this->productRepository->deleteById($sku);
  130. }
  131. } catch (\Exception $e) {
  132. throw $e;
  133. //nothing to delete
  134. }
  135. $this->registry->unregister('isSecureArea');
  136. $size = $this->objectManager->create(Collection::class)
  137. ->addAttributeToFilter('sku', ['in' => $this->skus])
  138. ->load()
  139. ->getSize();
  140. if ($size > 0) {
  141. throw new Exception(new Phrase("Collection size after clearing the products: %size", ['size' => $size]));
  142. }
  143. }
  144. /**
  145. * @return array
  146. */
  147. public function productCreationProvider()
  148. {
  149. $productBuilder = function ($data) {
  150. return array_replace_recursive(
  151. $this->getSimpleProductData(),
  152. $data
  153. );
  154. };
  155. return [
  156. [
  157. [
  158. 'product' =>
  159. $productBuilder([
  160. ProductInterface::TYPE_ID => 'simple',
  161. ProductInterface::SKU => 'psku-test-1',
  162. ]),
  163. ],
  164. ],
  165. [
  166. [
  167. 'product' => $productBuilder([
  168. ProductInterface::TYPE_ID => 'virtual',
  169. ProductInterface::SKU => 'psku-test-2',
  170. ]),
  171. ],
  172. ],
  173. ];
  174. }
  175. /**
  176. * Get Simple Product Data
  177. *
  178. * @param array $productData
  179. * @return array
  180. */
  181. private function getSimpleProductData($productData = [])
  182. {
  183. return [
  184. ProductInterface::SKU => isset($productData[ProductInterface::SKU])
  185. ? $productData[ProductInterface::SKU] : uniqid('sku-', true),
  186. ProductInterface::NAME => isset($productData[ProductInterface::NAME])
  187. ? $productData[ProductInterface::NAME] : uniqid('sku-', true),
  188. ProductInterface::VISIBILITY => 4,
  189. ProductInterface::TYPE_ID => 'simple',
  190. ProductInterface::PRICE => 3.62,
  191. ProductInterface::STATUS => 1,
  192. ProductInterface::TYPE_ID => 'simple',
  193. ProductInterface::ATTRIBUTE_SET_ID => 4,
  194. 'custom_attributes' => [
  195. ['attribute_code' => 'cost', 'value' => ''],
  196. ['attribute_code' => 'description', 'value' => 'Description'],
  197. ],
  198. ];
  199. }
  200. /**
  201. * @param $requestData
  202. * @param string|null $storeCode
  203. * @return mixed
  204. */
  205. private function saveProductByCustomRoute($requestData, $storeCode = null)
  206. {
  207. $serviceInfo = [
  208. 'rest' => [
  209. 'resourcePath' => self::ASYNC_RESOURCE_CUSTOM_PATH,
  210. 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
  211. ],
  212. ];
  213. return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode);
  214. }
  215. public function assertProductCreation()
  216. {
  217. $collection = $this->objectManager->create(Collection::class)
  218. ->addAttributeToFilter('sku', ['in' => $this->skus])
  219. ->load();
  220. $size = $collection->getSize();
  221. return $size == count($this->skus);
  222. }
  223. }