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