AsyncBulkScheduleTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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\NoSuchEntityException;
  10. use Magento\Framework\Exception\NotFoundException;
  11. use Magento\TestFramework\MessageQueue\PreconditionFailedException;
  12. use Magento\TestFramework\MessageQueue\PublisherConsumerController;
  13. use Magento\TestFramework\MessageQueue\EnvironmentPreconditionException;
  14. use Magento\TestFramework\TestCase\WebapiAbstract;
  15. use Magento\TestFramework\Helper\Bootstrap;
  16. use Magento\Catalog\Model\ResourceModel\Product\Collection;
  17. use Magento\Framework\Phrase;
  18. use Magento\Framework\Registry;
  19. use Magento\Framework\Webapi\Exception;
  20. use Magento\Catalog\Api\ProductRepositoryInterface;
  21. /**
  22. * Check async request for multiple products creation service,
  23. * scheduling bulk to rabbitmq
  24. * running consumers and check async.operation.add consumer
  25. * check if product was created by async bulk requests
  26. *
  27. * @magentoAppIsolation enabled
  28. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  29. */
  30. class AsyncBulkScheduleTest extends WebapiAbstract
  31. {
  32. const SERVICE_NAME = 'catalogProductRepositoryV1';
  33. const SERVICE_VERSION = 'V1';
  34. const REST_RESOURCE_PATH = '/V1/products';
  35. const ASYNC_BULK_RESOURCE_PATH = '/async/bulk/V1/products';
  36. const ASYNC_CONSUMER_NAME = 'async.operations.all';
  37. const KEY_TIER_PRICES = 'tier_prices';
  38. const KEY_SPECIAL_PRICE = 'special_price';
  39. const KEY_CATEGORY_LINKS = 'category_links';
  40. const BULK_UUID_KEY = 'bulk_uuid';
  41. protected $consumers = [
  42. self::ASYNC_CONSUMER_NAME,
  43. ];
  44. /**
  45. * @var string[]
  46. */
  47. private $skus = [];
  48. /**
  49. * @var PublisherConsumerController
  50. */
  51. private $publisherConsumerController;
  52. /**
  53. * @var ProductRepositoryInterface
  54. */
  55. private $productRepository;
  56. /**
  57. * @var \Magento\Framework\ObjectManagerInterface
  58. */
  59. private $objectManager;
  60. /**
  61. * @var Registry
  62. */
  63. private $registry;
  64. protected function setUp()
  65. {
  66. $this->objectManager = Bootstrap::getObjectManager();
  67. $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt";
  68. $this->registry = $this->objectManager->get(Registry::class);
  69. $params = array_merge_recursive(
  70. \Magento\TestFramework\Helper\Bootstrap::getInstance()->getAppInitParams(),
  71. ['MAGE_DIRS' => ['cache' => ['path' => TESTS_TEMP_DIR . '/cache']]]
  72. );
  73. /** @var PublisherConsumerController publisherConsumerController */
  74. $this->publisherConsumerController = $this->objectManager->create(PublisherConsumerController::class, [
  75. 'consumers' => $this->consumers,
  76. 'logFilePath' => $this->logFilePath,
  77. 'appInitParams' => $params,
  78. ]);
  79. $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
  80. try {
  81. $this->publisherConsumerController->initialize();
  82. } catch (EnvironmentPreconditionException $e) {
  83. $this->markTestSkipped($e->getMessage());
  84. } catch (PreconditionFailedException $e) {
  85. $this->fail(
  86. $e->getMessage()
  87. );
  88. }
  89. parent::setUp();
  90. }
  91. /**
  92. * @dataProvider productsArrayCreationProvider
  93. */
  94. public function testAsyncScheduleBulkMultipleEntities($products)
  95. {
  96. $this->_markTestAsRestOnly();
  97. $this->skus = [];
  98. foreach ($products as $product) {
  99. $this->skus[] = $product['product'][ProductInterface::SKU];
  100. }
  101. $this->clearProducts();
  102. $response = $this->saveProductAsync($products);
  103. $this->assertArrayHasKey(self::BULK_UUID_KEY, $response);
  104. $this->assertNotNull($response[self::BULK_UUID_KEY]);
  105. $this->assertCount(2, $response['request_items']);
  106. foreach ($products as $key => $product) {
  107. $this->assertEquals('accepted', $response['request_items'][$key]['status']);
  108. }
  109. $this->assertFalse($response['errors']);
  110. //assert one products is created
  111. try {
  112. $this->publisherConsumerController->waitForAsynchronousResult(
  113. [$this, 'assertProductCreation'],
  114. [$products]
  115. );
  116. } catch (PreconditionFailedException $e) {
  117. $this->fail("Not all products were created");
  118. }
  119. }
  120. /**
  121. * @dataProvider productSingleCreationProvider
  122. */
  123. public function testAsyncScheduleBulkSingleEntity($products)
  124. {
  125. $this->_markTestAsRestOnly();
  126. $this->skus = [];
  127. $this->skus[] = $products[0]['product'][ProductInterface::SKU];
  128. $this->clearProducts();
  129. $response = $this->saveProductAsync($products);
  130. $this->assertArrayHasKey(self::BULK_UUID_KEY, $response);
  131. $this->assertNotNull($response[self::BULK_UUID_KEY]);
  132. $this->assertCount(1, $response['request_items']);
  133. $this->assertEquals('accepted', $response['request_items'][0]['status']);
  134. $this->assertFalse($response['errors']);
  135. //assert one products is created
  136. try {
  137. $this->publisherConsumerController->waitForAsynchronousResult(
  138. [$this, 'assertProductCreation'],
  139. [$products]
  140. );
  141. } catch (PreconditionFailedException $e) {
  142. $this->fail("Not all products were created");
  143. }
  144. }
  145. /**
  146. * @dataProvider wrongProductCreationProvider
  147. */
  148. public function testAsyncScheduleBulkWrongEntity($products)
  149. {
  150. $this->_markTestAsRestOnly();
  151. $this->skus = [];
  152. foreach ($products as $product) {
  153. $this->skus[] = $product['product'][ProductInterface::SKU];
  154. }
  155. $this->clearProducts();
  156. $response = null;
  157. try {
  158. $response = $this->saveProductAsync($products);
  159. } catch (\Exception $e) {
  160. $this->assertEquals(500, $e->getCode());
  161. }
  162. $this->assertNull($response);
  163. $this->assertEquals(0, $this->checkProductsCreation());
  164. }
  165. /**
  166. * @param string $sku
  167. * @param string|null $storeCode
  168. * @dataProvider productGetDataProvider
  169. * @expectedException \Exception
  170. * @expectedExceptionMessage Specified request cannot be processed.
  171. */
  172. public function testGETRequestToAsyncBulk($sku, $storeCode = null)
  173. {
  174. $this->_markTestAsRestOnly();
  175. $serviceInfo = [
  176. 'rest' => [
  177. 'resourcePath' => self::ASYNC_BULK_RESOURCE_PATH . '/' . $sku,
  178. 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
  179. ],
  180. ];
  181. $response = null;
  182. try {
  183. $response = $this->_webApiCall($serviceInfo, [ProductInterface::SKU => $sku], null, $storeCode);
  184. } catch (NotFoundException $e) {
  185. $this->assertEquals(400, $e->getCode());
  186. }
  187. $this->assertNull($response);
  188. }
  189. public function tearDown()
  190. {
  191. $this->clearProducts();
  192. $this->publisherConsumerController->stopConsumers();
  193. parent::tearDown();
  194. }
  195. private function clearProducts()
  196. {
  197. $size = $this->objectManager->create(Collection::class)
  198. ->addAttributeToFilter('sku', ['in' => $this->skus])
  199. ->load()
  200. ->getSize();
  201. if ($size == 0) {
  202. return;
  203. }
  204. $this->registry->unregister('isSecureArea');
  205. $this->registry->register('isSecureArea', true);
  206. try {
  207. foreach ($this->skus as $sku) {
  208. $this->productRepository->deleteById($sku);
  209. }
  210. } catch (\Exception $e) {
  211. throw $e;
  212. //nothing to delete
  213. }
  214. $this->registry->unregister('isSecureArea');
  215. $size = $this->objectManager->create(Collection::class)
  216. ->addAttributeToFilter('sku', ['in' => $this->skus])
  217. ->load()
  218. ->getSize();
  219. if ($size > 0) {
  220. throw new Exception(new Phrase("Collection size after clearing the products: %size", ['size' => $size]));
  221. }
  222. }
  223. /**
  224. * @return array
  225. */
  226. public function productsArrayCreationProvider()
  227. {
  228. $productBuilder = function ($data) {
  229. return array_replace_recursive(
  230. $this->getSimpleProductData(),
  231. $data
  232. );
  233. };
  234. return
  235. [
  236. [
  237. [
  238. [
  239. 'product' =>
  240. $productBuilder([
  241. ProductInterface::TYPE_ID => 'simple',
  242. ProductInterface::SKU => 'psku-test-1-multiple',
  243. ]),
  244. ],
  245. [
  246. 'product' => $productBuilder([
  247. ProductInterface::TYPE_ID => 'virtual',
  248. ProductInterface::SKU => 'psku-test-2-multiple',
  249. ]),
  250. ],
  251. ],
  252. ],
  253. ];
  254. }
  255. /**
  256. * @return array
  257. */
  258. public function productSingleCreationProvider()
  259. {
  260. $productBuilder = function ($data) {
  261. return array_replace_recursive(
  262. $this->getSimpleProductData(),
  263. $data
  264. );
  265. };
  266. return
  267. [
  268. [
  269. [
  270. [
  271. 'product' =>
  272. $productBuilder([
  273. ProductInterface::TYPE_ID => 'simple',
  274. ProductInterface::SKU => 'psku-test-1-single',
  275. ]),
  276. ],
  277. ],
  278. ],
  279. ];
  280. }
  281. /**
  282. * @return array
  283. */
  284. public function wrongProductCreationProvider()
  285. {
  286. $productBuilder = function ($data) {
  287. return array_replace_recursive(
  288. $this->getSimpleProductData(),
  289. $data
  290. );
  291. };
  292. $wrongProductBuilder = function ($data) {
  293. return array_replace_recursive(
  294. $this->getWrongProductStructureData(),
  295. $data
  296. );
  297. };
  298. return
  299. [
  300. [
  301. [
  302. [
  303. 'product' =>
  304. $productBuilder([
  305. ProductInterface::TYPE_ID => 'simple',
  306. ProductInterface::SKU => 'psku-test-1-wrong',
  307. ]),
  308. ],
  309. [
  310. 'product' => $productBuilder([
  311. ProductInterface::TYPE_ID => 'virtual',
  312. ProductInterface::SKU => 'psku-test-2-wrong',
  313. ]),
  314. ],
  315. [
  316. 'product' =>
  317. $wrongProductBuilder([
  318. 'wrong_attribute' => 'simple',
  319. ProductInterface::SKU => 'psku-test-3-wrong',
  320. ]),
  321. ],
  322. ],
  323. ],
  324. ];
  325. }
  326. /**
  327. * @return array
  328. */
  329. public function productGetDataProvider()
  330. {
  331. return [
  332. ['psku-test-1', null],
  333. ];
  334. }
  335. /**
  336. * Get Simple Product Data
  337. *
  338. * @param array $productData
  339. * @return array
  340. */
  341. private function getSimpleProductData($productData = [])
  342. {
  343. return [
  344. ProductInterface::SKU => isset($productData[ProductInterface::SKU])
  345. ? $productData[ProductInterface::SKU] : uniqid('sku-', true),
  346. ProductInterface::NAME => isset($productData[ProductInterface::NAME])
  347. ? $productData[ProductInterface::NAME] : uniqid('sku-', true),
  348. ProductInterface::VISIBILITY => 4,
  349. ProductInterface::TYPE_ID => 'simple',
  350. ProductInterface::PRICE => 3.62,
  351. ProductInterface::STATUS => 1,
  352. ProductInterface::TYPE_ID => 'simple',
  353. ProductInterface::ATTRIBUTE_SET_ID => 4,
  354. 'custom_attributes' => [
  355. ['attribute_code' => 'cost', 'value' => ''],
  356. ['attribute_code' => 'description', 'value' => 'Description'],
  357. ],
  358. ];
  359. }
  360. /**
  361. * Get Wrong Simple Product Data without required attributes
  362. *
  363. * @param array $productData
  364. * @return array
  365. */
  366. private function getWrongProductStructureData($productData = [])
  367. {
  368. return [
  369. ProductInterface::SKU => isset($productData[ProductInterface::SKU])
  370. ? $productData[ProductInterface::SKU] : uniqid('sku-', true),
  371. ];
  372. }
  373. /**
  374. * @param $requestData
  375. * @param string|null $storeCode
  376. * @return mixed
  377. */
  378. private function saveProductAsync($requestData, $storeCode = null)
  379. {
  380. $serviceInfo = [
  381. 'rest' => [
  382. 'resourcePath' => self::ASYNC_BULK_RESOURCE_PATH,
  383. 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
  384. ],
  385. ];
  386. return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode);
  387. }
  388. public function assertProductCreation()
  389. {
  390. $collection = $this->objectManager->create(Collection::class)
  391. ->addAttributeToFilter('sku', ['in' => $this->skus])
  392. ->load();
  393. $size = $collection->getSize();
  394. return $size == count($this->skus);
  395. }
  396. /**
  397. * @return int
  398. */
  399. public function checkProductsCreation()
  400. {
  401. $collection = $this->objectManager->create(Collection::class)
  402. ->addAttributeToFilter('sku', ['in' => $this->skus])
  403. ->load();
  404. $size = $collection->getSize();
  405. return $size;
  406. }
  407. }