/** * @covers ::getContextValues */ public function testGetContextValuesEntityContext() { $input = ['foo' => ['label' => 'Foo', 'type' => 'entity:node', 'value' => 'the_node_uuid']]; $expected = new EntityLazyLoadContext(new ContextDefinition('entity:node', 'Foo'), $this->entityRepository->reveal(), 'the_node_uuid'); $actual = $this->staticContext->getContextValues($input)['foo']; $this->assertEquals($expected, $actual); }
/** * Tests the action execution. * * @covers ::execute */ public function testActionExecution() { $path = 'node/1'; $this->aliasStorage->delete(['path' => $path])->shouldBeCalledTimes(1); $this->action->setContextValue('path', $path); $this->action->execute(); }
/** * Tests the action execution when saving is postponed. * * @covers ::execute */ public function testActionExecutionPostponed() { $this->entity->save()->shouldNotBeCalled(); $this->action->setContextValue('entity', $this->entity->reveal()); $this->action->execute(); $this->assertEquals($this->action->autoSaveContext(), ['entity'], 'Action returns the entity context name for auto saving.'); }
/** * Tests the action execution. * * @covers ::execute */ public function testActionExecution() { $alias = 'about/team'; $this->aliasStorage->delete(['alias' => $alias])->shouldBeCalledTimes(1); $this->action->setContextValue('alias', $alias); $this->action->execute(); }
/** * Sets up the entity type manager to be tested. * * @param \Drupal\Core\Entity\EntityTypeInterface[]|\Prophecy\Prophecy\ProphecyInterface[] $definitions * (optional) An array of entity type definitions. */ protected function setUpEntityTypeDefinitions($definitions = []) { $class = $this->getMockClass(EntityInterface::class); foreach ($definitions as $key => $entity_type) { // \Drupal\Core\Entity\EntityTypeInterface::getLinkTemplates() is called // by \Drupal\Core\Entity\EntityManager::processDefinition() so it must // always be mocked. $entity_type->getLinkTemplates()->willReturn([]); // Give the entity type a legitimate class to return. $entity_type->getClass()->willReturn($class); $definitions[$key] = $entity_type->reveal(); } $this->entityTypeManager->getDefinition(Argument::cetera())->will(function ($args) use($definitions) { $entity_type_id = $args[0]; $exception_on_invalid = $args[1]; if (isset($definitions[$entity_type_id])) { return $definitions[$entity_type_id]; } elseif (!$exception_on_invalid) { return NULL; } else { throw new PluginNotFoundException($entity_type_id); } }); $this->entityTypeManager->getDefinitions()->willReturn($definitions); }
/** * Tests the clearCachedDefinitions() method. * * @covers ::clearCachedDefinitions */ public function testClearCachedDefinitions() { $this->entityTypeManager->clearCachedDefinitions()->shouldBeCalled(); $this->entityTypeRepository->clearCachedDefinitions()->shouldBeCalled(); $this->entityTypeBundleInfo->clearCachedBundles()->shouldBeCalled(); $this->entityFieldManager->clearCachedFieldDefinitions()->shouldBeCalled(); $this->entityManager->clearCachedDefinitions(); }
/** * Tests the action execution when a language is specified. * * @covers ::execute */ public function testActionExecutionWithLanguage() { $language = $this->prophesize(LanguageInterface::class); $language->getId()->willReturn('en'); $this->aliasStorage->save('node/1', 'about', 'en')->shouldBeCalledTimes(1); $this->action->setContextValue('source', 'node/1')->setContextValue('alias', 'about')->setContextValue('language', $language->reveal()); $this->action->execute(); }
/** * Tests sending a mail to two recipients. * * @covers ::execute */ public function testSendMailToTwoRecipients() { $to = ['*****@*****.**', '*****@*****.**']; $this->action->setContextValue('to', $to)->setContextValue('subject', 'subject')->setContextValue('message', 'hello'); $params = ['subject' => 'subject', 'message' => 'hello']; $this->mailManager->mail('rules', 'rules_action_mail_' . $this->action->getPluginId(), implode(', ', $to), LanguageInterface::LANGCODE_SITE_DEFAULT, $params, NULL)->willReturn(['result' => TRUE])->shouldBeCalledTimes(1); $this->logger->notice(Argument::any(), Argument::any())->shouldBeCalledTimes(1); $this->action->execute(); }
/** * Tests sending a mail to two recipients. * * @covers ::execute */ public function testSendMailToTwoRecipients() { $to = ['*****@*****.**', '*****@*****.**']; $this->action->setContextValue('to', $to)->setContextValue('subject', 'subject')->setContextValue('message', 'hello'); $params = ['subject' => 'subject', 'message' => 'hello']; $this->mailManager->mail('rules', 'rules_action_mail_' . $this->action->getPluginId(), implode(', ', $to), LanguageInterface::LANGCODE_SITE_DEFAULT, $params, NULL)->willReturn(['result' => TRUE])->shouldBeCalledTimes(1); $this->logger->log(LogLevel::NOTICE, SafeMarkup::format('Successfully sent email to %to', ['%to' => implode(', ', $to)]))->shouldBeCalledTimes(1); $this->action->execute(); }
/** * @covers ::getContexts * @covers ::removeStaticContext */ public function testGetContextsAfterReset() { $this->contextMapper->getContextValues([])->willReturn([])->shouldBeCalledTimes(2); $this->page->getContexts()->willReturn([])->shouldBeCalledTimes(2); $expected = []; $contexts = $this->pageVariant->getContexts(); $this->assertSame($expected, $contexts); $this->pageVariant->removeStaticContext('anything'); $contexts = $this->pageVariant->getContexts(); $this->assertSame($expected, $contexts); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->typedDataManager = $this->prophesize(TypedDataManager::class); $container = new ContainerBuilder(); $container->set('string_translation', $this->getStringTranslationStub()); $container->set('typed_data_manager', $this->typedDataManager->reveal()); \Drupal::setContainer($container); $this->page = $this->prophesize(PageInterface::class); $this->event = new PageManagerContextEvent($this->page->reveal()); }
/** * @dataProvider getInvokeParameters */ public function testInvoke(Request $request, ProphecyInterface $twigProphecy) { $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class); $resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['Foo', 'Bar']))->shouldBeCalled(); $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class); $resourceMetadataFactoryProphecy->create('Foo')->willReturn(new ResourceMetadata('F'))->shouldBeCalled(); $serializerProphecy = $this->prophesize(SerializerInterface::class); $serializerProphecy->serialize(Argument::type(Documentation::class), 'json')->willReturn('hello')->shouldBeCalled(); $action = new SwaggerUiAction($resourceNameCollectionFactoryProphecy->reveal(), $resourceMetadataFactoryProphecy->reveal(), $serializerProphecy->reveal(), $twigProphecy->reveal()); $action($request); }
/** * Tests the action execution with a saved entity. * * @covers ::execute */ public function testActionExecutionWithSavedEntity() { // Test that the alias is only saved once. $this->aliasStorage->save('test/1', 'about', 'en')->shouldBeCalledTimes(1); $entity = $this->getMockEntity(); $entity->isNew()->willReturn(FALSE)->shouldBeCalledTimes(1); // Test that existing entities are not saved again. $entity->save()->shouldNotBeCalled(); $this->action->setContextValue('entity', $entity->reveal())->setContextValue('alias', 'about'); $this->action->execute(); }
/** * @dataProvider getCreateDependencies */ public function testCreate(ProphecyInterface $reader, ProphecyInterface $decorated = null, $expectedShortName, $expectedDescription) { $factory = new AnnotationResourceMetadataFactory($reader->reveal(), $decorated ? $decorated->reveal() : null); $metadata = $factory->create(Dummy::class); $this->assertEquals($expectedShortName, $metadata->getShortName()); $this->assertEquals($expectedDescription, $metadata->getDescription()); $this->assertEquals('http://example.com', $metadata->getIri()); $this->assertEquals(['foo' => ['bar' => true]], $metadata->getItemOperations()); $this->assertEquals(['baz' => ['tab' => false]], $metadata->getCollectionOperations()); $this->assertEquals(['a' => 1], $metadata->getAttributes()); }
/** * @dataProvider getDependencies */ public function testCreate(ProphecyInterface $decorated = null, array $results) { $reader = $this->prophesize(Reader::class); $reader->getPropertyAnnotation(new \ReflectionProperty(Dummy::class, 'name'), ApiProperty::class)->willReturn(new ApiProperty())->shouldBeCalled(); $reader->getPropertyAnnotation(Argument::type(\ReflectionProperty::class), ApiProperty::class)->willReturn(null)->shouldBeCalled(); $reader->getMethodAnnotation(new \ReflectionMethod(Dummy::class, 'getName'), ApiProperty::class)->willReturn(new ApiProperty())->shouldBeCalled(); $reader->getMethodAnnotation(new \ReflectionMethod(Dummy::class, 'getAlias'), ApiProperty::class)->willReturn(new ApiProperty())->shouldBeCalled(); $reader->getMethodAnnotation(Argument::type(\ReflectionMethod::class), ApiProperty::class)->willReturn(null)->shouldBeCalled(); $factory = new AnnotationPropertyNameCollectionFactory($reader->reveal(), $decorated ? $decorated->reveal() : null); $metadata = $factory->create(Dummy::class, []); $this->assertEquals($results, iterator_to_array($metadata)); }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->trueConditionExpression = $this->prophesize(ConditionExpressionInterface::class); $this->trueConditionExpression->execute()->willReturn(TRUE); $this->trueConditionExpression->executeWithState(Argument::type(RulesStateInterface::class))->willReturn(TRUE); $this->falseConditionExpression = $this->prophesize(ConditionExpressionInterface::class); $this->falseConditionExpression->execute()->willReturn(FALSE); $this->falseConditionExpression->executeWithState(Argument::type(RulesStateInterface::class))->willReturn(FALSE); $this->testActionExpression = $this->prophesize(ActionExpressionInterface::class); $this->expressionManager = $this->prophesize(ExpressionManagerInterface::class); }
/** * Tests evaluating the condition for path without an alias. * * @covers ::evaluate */ public function testConditionEvaluationPathWithoutAlias() { $this->aliasManager->getAliasByPath('path-without-alias', NULL)->willReturn('path-without-alias')->shouldBeCalledTimes(1); $this->aliasManager->getAliasByPath('path-without-alias', 'en')->willReturn('path-without-alias')->shouldBeCalledTimes(1); // First, only set the path context. $this->condition->setContextValue('path', 'path-without-alias'); // Test without language context set. $this->assertFalse($this->condition->evaluate()); // Test with language context set. $this->condition->setContextValue('language', $this->englishLanguage->reveal()); $this->assertFalse($this->condition->evaluate()); }
/** * Tests evaluating the condition for an alias that can not be resolved. * * @covers ::evaluate */ public function testConditionEvaluationAliasWithoutPath() { $this->aliasManager->getPathByAlias('alias-for-path-that-does-not-exist', NULL)->willReturn('alias-for-path-that-does-not-exist')->shouldBeCalledTimes(1); $this->aliasManager->getPathByAlias('alias-for-path-that-does-not-exist', 'en')->willReturn('alias-for-path-that-does-not-exist')->shouldBeCalledTimes(1); // First, only set the path context. $this->condition->setContextValue('alias', 'alias-for-path-that-does-not-exist'); // Test without language context set. $this->assertFalse($this->condition->evaluate()); // Test with language context set. $this->condition->setContextValue('language', $this->englishLanguage->reveal()); $this->assertFalse($this->condition->evaluate()); }
/** * @dataProvider getDependencies */ public function testCreateProperty(ProphecyInterface $reader, ProphecyInterface $decorated = null, string $description) { $factory = new AnnotationPropertyMetadataFactory($reader->reveal(), $decorated ? $decorated->reveal() : null); $metadata = $factory->create(Dummy::class, 'name'); $this->assertEquals($description, $metadata->getDescription()); $this->assertTrue($metadata->isReadable()); $this->assertTrue($metadata->isWritable()); $this->assertFalse($metadata->isReadableLink()); $this->assertFalse($metadata->isWritableLink()); $this->assertFalse($metadata->isIdentifier()); $this->assertTrue($metadata->isRequired()); $this->assertEquals('foo', $metadata->getIri()); $this->assertEquals(['foo' => 'bar'], $metadata->getAttributes()); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class); $this->entityTypeManager->getDefinitions()->willReturn([$this->entityTypeId => '']); $this->processPlugin = new LinkUri([], 'link_uri', [], $this->entityTypeManager->reveal()); // Url::fromInternalUri() accesses the path validator from the global // container. // @see \Drupal\Core\Url::fromInternalUri() $this->pathValidator = $this->prophesize(PathValidator::class); $container = new ContainerBuilder(); $container->set('path.validator', $this->pathValidator->reveal()); \Drupal::setContainer($container); }
/** * Tests the getAllBundleInfo() method. * * @covers ::getAllBundleInfo */ public function testGetAllBundleInfo() { $this->moduleHandler->invokeAll('entity_bundle_info')->willReturn([]); $this->moduleHandler->alter('entity_bundle_info', Argument::type('array'))->willReturn(NULL); $apple = $this->prophesize(EntityTypeInterface::class); $apple->getLabel()->willReturn('Apple'); $apple->getBundleOf()->willReturn(NULL); $banana = $this->prophesize(EntityTypeInterface::class); $banana->getLabel()->willReturn('Banana'); $banana->getBundleOf()->willReturn(NULL); $this->setUpEntityTypeDefinitions(['apple' => $apple, 'banana' => $banana]); $this->cacheBackend->get('entity_bundle_info:en')->willReturn(FALSE); $this->cacheBackend->set('entity_bundle_info:en', Argument::any(), Cache::PERMANENT, ['entity_types', 'entity_bundles'])->will(function () { $this->get('entity_bundle_info:en')->willReturn((object) ['data' => 'cached data'])->shouldBeCalled(); })->shouldBeCalled(); $this->cacheTagsInvalidator->invalidateTags(['entity_bundles'])->shouldBeCalled(); $this->typedDataManager->clearCachedDefinitions()->shouldBeCalled(); $expected = ['apple' => ['apple' => ['label' => 'Apple']], 'banana' => ['banana' => ['label' => 'Banana']]]; $bundle_info = $this->entityTypeBundleInfo->getAllBundleInfo(); $this->assertSame($expected, $bundle_info); $bundle_info = $this->entityTypeBundleInfo->getAllBundleInfo(); $this->assertSame($expected, $bundle_info); $this->entityTypeBundleInfo->clearCachedBundles(); $bundle_info = $this->entityTypeBundleInfo->getAllBundleInfo(); $this->assertSame('cached data', $bundle_info); }
/** * Tests the unique machine name generator. * * @see \Drupal\block\BlockForm::getUniqueMachineName() */ public function testGetUniqueMachineName() { $blocks = array(); $blocks['test'] = $this->getBlockMockWithMachineName('test'); $blocks['other_test'] = $this->getBlockMockWithMachineName('other_test'); $blocks['other_test_1'] = $this->getBlockMockWithMachineName('other_test'); $blocks['other_test_2'] = $this->getBlockMockWithMachineName('other_test'); $query = $this->getMock('Drupal\\Core\\Entity\\Query\\QueryInterface'); $query->expects($this->exactly(5))->method('condition')->will($this->returnValue($query)); $query->expects($this->exactly(5))->method('execute')->will($this->returnValue(array('test', 'other_test', 'other_test_1', 'other_test_2'))); $this->storage->expects($this->exactly(5))->method('getQuery')->will($this->returnValue($query)); $block_form_controller = new BlockForm($this->entityManager, $this->conditionManager, $this->contextRepository, $this->language, $this->themeHandler, $this->pluginFormFactory->reveal()); // Ensure that the block with just one other instance gets the next available // name suggestion. $this->assertEquals('test_2', $block_form_controller->getUniqueMachineName($blocks['test'])); // Ensure that the block with already three instances (_0, _1, _2) gets the // 4th available name. $this->assertEquals('other_test_3', $block_form_controller->getUniqueMachineName($blocks['other_test'])); $this->assertEquals('other_test_3', $block_form_controller->getUniqueMachineName($blocks['other_test_1'])); $this->assertEquals('other_test_3', $block_form_controller->getUniqueMachineName($blocks['other_test_2'])); // Ensure that a block without an instance yet gets the suggestion as // unique machine name. $last_block = $this->getBlockMockWithMachineName('last_test'); $this->assertEquals('last_test', $block_form_controller->getUniqueMachineName($last_block)); }
/** * Tests overriding an existing route. * * @covers ::alterRoutes * @covers ::findPageRouteName * * @dataProvider providerTestAlterRoutesOverrideExisting */ public function testAlterRoutesOverrideExisting($page_path, $existing_route_path, $requirements = []) { $route_name = 'test_route'; // Set up a page with the same path as an existing route. $page = $this->prophesize(PageInterface::class); $page->status()->willReturn(TRUE)->shouldBeCalled(); $page->getPath()->willReturn($page_path)->shouldBeCalled(); $variant1 = $this->prophesize(PageVariantInterface::class); $variant1->getWeight()->willReturn(0); $page->getVariants()->willReturn(['variant1' => $variant1->reveal()]); $page->id()->willReturn('page1'); $page->label()->willReturn(NULL); $page->usesAdminTheme()->willReturn(FALSE); $this->pageStorage->loadMultiple()->willReturn(['page1' => $page->reveal()])->shouldBeCalledTimes(1); $this->cacheTagsInvalidator->invalidateTags(["page_manager_route_name:{$route_name}"])->shouldBeCalledTimes(1); $collection = new RouteCollection(); $collection->add($route_name, new Route($existing_route_path, ['default_exists' => 'default_value'], $requirements, ['parameters' => ['foo' => 'bar']])); $route_event = new RouteBuildEvent($collection); $this->routeSubscriber->onAlterRoutes($route_event); // The normal route name is not used, the existing route name is instead. $this->assertSame(1, $collection->count()); $this->assertNull($collection->get('page_manager.page_view_page1')); $this->assertNull($collection->get('page_manager.page_view_page1_variant1')); $route = $collection->get($route_name); $expected_defaults = ['_entity_view' => 'page_manager_page_variant', '_title' => NULL, 'page_manager_page_variant' => 'variant1', 'page_manager_page' => 'page1', 'page_manager_page_variant_weight' => 0, 'base_route_name' => $route_name]; $expected_requirements = $requirements; $expected_options = ['compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler', 'parameters' => ['page_manager_page_variant' => ['type' => 'entity:page_variant'], 'page_manager_page' => ['type' => 'entity:page'], 'foo' => 'bar'], '_admin_route' => FALSE]; $this->assertMatchingRoute($route, $existing_route_path, $expected_defaults, $expected_requirements, $expected_options); }
/** * Tests unsuccessful redirection due to rules admin page location. * * @covers ::execute */ public function testRedirectRulesAdminPage() { $this->currentPathStack->getPath()->willReturn('admin/config/workflow/rules'); $this->action->setContextValue('url', '/test/url'); $this->action->execute(); $this->logger->warning('Skipped page redirect on a rules admin page.')->shouldHaveBeenCalled(); }
/** * Tests the action execution without Context IP set. * * Should fallback to the current IP of the request. * * @covers ::execute */ public function testActionExecutionWithoutContextIP() { // TEST-NET-1 IPv4. $ip = '192.0.2.0'; $this->request->getClientIp()->willReturn($ip)->shouldBeCalledTimes(1); $this->banManager->banIp($ip)->shouldBeCalledTimes(1); $this->action->execute(); }
/** * @covers ::getEntityTypeIdKeyType */ public function testGetEntityTypeIdKeyTypeNotFieldable() { $entity_type = $this->prophesize(EntityTypeInterface::class); $entity_type->isSubclassOf(FieldableEntityInterface::class)->willReturn(FALSE); $this->entityFieldManager->getFieldStorageDefinitions(Argument::any())->shouldNotBeCalled(); $type = $this->routeProvider->getEntityTypeIdKeyType($entity_type->reveal()); $this->assertNull($type); }
/** * Test execute() method for blocked and anonymous users. * * @covers ::execute */ public function testBlockUserWithBlockedAnonymousUser() { $user = $this->getUserMock(self::BLOCKED, self::ANONYMOUS); $user->block()->shouldNotBeCalled(); $this->sessionManager->delete()->shouldNotBeCalled(); $this->action->setContextValue('user', $user->reveal()); $this->action->execute(); $this->assertEquals($this->action->autoSaveContext(), [], 'Action returns nothing for auto saving since the user has not been altered.'); }
/** * Tests that negating a condition works. */ public function testNegation() { $this->trueCondition->getContextDefinitions()->willReturn([]); $this->trueCondition->refineContextDefinitions([])->shouldBeCalledTimes(1); $this->trueCondition->getProvidedContextDefinitions()->willReturn([])->shouldBeCalledTimes(1); $this->conditionManager->createInstance('test_condition', ['negate' => TRUE])->willReturn($this->trueCondition->reveal())->shouldBeCalledTimes(1); // Create a condition which is negated. $condition_expression = new RulesCondition(['condition_id' => 'test_condition', 'negate' => TRUE], '', [], $this->conditionManager->reveal(), $this->processorManager->reveal()); $this->assertFalse($condition_expression->execute()); }
/** * Tests that context values get data processed with processor mappings. */ public function testDataProcessor() { $condition = new RulesCondition(['condition_id' => 'test_condition'] + ContextConfig::create()->process('test', 'foo', [])->toArray(), '', [], $this->conditionManager->reveal(), $this->processorManager->reveal()); // Build some mocked context and definitions for our mock condition. $context = $this->prophesize(ContextInterface::class); $condition->setContext('test', $context->reveal()); $this->trueCondition->getContextDefinitions()->willReturn(['test' => $this->prophesize(ContextDefinitionInterface::class)->reveal()])->shouldBeCalledTimes(2); $this->trueCondition->getProvidedContextDefinitions()->willReturn([])->shouldBeCalledTimes(1); // Mock some original old value that will be replaced by the data processor. $this->trueCondition->getContextValue('test')->willReturn('old_value')->shouldBeCalledTimes(1); // The outcome of the data processor needs to get set on the condition. $this->trueCondition->setContextValue('test', 'new_value')->shouldBeCalledTimes(1); $this->trueCondition->refineContextDefinitions()->shouldBeCalledTimes(1); $this->conditionManager->createInstance('test_condition', ['negate' => FALSE])->willReturn($this->trueCondition->reveal())->shouldBeCalledTimes(1); $this->conditionManager->createInstance('test_condition')->willReturn($this->trueCondition->reveal())->shouldBeCalledTimes(1); $data_processor = $this->prophesize(DataProcessorInterface::class); $data_processor->process('old_value', Argument::any())->willReturn('new_value')->shouldBeCalledTimes(1); $this->processorManager->createInstance('foo', [])->willReturn($data_processor->reveal())->shouldBeCalledTimes(1); $this->assertTrue($condition->execute()); }
/** * Tests that nested rules are properly executed. * * @covers ::execute */ public function testNestedRules() { $this->testActionExpression->executeWithState(Argument::type(ExecutionStateInterface::class))->shouldBeCalledTimes(1); $nested = new Rule([], 'rules_rule', [], $this->expressionManager->reveal()); // We need to replace the action and conditon container to not have the same // instances as in the outer rule. $nested->setConditions(new RulesAnd([], 'rules_and', [], $this->expressionManager->reveal())); $nested->setActions(new ActionSet([], 'rules_action_set', [], $this->expressionManager->reveal())); $nested->addExpressionObject($this->trueConditionExpression->reveal())->addExpressionObject($this->testActionExpression->reveal()); $this->rule->addExpressionObject($this->trueConditionExpression->reveal())->addExpressionObject($nested)->execute(); }