Programming Language PHP
Namespace Oro\Component\Testing
Class ReflectionUtil
Method/Function setPropertyValue
Total Examples 45
45 code examples of PHP Oro\Component\Testing\ReflectionUtil::setPropertyValue extracted from open source projects
public function addPostAction(TreeExecutor $treeExecutor, ActionInterface $action, bool $breakOnFailure)
{
$actionData = [];
if ($action instanceof TreeExecutor) {
$actionData = [
'_type' => TreeExecutor::ALIAS,
'actions' => $this->getActions($action),
];
} elseif ($action instanceof ArrayAction) {
$actionData = $action->toArray();
}
$conditionData = $this->getCondition($action);
if ($conditionData) {
$actionData['condition'] = $conditionData;
}
$treeActions = $this->getActions($treeExecutor);
$treeActions[] = [
'instance' => $actionData,
'breakOnFailure' => $breakOnFailure,
];
ReflectionUtil::setPropertyValue($treeExecutor, 'actions', $treeActions);
}
/**
* @depends testGetResult
*/
public function testGetResultUnserialized()
{
ReflectionUtil::setPropertyValue($this->workflowItem, 'result', null);
$this->assertInstanceOf(WorkflowResult::class, $this->workflowItem->getResult());
$this->assertTrue($this->workflowItem->getResult()->isEmpty());
}
protected function setUp(): void
{
$this->initClient();
$provider = $this->getContainer()->get('oro_workflow.configuration.provider.process_config');
ReflectionUtil::setPropertyValue($provider, 'configDirectory', '/Tests/Functional/Command/DataFixtures/');
}
public function testPersistWithSystemScopeDataAndLanguageShouldBeFilesBased(): void
{
//change the fileBasedLanguagesPath parameter to emulate the case when there is dumped translations
//in translations directory.
$translationsPath = realpath(__DIR__ . '/../Stub/translations');
$helper = self::getContainer()->get('oro_translation.helper.file_based_language');
ReflectionUtil::setPropertyValue($helper, 'fileBasedLanguagesPath', $translationsPath);
$language = $this->getReference(LoadLanguages::LANGUAGE2);
$translationKey = $this->getReference('tk-translation.trans5-test_domain');
$catalogData = [
'test_domain' => [
'translation.trans5' => 'translation.trans5',
],
];
$keyCount = $this->getEntityCount(TranslationKey::class);
$translationCount = $this->getEntityCount(Translation::class);
$this->getPersister()->persist(LoadLanguages::LANGUAGE2, $catalogData, Translation::SCOPE_SYSTEM);
$this->assertEquals($keyCount, $this->getEntityCount(TranslationKey::class));
$this->assertEquals($translationCount, $this->getEntityCount(Translation::class));
$updatedEntity = $this->getTranslationEntity($language, $translationKey);
self::assertEquals(Translation::SCOPE_SYSTEM, $updatedEntity->getScope());
self::assertTrue($language->isLocalFilesLanguage());
}
protected function setUp(): void
{
$this->initClient();
// change the translationServiceAdapter at the command instance to the stub
// to be able to work with local archive instead of real calls to the remote service.
$archivePath = realpath(__DIR__ . '/../../Stub/translations.zip');
$translationServiceAdapter = new TranslationServiceAdapterStub($archivePath);
$this->loader = self::getContainer()->get('oro_translation.catalogue_loader.crowdin');
ReflectionUtil::setPropertyValue($this->loader, 'translationServiceAdapter', $translationServiceAdapter);
}
protected function setUp(): void
{
$this->initClient();
$this->loadFixtures([LoadTranslations::class]);
$this->tempDir = $this->getTempDir('dump_translation_command');
$this->translationReader = self::getContainer()->get('translation.reader');
// change the translationServiceAdapter at the command instance to the stub
// to be able to work with local archive instead of real calls to the remote service.
$archivePath = realpath(__DIR__ . '/../Stub/translations.zip');
$translationServiceAdapter = new TranslationServiceAdapterStub($archivePath);
$loader = self::getContainer()->get('oro_translation.catalogue_loader.crowdin');
ReflectionUtil::setPropertyValue($loader, 'translationServiceAdapter', $translationServiceAdapter);
// change the directory of the dumped files to the temp directory
// because default translation path from the translator.default_path parameter can be
// forbidden to write at the test instances.
$command = self::getContainer()->get(DumpTranslationToFilesCommand::class);
ReflectionUtil::setPropertyValue($command, 'targetPath', $this->tempDir);
}
/**
* @param BatchItem[] $items
*/
private function setItems(array $items)
{
$val = [];
foreach ($items as $item) {
$key = ReflectionUtil::callMethod($this->manager, 'getKey', [$item->getOid()]);
$val[$key] = $item;
}
ReflectionUtil::setPropertyValue($this->manager, 'items', $val);
}
private function setItem(ObjectIdentity $oid, $state, MutableAclInterface $acl = null)
{
$key = ReflectionUtil::callMethod($this->manager, 'getKey', [$oid]);
ReflectionUtil::setPropertyValue(
$this->manager,
'items',
[$key => new BatchItem($oid, $state, $acl)]
);
}
private function appendPermissionConfig(PermissionConfigurationProvider $provider, array $newPermissions)
{
$provider->ensureCacheWarmedUp();
ReflectionUtil::setPropertyValue(
$provider,
'config',
array_merge(ReflectionUtil::getPropertyValue($provider, 'config'), $newPermissions)
);
}
public function testGetTitle()
{
$this->controllerClassProvider->expects(self::once())
->method('getControllers')
->willReturn([
'test1_route' => [TestController::class, 'test1Action'],
'test2_route' => [TestController::class, 'test2Action'],
]);
$this->reader->expects(self::exactly(2))
->method('getMethodAnnotation')
->willReturnCallback(function (\ReflectionMethod $method, $annotationName) {
self::assertEquals(TitleTemplate::class, $annotationName);
if ($method->getName() === 'test1Action') {
return new TitleTemplate(['value' => 'test1 title']);
}
return null;
});
$this->assertEquals('test1 title', $this->annotationReader->getTitle('test1_route'));
$this->assertNull($this->annotationReader->getTitle('test2_route'));
$this->assertNull($this->annotationReader->getTitle('unknown_route'));
// test load data from cache file
ReflectionUtil::setPropertyValue($this->annotationReader, 'config', null);
$this->assertEquals('test1 title', $this->annotationReader->getTitle('test1_route'));
$this->assertNull($this->annotationReader->getTitle('test2_route'));
$this->assertNull($this->annotationReader->getTitle('unknown_route'));
}
public function testRenderBlock()
{
$configManager = $this->createMock(ConfigManager::class);
$configManager->expects(self::once())
->method('get')
->with('oro_layout.debug_block_info')
->willReturn(true);
$this->twigRendererEngine->setConfigManager($configManager);
$view = $this->createMock(FormView::class);
$view->vars['cache_key'] = 'cache_key';
$template = $this->createMock(Template::class);
$template->expects($this->once())
->method('getTemplateName')
->willReturn('theme');
ReflectionUtil::setPropertyValue($this->twigRendererEngine, 'template', $template);
ReflectionUtil::setPropertyValue($this->twigRendererEngine, 'resources', ['cache_key' => []]);
$variables = ['id' => 'root'];
$result = array_merge(
$variables,
[
'attr' => [
'data-layout-debug-block-id' => 'root',
'data-layout-debug-block-template' => 'theme',
],
]
);
$this->environment->expects($this->once())
->method('mergeGlobals')
->with($result)
->willReturn([$template, 'root']);
$this->twigRendererEngine->renderBlock($view, [$template, 'root'], 'root', $variables);
}
public function testOnUpdateAfter()
{
ReflectionUtil::setPropertyValue(
$this->configListener,
'featuresStates',
[
'feature1' => true,
'feature2' => false,
'feature3' => true,
]
);
ReflectionUtil::setPropertyValue(
$this->configListener,
'affectedFeatures',
[
'feature1',
'feature2',
'feature3',
]
);
$this->featureChecker->expects($this->any())
->method('isFeatureEnabled')
->willReturnMap([
['feature1', null, true],
['feature2', null, true],
['feature3', null, true],
]);
$this->featureChecker->expects($this->once())
->method('resetCache');
$this->eventDispatcher->expects($this->exactly(2))
->method('dispatch')
->withConsecutive(
[new FeaturesChange(['feature2' => true]), FeaturesChange::NAME],
[new FeatureChange('feature2', true), FeatureChange::NAME . '.feature2']
);
$this->configListener->onUpdateAfter();
}
/**
* @dataProvider dataProviderForMergeColumnOptions
*/
public function testMergeColumnOptions(array $existingOptions, array $newOptions, array $expectedOptions)
{
$objectKey = sprintf(ExtendOptionsManager::COLUMN_OPTION_FORMAT, 'test_table', 'test_column');
ReflectionUtil::setPropertyValue($this->manager, 'options', [$objectKey => $existingOptions]);
$this->manager->mergeColumnOptions('test_table', 'test_column', $newOptions);
$this->assertEquals([$objectKey => $expectedOptions], $this->manager->getExtendOptions());
}
public function testShouldLogWarningIfInitializedPropertyOfEventManagerIsNotArray()
{
$logger = $this->createMock(LoggerInterface::class);
$metadataFactory = $this->createMock(OroClassMetadataFactory::class);
$em = $this->createMock(EntityManager::class);
$eventManager = new ContainerAwareEventManager($this->container);
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('getConfiguration')
->willReturn(new DbalConfiguration());
$connection->expects(self::once())
->method('isConnected')
->willReturn(true);
$connection->expects(self::once())
->method('close');
$em->expects(self::once())
->method('getConnection')
->willReturn($connection);
// guard
self::assertObjectHasAttribute('listeners', $eventManager);
self::assertObjectHasAttribute('initialized', $eventManager);
ReflectionUtil::setPropertyValue($eventManager, 'listeners', []);
ReflectionUtil::setPropertyValue($eventManager, 'initialized', new ArrayCollection());
$logger->expects(self::once())
->method('info')
->with('Disconnect ORM metadata factory');
$logger->expects(self::once())
->method('warning')
->with('The EventManager "listeners" and "initialized" properties should be an array');
$this->container->expects(self::once())
->method('initialized')
->with('foo_metadata_factory')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('foo_metadata_factory')
->willReturn($metadataFactory);
$metadataFactory->expects(self::once())
->method('isDisconnected')
->willReturn(false);
$metadataFactory->expects(self::once())
->method('getEntityManager')
->willReturn($em);
$em->expects(self::once())
->method('isOpen')
->willReturn(true);
$em->expects(self::any())
->method('getConfiguration')
->willReturn(new OrmConfiguration());
$em->expects(self::once())
->method('getEventManager')
->willReturn($eventManager);
$this->clearer->clear($logger);
}
public function testShouldLogWarningIfListenersPropertyOfEventManagerIsNotArray()
{
$logger = $this->createMock(LoggerInterface::class);
$metadataFactory = $this->createMock(OroClassMetadataFactory::class);
$em = $this->createMock(EntityManager::class);
$eventManager = new ContainerAwareEventManager($this->container);
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('getConfiguration')
->willReturn(new DbalConfiguration());
$connection->expects(self::once())
->method('isConnected')
->willReturn(true);
$connection->expects(self::once())
->method('close');
$em->expects(self::once())
->method('getConnection')
->willReturn($connection);
// guard
self::assertObjectHasAttribute('listeners', $eventManager);
self::assertObjectHasAttribute('initialized', $eventManager);
ReflectionUtil::setPropertyValue($eventManager, 'listeners', new ArrayCollection());
ReflectionUtil::setPropertyValue($eventManager, 'initialized', []);
$logger->expects(self::once())
->method('info')
->with('Disconnect ORM metadata factory');
$logger->expects(self::once())
->method('warning')
->with('The EventManager "listeners" and "initialized" properties should be an array');
$this->container->expects(self::once())
->method('initialized')
->with('foo_metadata_factory')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('foo_metadata_factory')
->willReturn($metadataFactory);
$metadataFactory->expects(self::once())
->method('isDisconnected')
->willReturn(false);
$metadataFactory->expects(self::once())
->method('getEntityManager')
->willReturn($em);
$em->expects(self::once())
->method('isOpen')
->willReturn(true);
$em->expects(self::any())
->method('getConfiguration')
->willReturn(new OrmConfiguration());
$em->expects(self::once())
->method('getEventManager')
->willReturn($eventManager);
$this->clearer->clear($logger);
}
public function testShouldRemoveUnneededListenersIfEventManagerIsInstanceOfContainerAwareEventManagerClass()
{
$logger = $this->createMock(LoggerInterface::class);
$metadataFactory = $this->createMock(OroClassMetadataFactory::class);
$em = $this->createMock(EntityManager::class);
$eventManager = new ContainerAwareEventManager($this->container);
$connection = $this->createMock(Connection::class);
$connection->expects(self::once())
->method('getConfiguration')
->willReturn(new DbalConfiguration());
$connection->expects(self::once())
->method('isConnected')
->willReturn(true);
$connection->expects(self::once())
->method('close');
$em->expects(self::once())
->method('getConnection')
->willReturn($connection);
// guard
self::assertObjectHasAttribute('listeners', $eventManager);
self::assertObjectHasAttribute('initialized', $eventManager);
$eventManager->addEventListener(
[OrmEvents::onFlush, OrmEvents::loadClassMetadata, OrmEvents::onClassMetadataNotFound],
'foo_listener'
);
ReflectionUtil::setPropertyValue(
$eventManager,
'initialized',
[
OrmEvents::onFlush => true,
OrmEvents::loadClassMetadata => true,
OrmEvents::onClassMetadataNotFound => true,
]
);
$logger->expects(self::once())
->method('info')
->with('Disconnect ORM metadata factory');
$logger->expects(self::never())
->method('warning');
$this->container->expects(self::once())
->method('initialized')
->with('foo_metadata_factory')
->willReturn(true);
$this->container->expects(self::once())
->method('get')
->with('foo_metadata_factory')
->willReturn($metadataFactory);
$metadataFactory->expects(self::once())
->method('isDisconnected')
->willReturn(false);
$metadataFactory->expects(self::once())
->method('getEntityManager')
->willReturn($em);
$em->expects(self::once())
->method('isOpen')
->willReturn(true);
$em->expects(self::any())
->method('getConfiguration')
->willReturn(new OrmConfiguration());
$em->expects(self::once())
->method('getEventManager')
->willReturn($eventManager);
$this->clearer->clear($logger);
self::assertEquals(
[
OrmEvents::loadClassMetadata => ['_service_foo_listener' => 'foo_listener'],
OrmEvents::onClassMetadataNotFound => ['_service_foo_listener' => 'foo_listener'],
],
ReflectionUtil::getPropertyValue($eventManager, 'listeners')
);
self::assertEquals(
[
OrmEvents::loadClassMetadata => true,
OrmEvents::onClassMetadataNotFound => true,
],
ReflectionUtil::getPropertyValue($eventManager, 'initialized')
);
}
/**
* @inheritDoc
*/
protected function getExtensions(): array
{
$attributeMultiSelectType = new AttributeMultiSelectType($this->attributeManager, $this->getTranslator());
ReflectionUtil::setPropertyValue($attributeMultiSelectType, 'choices', self::ATTRIBUTES_CHOICES);
return [
new PreloadedExtension(
[
new LocalizedFallbackValueCollectionType($this->doctrine),
$attributeMultiSelectType,
new LocalizedPropertyType(),
new FallbackValueType(),
new FallbackPropertyType($this->createMock(TranslatorInterface::class)),
LocalizationCollectionType::class => new LocalizationCollectionTypeStub([
$this->getLocalization(self::LOCALIZATION_ID),
]),
],
[
FormType::class => [
new StripTagsExtensionStub($this),
new TooltipFormExtensionStub($this),
],
]
),
$this->getValidatorExtension(true),
];
}
/**
* @dataProvider addAttributesDataProvider
*/
public function testOnPreSubmit(array $fields, array $attributes, int $expectAdds)
{
$attributeFamilyId = 777;
$entity = $this->getEntityWithFamily();
$form = $this->getForm();
$form->expects($this->exactly($expectAdds))
->method('add');
ReflectionUtil::setPropertyValue($this->extension, 'fields', [get_class($entity) => $fields]);
$this->attributeManager->expects($this->once())
->method('getAttributesByFamily')
->with($entity->getAttributeFamily())
->willReturn($attributes);
$attributeFamilyRepository = $this->createMock(EntityRepository::class);
$attributeFamilyRepository->expects($this->once())
->method('find')
->with($attributeFamilyId)
->willReturn($entity->getAttributeFamily());
$this->doctrineHelper->expects($this->once())
->method('getEntityRepositoryForClass')
->with(AttributeFamily::class)
->willReturn($attributeFamilyRepository);
$event = new FormEvent($form, ['attributeFamily' => $attributeFamilyId]);
$this->extension->onPreSubmit($event);
}
/**
* @dataProvider addAttributesDataProvider
*/
public function testOnPreSetData(array $fields, array $attributes, int $expectAdds)
{
$entity = $this->getEntityWithFamily();
$form = $this->getForm();
ReflectionUtil::setPropertyValue($this->extension, 'fields', [get_class($entity) => $fields]);
$this->attributeManager->expects($this->once())
->method('getAttributesByFamily')
->with($entity->getAttributeFamily())
->willReturn($attributes);
$form->expects($this->any())
->method('has')
->willReturn(false);
$form->expects($this->exactly($expectAdds))
->method('add');
$event = new FormEvent($form, $entity);
$this->extension->onPreSetData($event);
}
public function testPostFlush(): void
{
$emptyFamilyId = 1;
$filledFamilyId = 2;
$filledFamilyAttributeNames = ['name'];
$topicName = 'topic';
ReflectionUtil::setPropertyValue(
$this->listener,
'deletedAttributes',
[
$emptyFamilyId => [],
$filledFamilyId => $filledFamilyAttributeNames,
]
);
$this->listener->setTopic($topicName);
$this->messageProducer->expects(self::once())
->method('send')
->with(
$topicName,
new Message([
'attributeFamilyId' => $filledFamilyId,
'attributeNames' => $filledFamilyAttributeNames,
], MessagePriority::NORMAL)
);
$this->listener->postFlush();
self::assertEmpty(ReflectionUtil::getPropertyValue($this->listener, 'deletedAttributes'));
}
public function testScheduleSyncOriginsJobShouldSendMessageToTopicWithIds(): void
{
ReflectionUtil::setPropertyValue($this->sync, 'messageQueueTopic', 'topic-name');
$producer = $this->createMock(MessageProducerInterface::class);
$producer->expects(self::once())
->method('send')
->with('topic-name', ['ids' => [1, 2, 3]]);
$this->sync->setMessageProducer($producer);
$this->sync->scheduleSyncOriginsJob([1, 2, 3]);
}
public function testScheduleSyncOriginsJobShouldThrowExceptionIfMessageProducerIsNotSet(): void
{
ReflectionUtil::setPropertyValue($this->sync, 'messageQueueTopic', 'topic-name');
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Message producer is not set');
$this->sync->scheduleSyncOriginsJob([1, 2, 3]);
}
public function testShouldFilterOutEmailsWhichHasNoAutoResponse()
{
$email1 = new Email();
ReflectionUtil::setId($email1, 123);
$emailBody1 = new EmailBody();
$emailBody1->setEmail($email1);
$email2 = new Email();
ReflectionUtil::setId($email2, 12345);
$emailBody2 = new EmailBody();
$emailBody2->setEmail($email2);
ReflectionUtil::setPropertyValue($this->listener, 'emailBodies', [$emailBody1, $emailBody2]);
$this->autoResponseManager->expects($this->exactly(2))
->method('hasAutoResponses')
->willReturnOnConsecutiveCalls(false, true);
$this->producer->expects($this->once())
->method('send')
->with(SendAutoResponsesTopic::getName(), ['ids' => [12345]]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
}
public function testShouldPublishEmailIdsIfTheyHasAutoResponse()
{
$this->autoResponseManager->expects($this->exactly(2))
->method('hasAutoResponses')
->willReturn(true);
$this->producer->expects($this->once())
->method('send')
->with(SendAutoResponsesTopic::getName(), ['ids' => [123, 12345]]);
$email1 = new Email();
ReflectionUtil::setId($email1, 123);
$emailBody1 = new EmailBody();
$emailBody1->setEmail($email1);
$email2 = new Email();
ReflectionUtil::setId($email2, 12345);
$emailBody2 = new EmailBody();
$emailBody2->setEmail($email2);
ReflectionUtil::setPropertyValue($this->listener, 'emailBodies', [$emailBody1, $emailBody2]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
}
/**
* @dataProvider normalizeFileOptionsDataProvider
*/
public function testNormalizeFileOptions(Options $allOptions, array $option, array $expectedOption): void
{
ReflectionUtil::setPropertyValue($allOptions, 'locked', true);
$this->assertEquals(
$expectedOption,
$this->extension->normalizeFileOptions($allOptions, $option)
);
}
private function setOwnershipFields(array $ownershipFields)
{
// set ownership fields
ReflectionUtil::setPropertyValue($this->extension, 'ownershipFields', $ownershipFields);
// skip load actions metadata
ReflectionUtil::setPropertyValue($this->extension, 'isMetadataVisited', true);
}
public function testCreatedAtGetter()
{
$date = new \DateTime('now');
$obj = new ConfigValue();
ReflectionUtil::setPropertyValue($obj, 'createdAt', $date);
$this->assertEquals($date, $obj->getCreatedAt());
}
public function testPostFlush(): void
{
ReflectionUtil::setPropertyValue($this->listener, 'filesShouldBeDeleted', ['test', 'test1']);
$this->fileManager->expects(self::exactly(2))
->method('deleteFile')
->withConsecutive(['test'], ['test1']);
$this->logger->expects(self::never())
->method('warning');
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
self::assertEquals([], ReflectionUtil::getPropertyValue($this->listener, 'filesShouldBeDeleted'));
}
public function testPostFlushWithExceptionDuringDeletion(): void
{
$exception = new \Exception('Test exception.');
ReflectionUtil::setPropertyValue($this->listener, 'filesShouldBeDeleted', ['test']);
$this->fileManager->expects(self::once())
->method('deleteFile')
->with('test')
->willThrowException($exception);
$this->logger->expects(self::once())
->method('warning')
->with('Could not delete file "test"', ['exception' => $exception]);
$this->listener->postFlush($this->createMock(PostFlushEventArgs::class));
self::assertEquals([], ReflectionUtil::getPropertyValue($this->listener, 'filesShouldBeDeleted'));
}
public function testOnFlush(): void
{
ReflectionUtil::setPropertyValue($this->listener, 'filesShouldBeDeleted', ['test']);
$this->listener->onFlush($this->createMock(OnFlushEventArgs::class));
self::assertEquals([], ReflectionUtil::getPropertyValue($this->listener, 'filesShouldBeDeleted'));
}
private function setFormViewData(FormInterface $form, $data): void
{
ReflectionUtil::setPropertyValue($form, 'defaultDataSet', true);
ReflectionUtil::setPropertyValue($form, 'viewData', $data);
}
public function testElapsedTimeForUpdatedEntity()
{
$entity = new AsyncOperation();
$entity->beforeSave();
// now - 5 min 10 sec
ReflectionUtil::setPropertyValue(
$entity,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT5M10S'))
);
$entity->preUpdate();
self::assertSame(310, $entity->getElapsedTime());
}
public function testForRootJobLinkedToAsyncOperationUpdateInvalidProgress()
{
$job = new Job();
$job->setId(123);
$job->setData(['api_operation_id' => 1]);
$job->setStatus(Job::STATUS_RUNNING);
$job->setJobProgress(-1);
$operation = new AsyncOperation();
$operation->setJobId(123);
$operation->setStatus(AsyncOperation::STATUS_RUNNING);
// now - 10 min
ReflectionUtil::setPropertyValue(
$operation,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT10M'))
);
$operation->setProgress(0.5);
$this->em->expects(self::once())
->method('find')
->with(AsyncOperation::class, 1)
->willReturn($operation);
$this->uow->expects(self::never())
->method('recomputeSingleEntityChangeSet');
$this->listener->onBeforeSaveJob(new BeforeSaveJobEvent($job));
self::assertSame(0.5, $operation->getProgress());
}
public function testForRootJobLinkedToAsyncOperationUpdateZeroProgress()
{
$job = new Job();
$job->setId(123);
$job->setData(['api_operation_id' => 1]);
$job->setStatus(Job::STATUS_RUNNING);
$job->setJobProgress(0);
$operation = new AsyncOperation();
$operation->setJobId(123);
$operation->setStatus(AsyncOperation::STATUS_RUNNING);
// now - 10 min
ReflectionUtil::setPropertyValue(
$operation,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT10M'))
);
$operation->setProgress(0.5);
$classMetadata = $this->createMock(ClassMetadata::class);
$this->em->expects(self::once())
->method('find')
->with(AsyncOperation::class, 1)
->willReturn($operation);
$this->em->expects(self::once())
->method('getClassMetadata')
->with(AsyncOperation::class)
->willReturn($classMetadata);
$this->uow->expects(self::once())
->method('recomputeSingleEntityChangeSet')
->with(self::identicalTo($classMetadata), self::identicalTo($operation));
$this->listener->onBeforeSaveJob(new BeforeSaveJobEvent($job));
self::assertSame(0, $operation->getProgress());
}
public function testForRootJobLinkedToAsyncOperationUpdateProgress()
{
$job = new Job();
$job->setId(123);
$job->setData(['api_operation_id' => 1]);
$job->setStatus(Job::STATUS_RUNNING);
$job->setJobProgress(0.1); // 10%
$operation = new AsyncOperation();
$operation->setJobId(123);
$operation->setStatus(AsyncOperation::STATUS_RUNNING);
// now - 10 min
ReflectionUtil::setPropertyValue(
$operation,
'createdAt',
(new \DateTime('now', new \DateTimeZone('UTC')))->sub(new \DateInterval('PT10M'))
);
$classMetadata = $this->createMock(ClassMetadata::class);
$this->em->expects(self::once())
->method('find')
->with(AsyncOperation::class, 1)
->willReturn($operation);
$this->em->expects(self::once())
->method('getClassMetadata')
->with(AsyncOperation::class)
->willReturn($classMetadata);
$this->uow->expects(self::once())
->method('recomputeSingleEntityChangeSet')
->with(self::identicalTo($classMetadata), self::identicalTo($operation));
$this->listener->onBeforeSaveJob(new BeforeSaveJobEvent($job));
self::assertSame(0.1, $operation->getProgress()); // 10%
}
protected function setUp(): void
{
$this->initClient();
$this->loadFixtures([
LoadActivityData::class,
]);
$this->authorizationChecker = $this->createMock(AuthorizationChecker::class);
$manager = self::getContainer()->get('oro_activity.manager.activity_context.api');
ReflectionUtil::setPropertyValue($manager, 'authorizationChecker', $this->authorizationChecker);
}
public function testGetTokenData()
{
$actionData = new ActionData([ActionData::OPERATION_TOKEN => 'test_key']);
$operation = $this->createMock(Operation::class);
$form = $this->createMock(FormInterface::class);
$formView = new FormView();
$tokenView = new FormView();
ReflectionUtil::setPropertyValue($formView, 'children', [FormProvider::CSRF_TOKEN_FIELD => $tokenView]);
$operation->expects($this->once())
->method('getName')
->willReturn('test_operation');
$form->expects($this->once())
->method('createView')
->willReturn($formView);
$options = ['csrf_token_id' => 'test_operation'];
$this->formFactory->expects($this->once())
->method('create')
->with($this->formType, $operation, $options)
->willReturn($form);
$result = $this->formProvider->createTokenData($operation, $actionData);
$this->assertArrayHasKey(OperationExecutionType::NAME, $result);
}
public function testPostFlush()
{
$this->em->expects(self::any())
->method('getRepository')
->with('OroChannelBundle:LifetimeValueHistory')
->willReturn($this->lifetimeRepo);
$account = $this->createMock(Account::class);
$channel = $this->createMock(Channel::class);
$channel->expects(self::any())
->method('getId')
->willReturn(1);
$account2 = clone $account;
$this->lifetimeRepo->expects(self::exactly(2))
->method('calculateAccountLifetime')
->with(
[Customer::class => 'lifetime'],
self::isInstanceOf(Account::class),
self::isInstanceOf(Channel::class)
)
->willReturnOnConsecutiveCalls(100, 200);
$this->em->expects(self::exactly(2))
->method('persist');
$this->em->expects(self::once())
->method('flush');
$channelDoctrineListener = new ChannelDoctrineListener($this->settingsProvider);
ReflectionUtil::setPropertyValue($channelDoctrineListener, 'queued', [
uniqid('accountId__channelId', true) => ['account' => $account, 'channel' => $channel],
uniqid('accountId__channelId', true) => ['account' => $account2, 'channel' => $channel],
]);
$channelDoctrineListener->postFlush(new PostFlushEventArgs($this->em));
}
public function testCloseOnSelfGeneratedIterator()
{
ReflectionUtil::setPropertyValue($this->reader, 'isSelfCreatedIterator', true);
$iterator = $this->createMock('\Iterator');
$this->reader->setSourceIterator($iterator);
$this->reader->close();
$this->assertNull($this->reader->getSourceIterator());
}
private function setHasChangedSerializedFields(array $value): void
{
ReflectionUtil::setPropertyValue($this->listener, 'hasChangedSerializedFields', $value);
}
public function testExecuteAttemptsPassed()
{
$restClient = $this->createMock('RestClient\Client');
ReflectionUtil::setPropertyValue($this->client, 'restClient', $restClient);
ReflectionUtil::setPropertyValue($this->client, 'sleepBetweenAttempt', [0.1, 0.2, 0.3, 0.4]);
$request = $this->createMock('RestClient\Request');
$exceptionMessagePattern = 'Dotmailer REST client exception:' . PHP_EOL .
'[exception type] Exception' . PHP_EOL .
'[exception message] %s' . PHP_EOL .
'[request url] testCall' . PHP_EOL .
'[request method] ' . PHP_EOL .
'[request data] ' . PHP_EOL .
'[response code] ' . PHP_EOL .
'[response body] ';
$this->logger->expects($this->exactly(6))
->method('warning')
->withConsecutive(
[
'[Warning] Attempt failed. Error message:' . PHP_EOL .
sprintf($exceptionMessagePattern, 'Exception A'),
],
['[Warning] Attempt number 1 with 0.1 sec delay.'],
[
'[Warning] Attempt failed. Error message:' . PHP_EOL .
sprintf($exceptionMessagePattern, 'Exception B'),
],
['[Warning] Attempt number 2 with 0.2 sec delay.'],
[
'[Warning] Attempt failed. Error message:' . PHP_EOL .
sprintf($exceptionMessagePattern, 'Exception C'),
],
['[Warning] Attempt number 3 with 0.3 sec delay.']
);
$restClient->expects($this->exactly(4))
->method('newRequest')
->willReturnOnConsecutiveCalls(
new ReturnCallback(function () {
throw new \Exception('Exception A');
}),
new ReturnCallback(function () {
throw new \Exception('Exception B');
}),
new ReturnCallback(function () {
throw new \Exception('Exception C');
}),
$request
);
$request->expects($this->once())
->method('getResponse')
->will($this->returnValue($this->response));
$this->response->expects($this->once())
->method('getInfo')
->will($this->returnValue($this->info));
$this->info->http_code = 200;
$expectedResult = 'Some result';
$this->response->expects($this->once())
->method('getParsedResponse')
->will($this->returnValue($expectedResult));
$this->assertEquals($expectedResult, $this->client->execute('testCall'));
}
/**
* @dataProvider executeAttemptsFailedDataProvider
*/
public function testExecuteAttemptsFailed(string $responseBody, string $responseCode, string $expectedMessage)
{
$exceptionMessage = 'Dotmailer REST client exception:' . PHP_EOL .
'[exception type] Oro\Bundle\DotmailerBundle\Exception\RestClientAttemptException' . PHP_EOL .
'[exception message] ' . $expectedMessage . PHP_EOL .
'[request url] testCall' . PHP_EOL .
'[request method] ' . PHP_EOL .
'[request data] ' . PHP_EOL .
'[response code] ' . $responseCode . PHP_EOL .
'[response body] ' . $responseBody;
$this->expectException(\Oro\Bundle\DotmailerBundle\Exception\RestClientException::class);
$this->expectExceptionMessage($exceptionMessage);
$restClient = $this->createMock('RestClient\Client');
ReflectionUtil::setPropertyValue($this->client, 'restClient', $restClient);
ReflectionUtil::setPropertyValue($this->client, 'sleepBetweenAttempt', [0.1, 0.2, 0.3, 0.4]);
$request = $this->createMock('RestClient\Request');
$restClient->expects($this->exactly(5))
->method('newRequest')
->will($this->returnValue($request));
$request->expects($this->exactly(5))
->method('getResponse')
->will($this->returnValue($this->response));
$this->response->expects($this->exactly(5))
->method('getInfo')
->will($this->returnValue($this->info));
$this->info->http_code = $responseCode;
$this->response->expects($this->exactly(5))
->method('getParsedResponse')
->will($this->returnValue($responseBody));
$this->logger->expects($this->exactly(8))
->method('warning')
->withConsecutive(
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 1 with 0.1 sec delay.'],
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 2 with 0.2 sec delay.'],
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 3 with 0.3 sec delay.'],
['[Warning] Attempt failed. Error message:' . PHP_EOL . $exceptionMessage],
['[Warning] Attempt number 4 with 0.4 sec delay.']
);
$this->client->execute('testCall');
}
protected function initClient()
{
$restClient = $this->createMock('\RestClient\Client');
ReflectionUtil::setPropertyValue($this->client, 'restClient', $restClient);
$request = $this->createMock('\RestClient\Request');
$restClient->expects($this->once())
->method('newRequest')
->will($this->returnValue($request));
$request->expects($this->once())
->method('getResponse')
->will($this->returnValue($this->response));
$this->response->expects($this->once())
->method('getInfo')
->will($this->returnValue($this->info));
}
public function testOnClear()
{
ReflectionUtil::setPropertyValue($this->manager, 'currentWebsite', new Website());
$this->manager->onClear();
self::assertEmpty(ReflectionUtil::getPropertyValue($this->manager, 'currentWebsite'));
}
public function testHandleWithRememberedToken(): void
{
$rememberedToken = new AnonymousCustomerUserToken('User');
ReflectionUtil::setPropertyValue($this->listener, 'rememberedToken', $rememberedToken);
$this->tokenStorage->expects(self::once())
->method('getToken')
->willReturn(null);
$this->tokenStorage->expects(self::once())
->method('setToken')
->with($rememberedToken);
($this->listener)($this->getRequestEvent(new Request()));
self::assertNull(ReflectionUtil::getPropertyValue($this->listener, 'rememberedToken'));
self::assertEmpty($this->logger->cleanLogs());
}