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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
<?php
/**
* Test services for name collisions.
*
* Let we have two service interfaces called Foo\Bar\Service\SomeBazV1Interface and Foo\Bar\Service\Some\BazV1Interface.
* Given current name generation logic both are going to be translated to BarSomeBazV1. This test checks such things
* are not going to happen.
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\AsynchronousOperations\Model;
use Magento\Framework\Exception\BulkException;
use Magento\Framework\Phrase;
use Magento\Framework\Registry;
use Magento\Framework\Webapi\Exception;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\TestFramework\MessageQueue\PublisherConsumerController;
use Magento\TestFramework\MessageQueue\EnvironmentPreconditionException;
use Magento\TestFramework\MessageQueue\PreconditionFailedException;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class MassScheduleTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string[]
*/
protected $consumers = ['async.operations.all'];
/**
* @var ObjectManagerInterface
*/
protected $objectManager;
/**
* @var MassSchedule
*/
private $massSchedule;
/**
* @var Collection
*/
private $collection;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var PublisherConsumerController
*/
private $publisherConsumerController;
/**
* @var array
*/
private $skus = [];
/**
* @var Registry
*/
private $registry;
protected function setUp()
{
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->massSchedule = $this->objectManager->create(MassSchedule::class);
$this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt";
$this->collection = $this->objectManager->create(Collection::class);
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
/** @var PublisherConsumerController publisherConsumerController */
$this->publisherConsumerController = $this->objectManager->create(PublisherConsumerController::class, [
'consumers' => $this->consumers,
'logFilePath' => $this->logFilePath,
'appInitParams' => \Magento\TestFramework\Helper\Bootstrap::getInstance()->getAppInitParams()
]);
try {
$this->publisherConsumerController->initialize();
} catch (EnvironmentPreconditionException $e) {
$this->markTestSkipped($e->getMessage());
} catch (PreconditionFailedException $e) {
$this->fail($e->getMessage());
}
parent::setUp();
}
/**
* @dataProvider productDataProvider
* @param ProductInterface[] $products
*/
public function testScheduleMass($products)
{
try {
$this->sendBulk($products);
} catch (BulkException $bulkException) {
$this->fail('Bulk was not accepted in full');
}
//assert all products are created
try {
$this->publisherConsumerController->waitForAsynchronousResult(
[$this, 'assertProductExists'],
[$this->skus, count($this->skus)]
);
} catch (PreconditionFailedException $e) {
$this->fail("Not all products were created");
}
}
public function sendBulk($products)
{
$this->skus = [];
foreach ($products as $data) {
if (isset($data['product'])) {
$this->skus[] = $data['product']->getSku();
}
}
$this->clearProducts();
$result = $this->massSchedule->publishMass(
'async.magento.catalog.api.productrepositoryinterface.save.post',
$products
);
//assert bulk accepted with no errors
$this->assertFalse($result->isErrors());
//assert number of products sent to queue
$this->assertCount(count($this->skus), $result->getRequestItems());
}
public function tearDown()
{
$this->publisherConsumerController->stopConsumers();
$this->clearProducts();
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) {
//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]));
}
}
public function assertProductExists($productsSkus, $count)
{
$collection = $this->objectManager->create(Collection::class)
->addAttributeToFilter('sku', ['in' => $productsSkus])
->load();
$size = $collection->getSize();
return $size == $count;
}
/**
* @dataProvider productExceptionDataProvider
* @param ProductInterface[] $products
*/
public function testScheduleMassOneEntityFailure($products)
{
try {
$this->sendBulk($products);
} catch (BulkException $e) {
$this->assertCount(1, $e->getErrors());
$errors = $e->getErrors();
$this->assertInstanceOf(\Magento\Framework\Exception\LocalizedException::class, $errors[0]);
$this->assertEquals("Error processing 1 element of input data", $errors[0]->getMessage());
$reasonException = $errors[0]->getPrevious();
$expectedErrorMessage = "Data item corresponding to \"product\" " .
"must be specified in the message with topic " .
"\"async.magento.catalog.api.productrepositoryinterface.save.post\".";
$this->assertEquals(
$expectedErrorMessage,
$reasonException->getMessage()
);
/** @var \Magento\WebapiAsync\Model\AsyncResponse $bulkStatus */
$bulkStatus = $e->getData();
$this->assertTrue($bulkStatus->isErrors());
/** @var ItemStatus[] $items */
$items = $bulkStatus->getRequestItems();
$this->assertCount(2, $items);
$this->assertEquals(ItemStatus::STATUS_ACCEPTED, $items[0]->getStatus());
$this->assertEquals(0, $items[0]->getId());
$this->assertEquals(ItemStatus::STATUS_REJECTED, $items[1]->getStatus());
$this->assertEquals(1, $items[1]->getId());
$this->assertEquals($expectedErrorMessage, $items[1]->getErrorMessage());
}
//assert one products is created
try {
$this->publisherConsumerController->waitForAsynchronousResult(
[$this, 'assertProductExists'],
[$this->skus, count($this->skus)]
);
} catch (PreconditionFailedException $e) {
$this->fail("Not all products were created");
}
}
private function getProduct()
{
/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(ProductInterface::class);
$product
->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product 1')
->setSku('unique-simple-product1')
->setPrice(10)
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0]);
return $product;
}
public function productDataProvider()
{
return [
'single_product' => [
[['product' => $this->getProduct()]],
],
'multiple_products' => [
[
['product' => $this->getProduct()
->setName('Simple Product 3')
->setSku('unique-simple-product3')
->setMetaTitle('meta title 3')
],
['product' => $this->getProduct()
->setName('Simple Product 2')
->setSku('unique-simple-product2')
->setMetaTitle('meta title 2')
]
]
],
];
}
public function productExceptionDataProvider()
{
return [
'single_product' => [
[['product' => $this->getProduct()]],
],
'multiple_products' => [
[
['product' => $this->getProduct()],
['customer' => $this->getProduct()]
]
],
];
}
}