This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,129 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Framework\MessageQueue;
use Magento\Framework\App\DeploymentConfig\FileReader;
use Magento\Framework\App\DeploymentConfig\Writer;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Config\File\ConfigFilePool;
use Magento\Framework\Filesystem;
use Magento\Framework\MessageQueue\Config;
use Magento\Framework\MessageQueue\Config\Data;
use Magento\Framework\MessageQueue\Config\Reader\Xml;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class ConfigGetConsumersTest extends TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var Config
*/
private $configSubject;
/**
* @var FileReader
*/
private $fileReader;
/**
* @var array
*/
private $envConfigBackup;
/**
* @var Writer
*/
private $fileWriter;
/**
* @var Xml
*/
private $xmlReader;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->fileWriter = $this->objectManager->get(Writer::class);
$this->xmlReader = $this->objectManager->create(Xml::class);
$this->fileReader = $this->objectManager->get(FileReader::class);
$this->envConfigBackup = $this->fileReader->load(ConfigFilePool::APP_ENV);
$customEnvConfig = $this->buildCustomEnvConfigWithConsumers();
$this->fileWriter->saveConfig([ConfigFilePool::APP_ENV => $customEnvConfig]);
/** @var Data data */
$configData = $this->objectManager->create(
Data::class,
[
'cacheId' => uniqid(microtime())
]
);
$this->configSubject = $this->objectManager->create(
Config::class,
[
'queueConfigData' => $configData
]
);
}
public function testGetConsumers(): void
{
$consumers = $this->configSubject->getConsumers();
foreach ($consumers as $consumer) {
$this->assertIsString($consumer['name']);
$this->assertIsArray($consumer['handlers']);
}
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$filesystem = $this->objectManager->get(Filesystem::class);
$configFilePool = $this->objectManager->get(ConfigFilePool::class);
$filesystem->getDirectoryWrite(DirectoryList::CONFIG)->writeFile(
$configFilePool->getPath(ConfigFilePool::APP_ENV),
"<?php\n return array();\n"
);
$this->fileWriter->saveConfig([ConfigFilePool::APP_ENV => $this->envConfigBackup]);
}
private function buildCustomEnvConfigWithConsumers(): array
{
$data = $this->xmlReader->read();
$names = array_keys($data['consumers']);
$consumers = [];
foreach ($names as $name) {
$consumers[$name] = ['connection' => 'amqp'];
}
return [
'queue' => [
'amqp' => [
'host' => 'localhost',
'port' => '5672',
'user' => 'guest',
'password' => 'guest',
'virtualhost' => '/',
'ssl' => ''
],
'consumers' => $consumers
],
];
}
}
@@ -0,0 +1,229 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue;
/**
* Test of communication configuration reading and parsing.
*
* @magentoCache config disabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppIsolation enabled
*/
public function testGetConsumers()
{
$consumers = $this->getConfigData()->getConsumers();
$expectedParsedConfig = include __DIR__ . '/_files/valid_expected_queue.php';
$this->assertEquals($expectedParsedConfig['consumers'], $consumers);
}
/**
* @magentoAppIsolation enabled
*/
public function testGetPublishers()
{
$publishers = $this->getConfigData()->getPublishers();
$expectedParsedConfig = include __DIR__ . '/_files/valid_expected_queue.php';
$this->assertEquals($expectedParsedConfig['publishers'], $publishers);
}
/**
* @magentoAppIsolation enabled
*/
public function testGetBinds()
{
$binds = $this->getConfigData()->getBinds();
$expectedParsedConfig = include __DIR__ . '/_files/valid_expected_queue.php';
$this->assertEquals($expectedParsedConfig['binds'], $binds);
}
/**
* @magentoAppIsolation enabled
*/
public function testGetMaps()
{
$topicName = 'topic.broker.test';
$queue = $this->getConfigData()->getQueuesByTopic($topicName);
$expectedParsedConfig = include __DIR__ . '/_files/valid_expected_queue.php';
$this->assertEquals(
$expectedParsedConfig['exchange_topic_to_queues_map']['magento--topic.broker.test'],
$queue
);
}
/**
* @magentoAppIsolation enabled
*/
public function testGetTopic()
{
$topicName = 'topic.broker.test';
$topic = $this->getConfigData()->getTopic($topicName);
$expectedParsedConfig = include __DIR__ . '/_files/valid_expected_queue.php';
$this->assertEquals($expectedParsedConfig['topics'][$topicName], $topic);
}
/**
* Return mocked config data
*
* @return \Magento\Framework\MessageQueue\ConfigInterface
*/
private function getConfigData()
{
return $this->getConfigInstance(
[
__DIR__ . '/_files/valid_new_queue.xml'
]
);
}
/**
* Create config instance initialized with configuration from $configFilePath
*
* @param string|string[] $configFilePath
* @param string|null $envConfigFilePath
* @return \Magento\Framework\MessageQueue\ConfigInterface
*/
protected function getConfigInstance($configFilePath, $envConfigFilePath = null)
{
$content = [];
if (is_array($configFilePath)) {
foreach ($configFilePath as $file) {
$content[] = file_get_contents($file);
}
} else {
$content[] = file_get_contents($configFilePath);
}
$fileResolver = $this->getMockForAbstractClass(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolver->expects($this->any())
->method('get')
->willReturn($content);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$topicConverter = $objectManager->create(
\Magento\Framework\MessageQueue\Config\Reader\Xml\Converter\TopicConfig::class,
[
'communicationConfig' => $this->getCommunicationConfigInstance()
]
);
$converter = $objectManager->create(
\Magento\Framework\MessageQueue\Config\Reader\Xml\CompositeConverter::class,
[
'converters' => [
['converter' => $topicConverter, 'sortOrder' => 10]
]
]
);
$xmlReader = $objectManager->create(
\Magento\Framework\MessageQueue\Config\Reader\Xml::class,
[
'fileResolver' => $fileResolver,
'converter' => $converter,
]
);
$deploymentConfigReader = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig\Reader::class)
->disableOriginalConstructor()
->setMethods([])
->getMock();
$envConfigData = include $envConfigFilePath ?: __DIR__ . '/_files/valid_queue_input.php';
$deploymentConfigReader->expects($this->any())->method('load')->willReturn($envConfigData);
$deploymentConfig = $objectManager->create(
\Magento\Framework\App\DeploymentConfig::class,
['reader' => $deploymentConfigReader]
);
$envReader = $objectManager->create(
\Magento\Framework\MessageQueue\Config\Reader\Env::class,
[
'deploymentConfig' => $deploymentConfig
]
);
$methodsMap = $objectManager->create(\Magento\Framework\Reflection\MethodsMap::class);
$envValidator = $objectManager->create(
\Magento\Framework\MessageQueue\Config\Reader\Env\Validator::class,
[
'methodsMap' => $methodsMap
]
);
$compositeReader = $objectManager->create(
\Magento\Framework\MessageQueue\Config\CompositeReader::class,
[
'readers' => [
['reader' => $xmlReader, 'sortOrder' => 10],
['reader' => $envReader, 'sortOrder' => 20]
],
]
);
/** @var \Magento\Framework\MessageQueue\Config $configData */
$configData = $objectManager->create(
\Magento\Framework\MessageQueue\Config\Data::class,
[
'reader' => $compositeReader,
'envValidator' => $envValidator
]
);
return $objectManager->create(
\Magento\Framework\MessageQueue\Config::class,
['queueConfigData' => $configData]
);
}
/**
* Get mocked Communication Config Instance
*
* @return \Magento\Framework\Communication\ConfigInterface
*/
private function getCommunicationConfigInstance()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$fileResolver = $this->getMockForAbstractClass(\Magento\Framework\Config\FileResolverInterface::class);
$fileResolver->expects($this->any())
->method('get')
->willReturn([file_get_contents(__DIR__ . '/_files/communication.xml')]);
$xmlReader = $objectManager->create(
\Magento\Framework\Communication\Config\Reader\XmlReader::class,
[
'fileResolver' => $fileResolver,
]
);
$compositeReader = $objectManager->create(
\Magento\Framework\Communication\Config\CompositeReader::class,
[
'readers' => [
['reader' => $xmlReader, 'sortOrder' => 10],
[
'reader' => $objectManager->create(
\Magento\Framework\Communication\Config\Reader\EnvReader::class
),
'sortOrder' => 20
]
],
]
);
/** @var \Magento\Framework\Communication\Config $configData */
$configData = $objectManager->create(
\Magento\Framework\Communication\Config\Data::class,
[
'reader' => $compositeReader
]
);
$config = $objectManager->create(
\Magento\Framework\Communication\ConfigInterface::class,
[
'configData' => $configData
]
);
return $config;
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\Consumer;
use Magento\Framework\MessageQueue\Consumer\Config\ConsumerConfigItem\Handler\Iterator as HandlerIterator;
use Magento\Framework\MessageQueue\DefaultValueProvider;
/**
* Test of queue consumer configuration reading and parsing.
*
* @magentoCache config disabled
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var DefaultValueProvider
*/
private $defaultValueProvider;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->defaultValueProvider = $this->objectManager->get(DefaultValueProvider::class);
}
public function testGetConsumers()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumers = $config->getConsumers();
$consumer = $config->getConsumer('consumer1');
$this->assertEquals(
$consumer,
$consumers['consumer1'],
'Consumers received from collection and via getter must be the same'
);
$this->assertEquals('consumer1', $consumer->getName());
$this->assertEquals('queue1', $consumer->getQueue());
$this->assertEquals('amqp', $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\BatchConsumer::class, $consumer->getConsumerInstance());
$this->assertEquals('100', $consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(1, $handlers);
$this->assertEquals('handlerMethodOne', $handlers[0]->getMethod());
$this->assertEquals('Magento\TestModuleMessageQueueConfiguration\HandlerOne', $handlers[0]->getType());
}
public function testGetConsumerWithDefaultValues()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumer = $config->getConsumer('consumer5');
$this->assertEquals('consumer5', $consumer->getName());
$this->assertEquals('queue5', $consumer->getQueue());
$this->assertEquals($this->defaultValueProvider->getConnection(), $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\ConsumerInterface::class, $consumer->getConsumerInstance());
$this->assertNull($consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(0, $handlers);
}
/**
*/
public function testGetUndeclaredConsumer()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Consumer \'undeclaredConsumer\' is not declared.');
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$config->getConsumer('undeclaredConsumer');
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\Consumer;
use Magento\Framework\MessageQueue\Consumer\Config\ConsumerConfigItem\Handler\Iterator as HandlerIterator;
use Magento\Framework\MessageQueue\DefaultValueProvider;
/**
* Test access to consumer configuration declared in deprecated queue.xml configs using Consumer\ConfigInterface.
*
* @magentoCache config disabled
*/
class DeprecatedConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var DefaultValueProvider
*/
private $defaultValueProvider;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->defaultValueProvider = $this->objectManager->get(DefaultValueProvider::class);
}
public function testGetConsumerMultipleHandlersFromCommunicationConfig()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumer = $config->getConsumer('deprecatedConfigAsyncBoolConsumer');
$this->assertEquals('deprecatedConfigAsyncBoolConsumer', $consumer->getName());
$this->assertEquals('deprecated.config.queue.2', $consumer->getQueue());
$this->assertEquals('db', $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\ConsumerInterface::class, $consumer->getConsumerInstance());
$this->assertNull($consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(2, $handlers);
$this->assertEquals('methodWithBoolParam', $handlers[0]->getMethod());
$this->assertEquals('Magento\TestModuleMessageQueueConfiguration\AsyncHandler', $handlers[0]->getType());
$this->assertEquals('methodWithMixedParam', $handlers[1]->getMethod());
$this->assertEquals('Magento\TestModuleMessageQueueConfiguration\AsyncHandler', $handlers[1]->getType());
}
public function testGetConsumerCustomHandler()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumer = $config->getConsumer('deprecatedConfigAsyncMixedConsumer');
$this->assertEquals('deprecatedConfigAsyncMixedConsumer', $consumer->getName());
$this->assertEquals('deprecated.config.queue.3', $consumer->getQueue());
$this->assertEquals($this->defaultValueProvider->getConnection(), $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\ConsumerInterface::class, $consumer->getConsumerInstance());
$this->assertNull($consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(1, $handlers);
$this->assertEquals('methodWithMixedParam', $handlers[0]->getMethod());
$this->assertEquals('Magento\TestModuleMessageQueueConfiguration\AsyncHandler', $handlers[0]->getType());
}
public function testGetConsumerCustomConnectionSync()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumer = $config->getConsumer('deprecatedConfigSyncBoolConsumer');
$this->assertEquals('deprecatedConfigSyncBoolConsumer', $consumer->getName());
$this->assertEquals('deprecated.config.queue.4', $consumer->getQueue());
$this->assertEquals('db', $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\ConsumerInterface::class, $consumer->getConsumerInstance());
$this->assertNull($consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(1, $handlers);
$this->assertEquals('methodWithBoolParam', $handlers[0]->getMethod());
$this->assertEquals('Magento\TestModuleMessageQueueConfiguration\SyncHandler', $handlers[0]->getType());
}
public function testGetConsumerCustomConsumerAndMaxMessages()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumer = $config->getConsumer('deprecatedConfigAsyncStringConsumer');
$this->assertEquals('deprecatedConfigAsyncStringConsumer', $consumer->getName());
$this->assertEquals('deprecated.config.queue.1', $consumer->getQueue());
$this->assertEquals($this->defaultValueProvider->getConnection(), $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\BatchConsumer::class, $consumer->getConsumerInstance());
$this->assertEquals(200, $consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(0, $handlers);
}
public function testGetOverlapWithQueueConfig()
{
/** @var \Magento\Framework\MessageQueue\Consumer\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Consumer\ConfigInterface::class);
$consumer = $config->getConsumer('overlappingConsumerDeclaration');
$this->assertEquals('overlappingConsumerDeclaration', $consumer->getName());
$this->assertEquals('consumer.config.queue', $consumer->getQueue());
$this->assertEquals('amqp', $consumer->getConnection());
$this->assertEquals(\Magento\Framework\MessageQueue\ConsumerInterface::class, $consumer->getConsumerInstance());
$this->assertNull($consumer->getMaxMessages());
$handlers = $consumer->getHandlers();
$this->assertInstanceOf(HandlerIterator::class, $handlers);
$this->assertCount(0, $handlers);
}
}
@@ -0,0 +1,229 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\MessageQueue\MessageEncoder;
use Magento\Framework\Communication\Config;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class MessageEncoderTest extends \PHPUnit\Framework\TestCase
{
/** @var MessageEncoder */
protected $encoder;
/** @var \Magento\Framework\ObjectManagerInterface */
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->encoder = $this->objectManager->create(MessageEncoder::class);
$this->setBackwardCompatibleProperty(
$this->encoder,
'communicationConfig',
$this->getConfig()
);
parent::setUp();
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testEncode()
{
/** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$fixtureCustomerId = 1;
$customer = $customerRepository->getById($fixtureCustomerId);
/** @var \Magento\Customer\Api\Data\CustomerExtensionInterface $customerExtension */
$customerExtension = $this->objectManager->create(\Magento\Customer\Api\Data\CustomerExtension::class);
$customerExtension->setTestGroupCode('Some Group Code');
$customer->setExtensionAttributes($customerExtension);
$encodedCustomerData = json_decode($this->encoder->encode('customer.created', $customer), true);
$createdAt = $customer->getCreatedAt();
$updatedAt = $customer->getUpdatedAt();
$expectedEncodedCustomerData = json_decode($this->getCustomerDataAsJson($createdAt, $updatedAt), true);
$this->assertEquals($expectedEncodedCustomerData, $encodedCustomerData);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testEncodeArrayOfEntities()
{
/** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$fixtureCustomerId = 1;
$customer = $customerRepository->getById($fixtureCustomerId);
/** @var \Magento\Customer\Api\Data\CustomerExtensionInterface $customerExtension */
$customerExtension = $this->objectManager->create(\Magento\Customer\Api\Data\CustomerExtension::class);
$customerExtension->setTestGroupCode('Some Group Code');
$customer->setExtensionAttributes($customerExtension);
$encodedCustomerData = json_decode($this->encoder->encode('customer.list.retrieved', [$customer]), true);
$createdAt = $customer->getCreatedAt();
$updatedAt = $customer->getUpdatedAt();
$expectedEncodedCustomerData = json_decode($this->getCustomerDataAsJson($createdAt, $updatedAt), true);
$this->assertEquals($expectedEncodedCustomerData, $encodedCustomerData[0]);
}
public function testDecode()
{
$encodedMessage = $this->getCustomerDataAsJson('2015-07-22 12:43:36', '2015-07-22 12:45:36');
/** @var \Magento\Customer\Api\Data\CustomerInterface $decodedCustomerObject */
$decodedCustomerObject = $this->encoder->decode('customer.created', $encodedMessage);
$this->assertInstanceOf(\Magento\Customer\Api\Data\CustomerInterface::class, $decodedCustomerObject);
$this->assertEquals('customer@example.com', $decodedCustomerObject->getEmail());
$this->assertEquals(1, $decodedCustomerObject->getGroupId());
$this->assertInstanceOf(
\Magento\Customer\Api\Data\CustomerExtensionInterface::class,
$decodedCustomerObject->getExtensionAttributes()
);
$this->assertEquals('Some Group Code', $decodedCustomerObject->getExtensionAttributes()->getTestGroupCode());
$addresses = $decodedCustomerObject->getAddresses();
$this->assertCount(1, $addresses, "Address was not decoded.");
$this->assertInstanceOf(
\Magento\Customer\Api\Data\AddressInterface::class,
$addresses[0]
);
$this->assertEquals('3468676', $addresses[0]->getTelephone());
$this->assertTrue($addresses[0]->isDefaultBilling());
$this->assertInstanceOf(
\Magento\Customer\Api\Data\RegionInterface::class,
$addresses[0]->getRegion()
);
$this->assertEquals('AL', $addresses[0]->getRegion()->getRegionCode());
}
/**
*/
public function testDecodeInvalidMessageFormat()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Error occurred during message decoding');
$this->encoder->decode('customer.created', "{");
}
/**
*/
public function testDecodeInvalidMessage()
{
$this->expectException(LocalizedException::class);
$message = 'customer.created" must be an instance of "Magento\Customer\Api\Data\CustomerInterface".';
$this->expectExceptionMessage($message);
$this->encoder->decode('customer.created', '{"not_existing_field": "value"}');
}
/**
*/
public function testDecodeIncorrectMessage()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Error occurred during message decoding');
$this->encoder->decode('customer.created', "{");
}
/**
* @return \Magento\Framework\MessageQueue\Config
*/
protected function getConfig()
{
$newData = include __DIR__ . '/_files/encoder_communication.php';
/** @var \Magento\Framework\Communication\Config\Data $configData */
$configData = $this->objectManager->create(\Magento\Framework\Communication\Config\Data::class);
$configData->reset();
$configData->merge($newData);
$config = $this->objectManager->create(Config::class, ['configData' => $configData]);
return $config;
}
/**
* Get fixture customer data in Json format
*
* @param string $createdAt
* @param string $updatedAt
* @return string
*/
protected function getCustomerDataAsJson($createdAt, $updatedAt)
{
return <<<JSON
{
"id": 1,
"group_id": 1,
"default_billing": "1",
"default_shipping": "1",
"created_at": "{$createdAt}",
"updated_at": "{$updatedAt}",
"email": "customer@example.com",
"firstname": "John",
"lastname": "Smith",
"middlename": "A",
"prefix": "Mr.",
"suffix": "Esq.",
"gender": 0,
"store_id": 1,
"taxvat": "12",
"website_id": 1,
"addresses": [
{
"id": 1,
"customer_id": 1,
"region": {
"region_code": "AL",
"region": "Alabama",
"region_id": 1
},
"region_id": 1,
"country_id": "US",
"street": [
"Green str, 67"
],
"company": "CompanyName",
"telephone": "3468676",
"postcode": "75477",
"city": "CityM",
"firstname": "John",
"lastname": "Smith",
"default_shipping": true,
"default_billing": true
}
],
"disable_auto_group_change": 0,
"extension_attributes": {
"test_group_code": "Some Group Code"
}
}
JSON;
}
/**
* Set mocked property
*
* @param object $object
* @param string $propertyName
* @param object $propertyValue
* @return void
*/
public function setBackwardCompatibleProperty($object, $propertyName, $propertyValue)
{
$reflection = new \ReflectionClass(get_class($object));
$reflectionProperty = $reflection->getProperty($propertyName);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, $propertyValue);
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\Publisher;
use Magento\Framework\MessageQueue\DefaultValueProvider;
/**
* Test of queue publisher configuration reading and parsing.
*
* @magentoCache config disabled
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var DefaultValueProvider
*/
private $defaultValueProvider;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->defaultValueProvider = $this->objectManager->get(DefaultValueProvider::class);
}
public function testGetPublishersWithOneEnabledConnection()
{
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$publishers = $config->getPublishers();
$publisher = $config->getPublisher('topic.message.queue.config.01');
$itemFromList = null;
foreach ($publishers as $item) {
if ($item->getTopic() == 'topic.message.queue.config.01') {
$itemFromList = $item;
break;
}
}
$this->assertEquals($publisher, $itemFromList, 'Inconsistent publisher object');
$this->assertEquals('topic.message.queue.config.01', $publisher->getTopic(), 'Incorrect topic name');
$this->assertFalse($publisher->isDisabled(), 'Incorrect publisher state');
/** @var \Magento\Framework\MessageQueue\Publisher\Config\PublisherConnectionInterface $connection */
$connection = $publisher->getConnection();
$this->assertEquals('amqp', $connection->getName(), 'Incorrect connection name');
$this->assertEquals('magento2', $connection->getExchange(), 'Incorrect exchange name');
$this->assertFalse($connection->isDisabled(), 'Incorrect connection status');
}
public function testGetPublisherConnectionWithoutConfiguredExchange()
{
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$publisher = $config->getPublisher('topic.message.queue.config.04');
$connection = $publisher->getConnection();
$this->assertEquals('magento', $connection->getExchange(), 'Incorrect exchange name');
}
public function testGetPublishersWithoutEnabledConnection()
{
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$publisher = $config->getPublisher('topic.message.queue.config.02');
$this->assertEquals('topic.message.queue.config.02', $publisher->getTopic(), 'Incorrect topic name');
$this->assertFalse($publisher->isDisabled(), 'Incorrect publisher state');
/** @var \Magento\Framework\MessageQueue\Publisher\Config\PublisherConnectionInterface $connection */
$connection = $publisher->getConnection();
$this->assertEquals(
$this->defaultValueProvider->getConnection(),
$connection->getName(),
'Incorrect default connection name'
);
$this->assertEquals('magento', $connection->getExchange(), 'Incorrect default exchange name');
$this->assertFalse($connection->isDisabled(), 'Incorrect connection status');
}
/**
*/
public function testGetDisabledPublisherThrowsException()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Publisher \'topic.message.queue.config.03\' is not declared.');
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$config->getPublisher('topic.message.queue.config.03');
}
}
@@ -0,0 +1,74 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\Publisher;
use Magento\Framework\MessageQueue\DefaultValueProvider;
/**
* Test access to publisher configuration declared in deprecated queue.xml configs using Publisher\ConfigInterface.
*
* @magentoCache config disabled
*/
class DeprecatedConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var DefaultValueProvider
*/
private $defaultValueProvider;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->defaultValueProvider = $this->objectManager->get(DefaultValueProvider::class);
}
public function testGetPublisher()
{
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$publisher = $config->getPublisher('deprecated.config.async.string.topic');
$this->assertEquals('deprecated.config.async.string.topic', $publisher->getTopic());
$this->assertFalse($publisher->isDisabled());
$connection = $publisher->getConnection();
$this->assertEquals($this->defaultValueProvider->getConnection(), $connection->getName());
$this->assertEquals('magento', $connection->getExchange());
$this->assertFalse($connection->isDisabled());
}
public function testGetPublisherCustomConnection()
{
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$publisher = $config->getPublisher('deprecated.config.sync.bool.topic');
$this->assertEquals('deprecated.config.sync.bool.topic', $publisher->getTopic());
$this->assertFalse($publisher->isDisabled());
$connection = $publisher->getConnection();
$this->assertEquals('db', $connection->getName());
$this->assertEquals('customExchange', $connection->getExchange());
$this->assertFalse($connection->isDisabled());
}
public function testGetOverlapWithQueueConfig()
{
/** @var \Magento\Framework\MessageQueue\Publisher\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Publisher\ConfigInterface::class);
$publisher = $config->getPublisher('overlapping.topic.declaration');
$this->assertEquals('overlapping.topic.declaration', $publisher->getTopic());
$this->assertFalse($publisher->isDisabled());
$connection = $publisher->getConnection();
$this->assertEquals($this->defaultValueProvider->getConnection(), $connection->getName());
$this->assertEquals('magento', $connection->getExchange());
$this->assertFalse($connection->isDisabled());
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\Topology;
use Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\BindingInterface;
/**
* Test of queue topology configuration reading and parsing.
*
* @magentoCache config disabled
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
public function testGetExchangeByName()
{
/** @var \Magento\Framework\MessageQueue\Topology\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Topology\ConfigInterface::class);
$exchange = $config->getExchange('magento-topic-based-exchange1', 'amqp');
$this->assertEquals('magento-topic-based-exchange1', $exchange->getName());
$this->assertEquals('topic', $exchange->getType());
$this->assertEquals('amqp', $exchange->getConnection());
$exchangeArguments = $exchange->getArguments();
$expectedArguments = ['alternate-exchange' => 'magento-log-exchange'];
$this->assertEquals($expectedArguments, $exchangeArguments);
/** @var BindingInterface $binding */
$binding = $exchange->getBindings()->current();
$this->assertEquals('queue--topic-queue1--anotherTopic1', $binding->getId());
$this->assertEquals('anotherTopic1', $binding->getTopic());
$this->assertEquals('queue', $binding->getDestinationType());
$this->assertEquals('topic-queue1', $binding->getDestination());
$bindingArguments = $binding->getArguments();
$expectedArguments = ['argument1' => 'value'];
$this->assertEquals($expectedArguments, $bindingArguments);
}
public function testGetExchangeByNameWithDefaultValues()
{
/** @var \Magento\Framework\MessageQueue\Topology\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Topology\ConfigInterface::class);
$exchange = $config->getExchange('magento-topic-based-exchange2', 'amqp');
$this->assertEquals('magento-topic-based-exchange2', $exchange->getName());
$this->assertEquals('topic', $exchange->getType());
$this->assertEquals('amqp', $exchange->getConnection());
$exchangeArguments = $exchange->getArguments();
$expectedArguments = [
'alternate-exchange' => 'magento-log-exchange',
'arrayValue' => [
'element01' => '10',
'element02' => '20',
]
];
$this->assertEquals($expectedArguments, $exchangeArguments);
/** @var BindingInterface $binding */
$binding = $exchange->getBindings()->current();
$this->assertEquals('queue--topic-queue2--anotherTopic2', $binding->getId());
$this->assertEquals('anotherTopic2', $binding->getTopic());
$this->assertEquals('queue', $binding->getDestinationType());
$this->assertEquals('topic-queue2', $binding->getDestination());
$bindingArguments = $binding->getArguments();
$expectedArguments = ['argument1' => 'value', 'argument2' => true, 'argument3' => 150];
$this->assertEquals($expectedArguments, $bindingArguments);
}
public function testGetAllExchanges()
{
/** @var \Magento\Framework\MessageQueue\Topology\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Topology\ConfigInterface::class);
$exchanges = $config->getExchanges();
$expectedResults = ['magento-topic-based-exchange1', 'magento-topic-based-exchange2'];
$actual = [];
foreach ($exchanges as $exchange) {
$actual[] = $exchange->getName();
}
$this->assertEmpty(array_diff($expectedResults, $actual));
}
}
@@ -0,0 +1,124 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\Topology;
use Magento\Framework\MessageQueue\DefaultValueProvider;
use Magento\Framework\MessageQueue\Topology\Config\ExchangeConfigItem\Binding\Iterator as BindingIterator;
/**
* Test access to topology configuration declared in deprecated queue.xml configs using Topology\ConfigInterface.
*
* @magentoCache config disabled
*/
class DeprecatedConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var DefaultValueProvider
*/
private $defaultValueProvider;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->defaultValueProvider = $this->objectManager->get(DefaultValueProvider::class);
}
public function testGetTopology()
{
/** @var \Magento\Framework\MessageQueue\Topology\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Topology\ConfigInterface::class);
$topology = $config->getExchange('deprecatedExchange', 'db');
$this->assertEquals('deprecatedExchange', $topology->getName());
$this->assertEquals('topic', $topology->getType());
$this->assertEquals('db', $topology->getConnection());
$this->assertTrue($topology->isDurable());
$this->assertFalse($topology->isAutoDelete());
$this->assertFalse($topology->isInternal());
$arguments = $topology->getArguments();
$this->assertIsArray($arguments);
$this->assertCount(0, $arguments);
// Verify bindings
$bindings = $topology->getBindings();
$this->assertInstanceOf(BindingIterator::class, $bindings);
$this->assertCount(1, $bindings);
$bindingId = 'queue--deprecated.config.queue.2--deprecated.config.async.bool.topic';
$this->assertArrayHasKey($bindingId, $bindings);
$binding = $bindings[$bindingId];
$this->assertEquals('queue', $binding->getDestinationType());
$this->assertEquals('deprecated.config.queue.2', $binding->getDestination());
$this->assertFalse($binding->isDisabled());
$this->assertEquals('deprecated.config.async.bool.topic', $binding->getTopic());
$arguments = $binding->getArguments();
$this->assertIsArray($arguments);
$this->assertCount(0, $arguments);
}
public function testGetTopologyOverlapWithQueueConfig()
{
/** @var \Magento\Framework\MessageQueue\Topology\ConfigInterface $config */
$config = $this->objectManager->create(\Magento\Framework\MessageQueue\Topology\ConfigInterface::class);
$topology = $config->getExchange('overlappingDeprecatedExchange', $this->defaultValueProvider->getConnection());
$this->assertEquals('overlappingDeprecatedExchange', $topology->getName());
$this->assertEquals('topic', $topology->getType());
$this->assertEquals($this->defaultValueProvider->getConnection(), $topology->getConnection());
$this->assertTrue($topology->isDurable());
$this->assertFalse($topology->isAutoDelete());
$this->assertFalse($topology->isInternal());
$arguments = $topology->getArguments();
$this->assertIsArray($arguments);
$this->assertCount(0, $arguments);
// Verify bindings
$bindings = $topology->getBindings();
$this->assertInstanceOf(BindingIterator::class, $bindings);
$this->assertCount(3, $bindings);
// Note that connection was changed for this binding during merge with topology config
// since we do not support exchanges with the same names on different connections
$bindingId = 'queue--consumer.config.queue--overlapping.topic.declaration';
$this->assertArrayHasKey($bindingId, $bindings);
$binding = $bindings[$bindingId];
$this->assertEquals('queue', $binding->getDestinationType());
$this->assertEquals('consumer.config.queue', $binding->getDestination());
$this->assertFalse($binding->isDisabled());
$this->assertEquals('overlapping.topic.declaration', $binding->getTopic());
$arguments = $binding->getArguments();
$this->assertIsArray($arguments);
$this->assertCount(0, $arguments);
$bindingId = 'queue--topology.config.queue--overlapping.topic.declaration';
$this->assertArrayHasKey($bindingId, $bindings);
$binding = $bindings[$bindingId];
$this->assertEquals('queue', $binding->getDestinationType());
$this->assertEquals('topology.config.queue', $binding->getDestination());
$this->assertFalse($binding->isDisabled());
$this->assertEquals('overlapping.topic.declaration', $binding->getTopic());
$arguments = $binding->getArguments();
$this->assertIsArray($arguments);
$this->assertCount(0, $arguments);
$bindingId = 'queue--topology.config.queue--deprecated.config.async.string.topic';
$this->assertArrayHasKey($bindingId, $bindings);
$binding = $bindings[$bindingId];
$this->assertEquals('queue', $binding->getDestinationType());
$this->assertEquals('topology.config.queue', $binding->getDestination());
$this->assertFalse($binding->isDisabled());
$this->assertEquals('deprecated.config.async.string.topic', $binding->getTopic());
$arguments = $binding->getArguments();
$this->assertIsArray($arguments);
$this->assertCount(0, $arguments);
}
}
@@ -0,0 +1,187 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Framework\MessageQueue;
use Magento\TestFramework\Helper\Amqp;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @see dev/tests/integration/_files/Magento/TestModuleMessageQueueConfiguration
* @see dev/tests/integration/_files/Magento/TestModuleMessageQueueConfigOverride
*/
class TopologyTest extends TestCase
{
/**
* List of declared exchanges.
*
* @var array
*/
private $declaredExchanges;
/**
* @var Amqp
*/
private $helper;
/**
* @return void
*/
protected function setUp(): void
{
$this->helper = Bootstrap::getObjectManager()->create(Amqp::class);
if (!$this->helper->isAvailable()) {
$this->fail('This test relies on RabbitMQ Management Plugin.');
}
$this->declaredExchanges = $this->helper->getExchanges();
}
/**
* @dataProvider exchangeDataProvider
* @param array $expectedConfig
* @param array $bindingConfig
*/
public function testTopologyInstallation(array $expectedConfig, array $bindingConfig): void
{
$name = $expectedConfig['name'];
$this->assertArrayHasKey($name, $this->declaredExchanges);
unset(
$this->declaredExchanges[$name]['message_stats'],
$this->declaredExchanges[$name]['user_who_performed_action'],
$this->declaredExchanges[$name]['policy']
);
$this->assertEquals(
$expectedConfig,
$this->declaredExchanges[$name],
'Invalid exchange configuration: ' . $name
);
$bindings = $this->helper->getExchangeBindings($name);
$bindings = array_map(static function ($value) {
unset($value['properties_key']);
return $value;
}, $bindings);
$this->assertEquals(
$bindingConfig,
$bindings,
'Invalid exchange bindings configuration: ' . $name
);
}
/**
* @return array
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function exchangeDataProvider(): array
{
$virtualHost = defined('RABBITMQ_VIRTUALHOST') ? RABBITMQ_VIRTUALHOST : Amqp::DEFAULT_VIRTUALHOST;
return [
'magento-topic-based-exchange1' => [
'exchangeConfig' => [
'name' => 'magento-topic-based-exchange1',
'vhost' => $virtualHost,
'type' => 'topic',
'durable' => true,
'auto_delete' => false,
'internal' => false,
'arguments' => [
'alternate-exchange' => 'magento-log-exchange'
],
],
'bindingConfig' => [
[
'source' => 'magento-topic-based-exchange1',
'vhost' => $virtualHost,
'destination' => 'topic-queue1',
'destination_type' => 'queue',
'routing_key' => 'anotherTopic1',
'arguments' => [
'argument1' => 'value'
],
],
]
],
'magento-topic-based-exchange2' => [
'exchangeConfig' => [
'name' => 'magento-topic-based-exchange2',
'vhost' => $virtualHost,
'type' => 'topic',
'durable' => true,
'auto_delete' => false,
'internal' => false,
'arguments' => [
'alternate-exchange' => 'magento-log-exchange',
'arrayValue' => ['10', '20']
],
],
'bindingConfig' => [
[
'source' => 'magento-topic-based-exchange2',
'vhost' => $virtualHost,
'destination' => 'topic-queue2',
'destination_type' => 'queue',
'routing_key' => 'anotherTopic2',
'arguments' => [
'argument1' => 'value',
'argument2' => true,
'argument3' => 150,
],
],
]
],
'magento-topic-based-exchange3' => [
'exchangeConfig' => [
'name' => 'magento-topic-based-exchange3',
'vhost' => $virtualHost,
'type' => 'topic',
'durable' => false,
'auto_delete' => true,
'internal' => true,
'arguments' => [],
],
'bindingConfig' => [],
],
'magento-topic-based-exchange4' => [
'exchangeConfig' => [
'name' => 'magento-topic-based-exchange4',
'vhost' => $virtualHost,
'type' => 'topic',
'durable' => true,
'auto_delete' => false,
'internal' => false,
'arguments' => [],
],
'bindingConfig' => [
[
'source' => 'magento-topic-based-exchange4',
'vhost' => $virtualHost,
'destination' => 'topic-queue1',
'destination_type' => 'queue',
'routing_key' => '#',
'arguments' => [
'test' => 'one'
],
],
[
'source' => 'magento-topic-based-exchange4',
'vhost' => $virtualHost,
'destination' => 'topic-queue2',
'destination_type' => 'queue',
'routing_key' => '*.*.*',
'arguments' => [],
],
]
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\TestModuleAsyncAmqp\Model\AsyncTestData;
class AsyncMultipleHandlersTest extends QueueTestCaseAbstract
{
/**
* @var string
*/
protected $expectedMessages;
/**
* @var string[]
*/
protected $consumers = [
'mtmh.queue.1.consumer',
'mtmh.queue.2.consumer',
];
/**
* @var string[]
*/
private $topicValueMap = [
'mtmh.topic.1' => 'mtmh.topic.1',
'mtmh.topic.2' => ['mtmh.topic.2-1', 'mtmh.topic.2-2']
];
/**
* @var string[]
*/
private $expectedValues = [
'string-mtmh.topic.1',
'mixed-mtmh.topic.1',
'array-mtmh.topic.2-1',
'array-mtmh.topic.2-2',
'mixed-mtmh.topic.2-1',
'mixed-mtmh.topic.2-2'
];
/**
* Verify that Queue Framework supports multiple topics per queue.
*
* Current test is not test of Web API framework itself,
* it just utilizes its infrastructure to test Message Queue.
*/
public function testAsynchronousRpcCommunication()
{
foreach ($this->topicValueMap as $topic => $data) {
$message = null;
if (is_array($data)) {
foreach ($data as $key => $value) {
/** @var AsyncTestData $testObject */
$testObject = $this->objectManager->create(AsyncTestData::class); // @phpstan-ignore-line
$testObject->setValue($value);
$testObject->setTextFilePath($this->logFilePath);
$message[$key] = $testObject;
}
} else {
$testObject = $this->objectManager->create(AsyncTestData::class); // @phpstan-ignore-line
$testObject->setValue($data);
$testObject->setTextFilePath($this->logFilePath);
$message = $testObject;
}
$this->publisher->publish($topic, $message);
}
$this->waitForAsynchronousResult(count($this->expectedValues), $this->logFilePath);
//assertions
foreach ($this->expectedValues as $item) {
$this->assertStringContainsString($item, file_get_contents($this->logFilePath));
}
}
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\TestModuleAsyncAmqp\Model\AsyncTestData;
class AsyncMultipleTopicsWithEachQueueTest extends QueueTestCaseAbstract
{
/**
* @var string[]
*/
protected $uniqueID;
/**
* @var AsyncTestData
*/
protected $msgObject;
/**
* @var string[]
*/
protected $consumers = ['queue.for.multiple.topics.test.y', 'queue.for.multiple.topics.test.z'];
/**
* @var string[]
*/
private $topics = ['multi.topic.queue.topic.y', 'multi.topic.queue.topic.z'];
/**
* Verify that Queue Framework processes multiple asynchronous topics sent to the same queue.
*
* Current test is not test of Web API framework itself, it just utilizes its infrastructure to test Message Queue.
*/
public function testAsyncMultipleTopicsPerQueue()
{
$this->msgObject = $this->objectManager->create(AsyncTestData::class); // @phpstan-ignore-line
foreach ($this->topics as $topic) {
// phpcs:ignore Magento2.Security.InsecureFunction
$this->uniqueID[$topic] = md5(uniqid($topic));
$this->msgObject->setValue($this->uniqueID[$topic] . "_" . $topic);
$this->msgObject->setTextFilePath($this->logFilePath);
$this->publisher->publish($topic, $this->msgObject);
}
$this->waitForAsynchronousResult(count($this->uniqueID), $this->logFilePath);
//assertions
foreach ($this->topics as $item) {
$this->assertStringContainsString(
$this->uniqueID[$item] . "_" . $item,
file_get_contents($this->logFilePath)
);
}
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase\DeprecatedFormat;
use Magento\Framework\MessageQueue\UseCase\QueueTestCaseAbstract;
use Magento\TestModuleAsyncAmqp\Model\AsyncTestData;
class AsyncMultiTopicsSeparateQueuesTest extends QueueTestCaseAbstract
{
/**
* @var string[]
*/
protected $uniqueID;
/**
* @var AsyncTestData
*/
protected $msgObject;
/**
* @var string[]
*/
protected $consumers = [
'queue.for.multiple.topics.test.c.deprecated',
'queue.for.multiple.topics.test.d.deprecated'
];
/**
* @var string[]
*/
private $topics = ['multi.topic.queue.topic.c.deprecated', 'multi.topic.queue.topic.d.deprecated'];
/**
* Verify that Queue Framework processes multiple asynchronous topics sent to the same queue.
*
* Current test is not test of Web API framework itself, it just utilizes its infrastructure to test Message Queue.
*/
public function testAsyncMultipleTopicsPerQueue()
{
$this->msgObject = $this->objectManager->create(AsyncTestData::class); // @phpstan-ignore-line
foreach ($this->topics as $topic) {
// phpcs:ignore Magento2.Security.InsecureFunction
$this->uniqueID[$topic] = md5(uniqid($topic));
$this->msgObject->setValue($this->uniqueID[$topic] . "_" . $topic);
$this->msgObject->setTextFilePath($this->logFilePath);
$this->publisher->publish($topic, $this->msgObject);
}
$this->waitForAsynchronousResult(count($this->uniqueID), $this->logFilePath);
//assertions
foreach ($this->topics as $item) {
$this->assertStringContainsString(
$this->uniqueID[$item] . "_" . $item,
file_get_contents($this->logFilePath)
);
}
}
}
@@ -0,0 +1,28 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase\DeprecatedFormat;
use Magento\Framework\MessageQueue\UseCase\QueueTestCaseAbstract;
class RpcCommunicationTest extends QueueTestCaseAbstract
{
/**
* {@inheritdoc}
*/
protected $consumers = ['synchronousRpcTestConsumer.deprecated'];
/**
* Verify that RPC call based on Rabbit MQ is processed correctly.
*
* Current test is not test of Web API framework itself, it just utilizes its infrastructure to test RPC.
*/
public function testSynchronousRpcCommunication()
{
$input = 'Input value';
$response = $this->publisher->publish('synchronous.rpc.test.deprecated', $input);
$this->assertEquals($input . ' processed by RPC handler', $response);
}
}
@@ -0,0 +1,55 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\TestModuleAsyncAmqp\Model\AsyncTestData;
class MixSyncAndAsyncSingleQueueTest extends QueueTestCaseAbstract
{
/**
* @var AsyncTestData
*/
protected $msgObject;
/**
* {@inheritdoc}
*/
protected $consumers = ['mixed.sync.and.async.queue.consumer'];
/**
* @var string[]
*/
protected $messages = ['message1', 'message2', 'message3'];
/**
* @var int
*/
protected $maxMessages = 4;
public function testMixSyncAndAsyncSingleQueue()
{
$this->msgObject = $this->objectManager->create(AsyncTestData::class); // @phpstan-ignore-line
// Publish asynchronous messages
foreach ($this->messages as $item) {
$this->msgObject->setValue($item);
$this->msgObject->setTextFilePath($this->logFilePath);
$this->publisher->publish('multi.topic.queue.topic.c', $this->msgObject);
}
// Publish synchronous message to the same queue
$input = 'Input value';
$response = $this->publisher->publish('sync.topic.for.mixed.sync.and.async.queue', $input);
$this->assertEquals($input . ' processed by RPC handler', $response);
$this->waitForAsynchronousResult(count($this->messages), $this->logFilePath);
// Verify that asynchronous messages were processed
foreach ($this->messages as $item) {
$this->assertStringContainsString($item, file_get_contents($this->logFilePath));
}
}
}
@@ -0,0 +1,32 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
class MultipleTopicsPerQueueTest extends QueueTestCaseAbstract
{
/**
* {@inheritdoc}
*/
protected $consumers = [
'queue.for.multiple.topics.test.a',
'queue.for.multiple.topics.test.b'
];
/**
* Verify that Queue Framework supports multiple topics per queue.
*
* Current test is not test of Web API framework itself,
* it just utilizes its infrastructure to test Message Queue.
*/
public function testSynchronousRpcCommunication()
{
foreach (['multi.topic.queue.topic.a', 'multi.topic.queue.topic.b'] as $topic) {
$input = "Input value for topic '{$topic}'";
$response = $this->publisher->publish($topic, $input);
$this->assertEquals($input . ' processed by RPC handler', $response);
}
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\MessageQueue\PublisherInterface;
use Magento\TestFramework\MessageQueue\PublisherConsumerController;
use Magento\TestFramework\MessageQueue\EnvironmentPreconditionException;
use Magento\TestFramework\MessageQueue\PreconditionFailedException;
/**
* Base test case for message queue tests.
*/
class QueueTestCaseAbstract extends \PHPUnit\Framework\TestCase
{
/**
* @var string[]
*/
protected $consumers = [];
/**
* @var ObjectManagerInterface
*/
protected $objectManager;
/**
* @var PublisherInterface
*/
protected $publisher;
/**
* @var string
*/
protected $logFilePath;
/**
* @var int|null
*/
protected $maxMessages = null;
/**
* @var PublisherConsumerController
*/
protected $publisherConsumerController;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->logFilePath = TESTS_TEMP_DIR . "/MessageQueueTestLog.txt";
$this->publisherConsumerController = $this->objectManager->create(
PublisherConsumerController::class,
[
'consumers' => $this->consumers,
'logFilePath' => $this->logFilePath,
'maxMessages' => $this->maxMessages,
'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()
);
}
$this->publisher = $this->publisherConsumerController->getPublisher();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->publisherConsumerController->stopConsumers();
}
/**
* Wait for asynchronous handlers to log data to file.
*
* @param int $expectedLinesCount
* @param string $logFilePath
*/
protected function waitForAsynchronousResult($expectedLinesCount, $logFilePath)
{
try {
//$expectedLinesCount, $logFilePath
$this->publisherConsumerController->waitForAsynchronousResult(
[$this, 'checkLogsExists'],
[$expectedLinesCount, $logFilePath]
);
} catch (PreconditionFailedException $e) {
$this->fail($e->getMessage());
}
}
/**
* Checks that logs exist
*
* @param int $expectedLinesCount
* @return bool
*/
public function checkLogsExists($expectedLinesCount)
{
//phpcs:ignore Magento2.Functions.DiscouragedFunction
$actualCount = file_exists($this->logFilePath) ? count(file($this->logFilePath)) : 0;
return $expectedLinesCount === $actualCount;
}
/**
* Workaround for https://bugs.php.net/bug.php?id=72286
* phpcs:disable Magento2.Functions.StaticFunction
*/
public static function tearDownAfterClass(): void
{
// phpcs:enable Magento2.Functions.StaticFunction
if (version_compare(phpversion(), '7') == -1) {
$closeConnection = new \ReflectionMethod(\Magento\Amqp\Model\Config::class, 'closeConnection');
$closeConnection->setAccessible(true);
$config = Bootstrap::getObjectManager()->get(\Magento\Amqp\Model\Config::class);
$closeConnection->invoke($config);
}
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\TestModuleSynchronousAmqp\Api\ServiceInterface;
class RemoteServiceCommunicationTest extends QueueTestCaseAbstract
{
/**
* {@inheritdoc}
*/
protected $consumers = ['RemoteServiceTestConsumer'];
public function testRemoteServiceCommunication()
{
$input = 'Input value';
/** @var ServiceInterface $generatedRemoteService */
$generatedRemoteService = $this->objectManager->get(ServiceInterface::class);
$response = $generatedRemoteService->execute($input);
$this->assertEquals($input . ' processed by RPC handler', $response);
}
}
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
class RpcCommunicationTest extends QueueTestCaseAbstract
{
/**
* {@inheritdoc}
*/
protected $consumers = ['synchronousRpcTestConsumer'];
/**
* Verify that RPC call based on Rabbit MQ is processed correctly.
*
* Current test is not test of Web API framework itself, it just utilizes its infrastructure to test RPC.
*/
public function testSynchronousRpcCommunication()
{
$input = 'Input value';
$response = $this->publisher->publish('synchronous.rpc.test', $input);
$this->assertEquals($input . ' processed by RPC handler', $response);
}
}
@@ -0,0 +1,162 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\Framework\App\DeploymentConfig\FileReader;
use Magento\Framework\App\DeploymentConfig\Writer;
use Magento\Framework\Config\File\ConfigFilePool;
use Magento\Framework\Filesystem;
use Magento\TestModuleAsyncAmqp\Model\AsyncTestData;
class WaitAndNotWaitMessagesTest extends QueueTestCaseAbstract
{
/**
* @var FileReader
*/
private $reader;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var array
*/
private $config;
/**
* @var AsyncTestData
*/
protected $msgObject;
/**
* {@inheritdoc}
*/
protected $consumers = ['mixed.sync.and.async.queue.consumer'];
/**
* @var string[]
*/
protected $messages = ['message1', 'message2', 'message3'];
/**
* @var int|null
*/
protected $maxMessages = 4;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
// phpstan:ignore "Class Magento\TestModuleAsyncAmqp\Model\AsyncTestData not found."
$this->msgObject = $this->objectManager->create(AsyncTestData::class);
$this->reader = $this->objectManager->get(FileReader::class);
$this->filesystem = $this->objectManager->get(Filesystem::class);
$this->config = $this->loadConfig();
}
/**
* Check if consumers wait for messages from the queue
*/
public function testWaitForMessages()
{
$this->publisherConsumerController->stopConsumers();
$config = $this->config;
$config['queue']['consumers_wait_for_messages'] = 1;
$this->writeConfig($config);
$loadedConfig = $this->loadConfig();
$this->assertArrayHasKey('queue', $loadedConfig);
$this->assertArrayHasKey('consumers_wait_for_messages', $loadedConfig['queue']);
$this->assertEquals(1, $loadedConfig['queue']['consumers_wait_for_messages']);
foreach ($this->messages as $message) {
$this->publishMessage($message);
}
$this->publisherConsumerController->startConsumers();
$this->waitForAsynchronousResult(count($this->messages), $this->logFilePath);
foreach ($this->messages as $item) {
$this->assertStringContainsString($item, file_get_contents($this->logFilePath));
}
$this->publishMessage('message4');
$this->waitForAsynchronousResult(count($this->messages) + 1, $this->logFilePath);
$this->assertStringContainsString('message4', file_get_contents($this->logFilePath));
}
/**
* Check if consumers do not wait for messages from the queue and die
*/
public function testNotWaitForMessages(): void
{
$this->publisherConsumerController->stopConsumers();
$config = $this->config;
$config['queue']['consumers_wait_for_messages'] = 0;
$this->writeConfig($config);
$loadedConfig = $this->loadConfig();
$this->assertArrayHasKey('queue', $loadedConfig);
$this->assertArrayHasKey('consumers_wait_for_messages', $loadedConfig['queue']);
$this->assertEquals(0, $loadedConfig['queue']['consumers_wait_for_messages']);
foreach ($this->messages as $message) {
$this->publishMessage($message);
}
$this->publisherConsumerController->startConsumers();
$this->waitForAsynchronousResult(count($this->messages), $this->logFilePath);
foreach ($this->messages as $item) {
$this->assertStringContainsString($item, file_get_contents($this->logFilePath));
}
// Checks that consumers do not wait 4th message and die
$consumersProcessIds = $this->publisherConsumerController->getConsumersProcessIds();
$this->assertArrayHasKey('mixed.sync.and.async.queue.consumer', $consumersProcessIds);
$this->assertEquals([], $consumersProcessIds['mixed.sync.and.async.queue.consumer']);
}
/**
* @param string $message
*/
private function publishMessage(string $message): void
{
$this->msgObject->setValue($message);
$this->msgObject->setTextFilePath($this->logFilePath);
$this->publisher->publish('multi.topic.queue.topic.c', $this->msgObject);
}
/**
* @return array
*/
private function loadConfig(): array
{
return $this->reader->load(ConfigFilePool::APP_ENV);
}
/**
* @param array $config
*/
private function writeConfig(array $config): void
{
$writer = $this->objectManager->get(Writer::class);
$writer->saveConfig([ConfigFilePool::APP_ENV => $config], true);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
parent::tearDown();
$this->writeConfig($this->config);
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\MessageQueue\UseCase;
use Magento\TestModuleAsyncAmqp\Model\AsyncTestData;
class WildcardTopicTest extends QueueTestCaseAbstract
{
/**
* @var string[]
*/
protected $consumers = [
'wildcard.queue.one.consumer',
'wildcard.queue.two.consumer',
'wildcard.queue.three.consumer',
'wildcard.queue.four.consumer',
];
/**
* @param string $topic
* @param string[] $matchingQueues
* @param string[] $nonMatchingQueues
*
* @dataProvider wildCardTopicsDataProvider
*/
public function testWildCardMatchingTopic($topic, $matchingQueues, $nonMatchingQueues)
{
$testObject = $this->generateTestObject();
$this->publisher->publish($topic, $testObject);
$this->waitForAsynchronousResult(count($matchingQueues), $this->logFilePath);
$this->assertFileExists($this->logFilePath, "No handlers invoked (log file was not created).");
foreach ($nonMatchingQueues as $queueName) {
$this->assertStringNotContainsString($queueName, file_get_contents($this->logFilePath));
}
foreach ($matchingQueues as $queueName) {
$this->assertStringContainsString($queueName, file_get_contents($this->logFilePath));
}
}
public function wildCardTopicsDataProvider()
{
return [
'segment1.segment2.segment3.wildcard' => [
'segment1.segment2.segment3.wildcard',
['wildcard.queue.one', 'wildcard.queue.two', 'wildcard.queue.four'],
['wildcard.queue.three']
],
'segment2.segment3.wildcard' => [
'segment2.segment3.wildcard',
['wildcard.queue.one', 'wildcard.queue.three', 'wildcard.queue.four'],
['wildcard.queue.two']
]
];
}
public function testWildCardNonMatchingTopic()
{
$testObject = $this->generateTestObject();
$this->publisher->publish('not.matching.wildcard.topic', $testObject);
sleep(2);
$this->assertFileDoesNotExist($this->logFilePath, "No log file must be created for non-matching topic.");
}
/**
* @return AsyncTestData
*/
private function generateTestObject()
{
$testObject = $this->objectManager->create(AsyncTestData::class); // @phpstan-ignore-line
$testObject->setValue('||Message Contents||');
$testObject->setTextFilePath($this->logFilePath);
return $testObject;
}
}
@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Communication/etc/communication.xsd">
<topic name="topic.broker.test" request="string" response="string">
<handler name="topicBrokerHandler" type="Magento\TestModuleMysqlMq\Model\Processor" method="processMessage"/>
</topic>
</config>
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
'topics' => [
'customer.created' => [
'request_type' => 'object_interface',
'request' => \Magento\Customer\Api\Data\CustomerInterface::class,
'response' => null,
],
'customer.list.retrieved' => [
'request_type' => 'object_interface',
'request' => 'Magento\Customer\Api\Data\CustomerInterface[]',
'response' => null,
],
'customer.updated' => [
'request_type' => 'object_interface',
'request' => \Magento\Customer\Api\Data\CustomerInterface::class,
'response' => null,
],
'customer.deleted' => [
'request_type' => 'object_interface',
'request' => \Magento\Customer\Api\Data\CustomerInterface::class,
'response' => null,
],
'product.created' => [
'request_type' => 'object_interface',
'request' => \Magento\Catalog\Api\Data\ProductInterface::class,
'response' => null,
],
],
];
@@ -0,0 +1,90 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
"publishers" => [
"amqp-magento" => [
"name" => "amqp-magento",
"connection" => "amqp",
"exchange" => "magento"
],
'demo-publisher-1' => [
'name' => 'demo-publisher-1',
'connection' => 'amqp',
"exchange" => "magento"
],
"test-publisher-5" => [
"name" => "test-publisher-5",
"connection" => "amqp",
"exchange" => "test-exchange-10"
]
],
"topics" => [
"topic.broker.test" => [
"name" => "topic.broker.test",
"schema" => [
"schema_type" => "object",
"schema_value" => "string"
],
"response_schema" => [
"schema_type" => "object",
"schema_value" => "string"
],
"publisher" => "amqp-magento",
'is_synchronous' => true,
],
"publisher5.topic" => [
"name" => "publisher5.topic",
"schema" => [
"schema_type" => "object",
"schema_value" => '\\' . \Magento\TestModuleMysqlMq\Model\DataObject::class
],
"response_schema" => [
"schema_type" => "object",
"schema_value" => \Magento\Customer\Api\Data\CustomerInterface::class
],
"publisher" => "test-publisher-5"
]
],
"consumers" => [
"topicBrokerConsumer" => [
"name" => "topicBrokerConsumer",
"queue" => "demo-queue-1",
"connection" => "amqp",
"consumer_type" => "sync",
"handlers" => [
"topic.broker.test" => [
"0" => [
"type" => \Magento\TestModuleMysqlMq\Model\Processor::class,
"method" => "processMessage"
]
]
],
"max_messages" => null,
"instance_type" => \Magento\Framework\MessageQueue\ConsumerInterface::class
]
],
"binds" => [
"topic.broker.test--magento--demo-queue-1" => [
"queue" => "demo-queue-1",
"exchange" => "magento",
"topic" => "topic.broker.test"
],
"publisher5.topic--test-exchange-10--demo-queue-1" => [
"queue" => "demo-queue-1",
"exchange" => "test-exchange-10",
"topic" => "publisher5.topic"
]
],
"exchange_topic_to_queues_map" => [
"magento--topic.broker.test" => [
"demo-queue-1"
],
"test-exchange-10--publisher5.topic" => [
"demo-queue-1"
]
]
];
@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/queue.xsd">
<broker topic="topic.broker.test" type="amqp" exchange="magento">
<queue consumer="topicBrokerConsumer" name="demo-queue-1" />
</broker>
</config>
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
return [
'queue' => [
'publishers' => [
'demo-publisher-1' => [
'name' => 'demo-publisher-1',
'connection' => 'amqp',
"exchange" => "magento"
],
"test-publisher-5" => [
"name" => "test-publisher-5",
"connection" => "amqp",
"exchange" => "test-exchange-10"
]
],
"topics" => [
"publisher5.topic" => [
"name" => "publisher5.topic",
"schema" => [
"schema_type" => "object",
"schema_value" => \Magento\TestModuleMysqlMq\Model\DataObject::class
],
"response_schema" => [
"schema_type" => "object",
"schema_value" => \Magento\Customer\Api\Data\CustomerInterface::class
],
"publisher" => "test-publisher-5"
]
],
"binds" => [
"publisher5.topic--test-exchange-10--demo-queue-1" => [
"queue" => "demo-queue-1",
"exchange" => "test-exchange-10",
"topic" => "publisher5.topic"
]
],
"exchange_topic_to_queues_map" => [
"test-exchange-10--publisher5.topic" => [
"demo-queue-1"
]
]
]
];