AsyncScheduleTest.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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, 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 AsyncScheduleTest extends WebapiAbstract
  29. {
  30. const SERVICE_NAME = 'catalogProductRepositoryV1';
  31. const SERVICE_VERSION = 'V1';
  32. const REST_RESOURCE_PATH = '/V1/products';
  33. const ASYNC_RESOURCE_PATH = '/async/V1/products';
  34. const ASYNC_CONSUMER_NAME = 'async.operations.all';
  35. const KEY_TIER_PRICES = 'tier_prices';
  36. const KEY_SPECIAL_PRICE = 'special_price';
  37. const KEY_CATEGORY_LINKS = 'category_links';
  38. const BULK_UUID_KEY = 'bulk_uuid';
  39. protected $consumers = [
  40. self::ASYNC_CONSUMER_NAME,
  41. ];
  42. /**
  43. * @var string[]
  44. */
  45. private $skus = [];
  46. /**
  47. * @var PublisherConsumerController
  48. */
  49. private $publisherConsumerController;
  50. /**
  51. * @var ProductRepositoryInterface
  52. */
  53. private $productRepository;
  54. /**
  55. * @var \Magento\Framework\ObjectManagerInterface
  56. */
  57. private $objectManager;
  58. /**
  59. * @var Registry
  60. */
  61. private $registry;
  62. protected function setUp()
  63. {
  64. $this->objectManager = Bootstrap::getObjectManager();
  65. $this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt";
  66. $this->registry = $this->objectManager->get(Registry::class);
  67. $params = array_merge_recursive(
  68. \Magento\TestFramework\Helper\Bootstrap::getInstance()->getAppInitParams(),
  69. ['MAGE_DIRS' => ['cache' => ['path' => TESTS_TEMP_DIR . '/cache']]]
  70. );
  71. /** @var PublisherConsumerController publisherConsumerController */
  72. $this->publisherConsumerController = $this->objectManager->create(PublisherConsumerController::class, [
  73. 'consumers' => $this->consumers,
  74. 'logFilePath' => $this->logFilePath,
  75. 'appInitParams' => $params,
  76. ]);
  77. $this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
  78. try {
  79. $this->publisherConsumerController->initialize();
  80. } catch (EnvironmentPreconditionException $e) {
  81. $this->markTestSkipped($e->getMessage());
  82. } catch (PreconditionFailedException $e) {
  83. $this->fail(
  84. $e->getMessage()
  85. );
  86. }
  87. parent::setUp();
  88. }
  89. /**
  90. * @dataProvider productCreationProvider
  91. */
  92. public function testAsyncScheduleBulk($product)
  93. {
  94. $this->_markTestAsRestOnly();
  95. $this->skus[] = $product['product'][ProductInterface::SKU];
  96. $this->clearProducts();
  97. $response = $this->saveProductAsync($product);
  98. $this->assertArrayHasKey(self::BULK_UUID_KEY, $response);
  99. $this->assertNotNull($response[self::BULK_UUID_KEY]);
  100. $this->assertCount(1, $response['request_items']);
  101. $this->assertEquals('accepted', $response['request_items'][0]['status']);
  102. $this->assertFalse($response['errors']);
  103. //assert one products is created
  104. try {
  105. $this->publisherConsumerController->waitForAsynchronousResult(
  106. [$this, 'assertProductCreation'],
  107. [$product]
  108. );
  109. } catch (PreconditionFailedException $e) {
  110. $this->fail("Not all products were created");
  111. }
  112. }
  113. public function tearDown()
  114. {
  115. $this->clearProducts();
  116. $this->publisherConsumerController->stopConsumers();
  117. parent::tearDown();
  118. }
  119. private function clearProducts()
  120. {
  121. $size = $this->objectManager->create(Collection::class)
  122. ->addAttributeToFilter('sku', ['in' => $this->skus])
  123. ->load()
  124. ->getSize();
  125. if ($size == 0) {
  126. return;
  127. }
  128. $this->registry->unregister('isSecureArea');
  129. $this->registry->register('isSecureArea', true);
  130. try {
  131. foreach ($this->skus as $sku) {
  132. $this->productRepository->deleteById($sku);
  133. }
  134. } catch (\Exception $e) {
  135. throw $e;
  136. //nothing to delete
  137. }
  138. $this->registry->unregister('isSecureArea');
  139. $size = $this->objectManager->create(Collection::class)
  140. ->addAttributeToFilter('sku', ['in' => $this->skus])
  141. ->load()
  142. ->getSize();
  143. if ($size > 0) {
  144. throw new Exception(new Phrase("Collection size after clearing the products: %size", ['size' => $size]));
  145. }
  146. }
  147. /**
  148. * @param string $sku
  149. * @param string|null $storeCode
  150. * @dataProvider productGetDataProvider
  151. * @expectedException \Exception
  152. * @expectedExceptionMessage Specified request cannot be processed.
  153. */
  154. public function testGETRequestToAsync($sku, $storeCode = null)
  155. {
  156. $this->_markTestAsRestOnly();
  157. $serviceInfo = [
  158. 'rest' => [
  159. 'resourcePath' => self::ASYNC_RESOURCE_PATH . '/' . $sku,
  160. 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
  161. ],
  162. ];
  163. $response = null;
  164. try {
  165. $response = $this->_webApiCall($serviceInfo, [ProductInterface::SKU => $sku], null, $storeCode);
  166. } catch (NotFoundException $e) {
  167. $this->assertEquals(400, $e->getCode());
  168. }
  169. $this->assertNull($response);
  170. }
  171. /**
  172. * @return array
  173. */
  174. public function productCreationProvider()
  175. {
  176. $productBuilder = function ($data) {
  177. return array_replace_recursive(
  178. $this->getSimpleProductData(),
  179. $data
  180. );
  181. };
  182. return [
  183. [
  184. [
  185. 'product' =>
  186. $productBuilder([
  187. ProductInterface::TYPE_ID => 'simple',
  188. ProductInterface::SKU => 'psku-test-1',
  189. ]),
  190. ],
  191. ],
  192. [
  193. [
  194. 'product' => $productBuilder([
  195. ProductInterface::TYPE_ID => 'virtual',
  196. ProductInterface::SKU => 'psku-test-2',
  197. ]),
  198. ],
  199. ],
  200. ];
  201. }
  202. /**
  203. * @return array
  204. */
  205. public function productGetDataProvider()
  206. {
  207. return [
  208. ['psku-test-1', null],
  209. ];
  210. }
  211. /**
  212. * Get Simple Product Data
  213. *
  214. * @param array $productData
  215. * @return array
  216. */
  217. private function getSimpleProductData($productData = [])
  218. {
  219. return [
  220. ProductInterface::SKU => isset($productData[ProductInterface::SKU])
  221. ? $productData[ProductInterface::SKU] : uniqid('sku-', true),
  222. ProductInterface::NAME => isset($productData[ProductInterface::NAME])
  223. ? $productData[ProductInterface::NAME] : uniqid('sku-', true),
  224. ProductInterface::VISIBILITY => 4,
  225. ProductInterface::TYPE_ID => 'simple',
  226. ProductInterface::PRICE => 3.62,
  227. ProductInterface::STATUS => 1,
  228. ProductInterface::TYPE_ID => 'simple',
  229. ProductInterface::ATTRIBUTE_SET_ID => 4,
  230. 'custom_attributes' => [
  231. ['attribute_code' => 'cost', 'value' => ''],
  232. ['attribute_code' => 'description', 'value' => 'Description'],
  233. ],
  234. ];
  235. }
  236. /**
  237. * @param $requestData
  238. * @param string|null $storeCode
  239. * @return mixed
  240. */
  241. private function saveProductAsync($requestData, $storeCode = null)
  242. {
  243. $serviceInfo = [
  244. 'rest' => [
  245. 'resourcePath' => self::ASYNC_RESOURCE_PATH,
  246. 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
  247. ],
  248. ];
  249. return $this->_webApiCall($serviceInfo, $requestData, null, $storeCode);
  250. }
  251. public function assertProductCreation()
  252. {
  253. $collection = $this->objectManager->create(Collection::class)
  254. ->addAttributeToFilter('sku', ['in' => $this->skus])
  255. ->load();
  256. $size = $collection->getSize();
  257. return $size == count($this->skus);
  258. }
  259. }