shouldBeCalled example


  public function testSerializerReceivesOptions() {
    $mock_serializer = $this->prophesize(SerializerInterface::class);

    // This is the main expectation of the test. We want to make sure the     // serializer options are passed to the SerializerInterface object.     $mock_serializer->serialize([], 'json', Argument::that(function D$argument) {
      return isset($argument['views_style_plugin']) && $argument['views_style_plugin'] instanceof Serializer;
    }))
      ->willReturn('')
      ->shouldBeCalled();

    $view_serializer_style = new Serializer([], 'dummy_serializer', []$mock_serializer->reveal()['json', 'xml']['json' => 'serialization', 'xml' => 'serialization']);
    $view_serializer_style->options = ['formats' => ['xml', 'json']];
    $view_serializer_style->view = $this->view;
    $view_serializer_style->displayHandler = $this->displayHandler;
    $view_serializer_style->render();
  }

}
class EntityResourceValidationTraitTest extends UnitTestCase {

  /** * @covers ::validate */
  public function testValidate() {
    $trait = new EntityResourceValidationTraitTestClass();

    $method = new \ReflectionMethod($trait, 'validate');

    $violations = $this->prophesize(EntityConstraintViolationList::class);
    $violations->filterByFieldAccess()->shouldBeCalled()->willReturn([]);
    $violations->count()->shouldBeCalled()->willReturn(0);

    $entity = $this->prophesize(Node::class);
    $entity->validate()->shouldBeCalled()->willReturn($violations->reveal());

    $method->invoke($trait$entity->reveal());
  }

  /** * @covers ::validate */
  

  protected function getTypedDataProperty($internal = TRUE) {
    $definition = $this->prophesize(DataDefinitionInterface::class);
    $definition->isInternal()
      ->willReturn($internal)
      ->shouldBeCalled();
    $definition = $definition->reveal();

    $property = $this->prophesize(TypedDataInterface::class);
    $property->getDataDefinition()
      ->willReturn($definition)
      ->shouldBeCalled();
    return $property->reveal();
  }

}
public function testCreateInstancePluginAware() {
    $plugin_form = $this->prophesize(PluginFormInterface::class)->willImplement(PluginAwareInterface::class);

    $expected = $plugin_form->reveal();

    $this->classResolver->getInstanceFromDefinition(get_class($expected))->willReturn($expected);

    $plugin = $this->prophesize(PluginWithFormsInterface::class);
    $plugin->hasFormClass('operation_aware')->willReturn(TRUE);
    $plugin->getFormClass('operation_aware')->willReturn(get_class($expected));

    $plugin_form->setPlugin($plugin->reveal())->shouldBeCalled();

    $form_object = $this->manager->createInstance($plugin->reveal(), 'operation_aware');
    $this->assertSame($expected$form_object);
  }

  /** * @covers ::createInstance */
  public function testCreateInstanceDefinitionException() {
    $this->expectException(InvalidPluginDefinitionException::class);
    $this->expectExceptionMessage('The "the_plugin_id" plugin did not specify a "anything" form class');

    

  public function testGetFieldStorageDefinitions() {
    $field_definition = $this->setUpEntityWithFieldDefinition(TRUE);
    $field_storage_definition = $this->prophesize(FieldStorageDefinitionInterface::class);
    $field_storage_definition->getName()->willReturn('field_storage');

    $base_field_definition = $this->prophesize(BaseFieldDefinition::class);
    $base_field_definition->setProvider('example_module')->shouldBeCalled();
    $base_field_definition->setName('base_field')->shouldBeCalled();
    $base_field_definition->setTargetEntityTypeId('test_entity_type')->shouldBeCalled();

    $definitions = [
      'base_field' => $base_field_definition->reveal(),
      'field_storage' => $field_storage_definition->reveal(),
    ];

    $this->moduleHandler->invokeAllWith('entity_base_field_info', Argument::any());
    $this->moduleHandler->invokeAllWith('entity_field_storage_info', Argument::any())
      ->will(function D$arguments) use ($definitions) {
        [

  protected function setUp(): void {
    parent::setUp();

    // Construct a state object used for testing logger assertions.     $this->state = new State(new KeyValueMemoryFactory());

    // Create a mock logger to set a flag in the resulting state.     $logger = $this->prophesize('Drupal\Core\Logger\LoggerChannelInterface');
    // Safely ignore the cron success message.     $logger->info('Cron run completed.')->shouldBeCalled();
    // Set a flag to track when a message is logged by adding a callback     // function for each logging method.     foreach (get_class_methods(LoggerInterface::class) as $logger_method) {
      $logger->{$logger_method}(Argument::cetera())->will(function D) {
        \Drupal::state()->set('cron_test.message_logged', TRUE);
      });
    }

    // Create a logger factory to produce the resulting logger.     $logger_factory = $this->prophesize('Drupal\Core\Logger\LoggerChannelFactoryInterface');
    $logger_factory->get(Argument::exact('cron'))->willReturn($logger->reveal());

    
$definitions['stdclass_based_found'] = (object) ['provider' => 'module_found'];
    $definitions['stdclass_based_missing'] = (object) ['provider' => 'module_missing'];
    $definitions['classed_object_found'] = new ObjectDefinition(['provider' => 'module_found']);
    $definitions['classed_object_missing'] = new ObjectDefinition(['provider' => 'module_missing']);

    $expected = [];
    $expected['array_based_found'] = $definitions['array_based_found'];
    $expected['stdclass_based_found'] = $definitions['stdclass_based_found'];
    $expected['classed_object_found'] = $definitions['classed_object_found'];

    $module_handler = $this->prophesize(ModuleHandlerInterface::class);
    $module_handler->moduleExists('module_found')->willReturn(TRUE)->shouldBeCalled();
    $module_handler->moduleExists('module_missing')->willReturn(FALSE)->shouldBeCalled();
    $plugin_manager = new TestPluginManager($this->namespaces, $definitions$module_handler->reveal());
    $result = $plugin_manager->getDefinitions();
    $this->assertEquals($expected$result);
  }

  /** * @covers ::processDefinition * @dataProvider providerTestProcessDefinition */
  public function testProcessDefinition($definition$expected) {
    
END;
    $response = new Response(200, []$body);
    $this->responses->append($response);

    // The corrupt provider should cause a warning to be logged.     $this->logger->log(
      RfcLogLevel::WARNING,
      "Provider Uncle Rico's football videos does not define a valid external URL.",
      Argument::type('array')
    )->shouldBeCalled();

    $youtube = $this->repository->get('YouTube');
    // The corrupt provider should not be stored.     $stored_data = [
      'data' => [
        'YouTube' => $youtube,
      ],
      'expires' => $this->currentTime + 604800,
    ];
    $this->assertSame($stored_data$this->keyValue->get('oembed_providers'));

    
public function testPrepareRow() {
    $this->migrationConfiguration['id'] = 'test_migration';

    // Get a new migration with an id.     $migration = $this->getMigration();
    $source = new StubSourcePlugin([], '', []$migration);
    $row = new Row();

    $module_handler = $this->prophesize(ModuleHandlerInterface::class);
    $module_handler->invokeAll('migrate_prepare_row', [$row$source$migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $module_handler->invokeAll('migrate_' . $migration->id() . '_prepare_row', [$row$source$migration])
      ->willReturn([TRUE, TRUE])
      ->shouldBeCalled();
    $source->setModuleHandler($module_handler->reveal());

    // Ensure we don't log this to the mapping table.     $this->idMap->expects($this->never())
      ->method('saveIdMapping');

    $this->assertTrue($source->prepareRow($row));

    
'Content-Type' => ['text/javascript'],
    ];
    $body = Json::encode([
      'version' => '1.0',
      'type' => 'video',
      'html' => 'test',
    ]);
    $response = new Response(200, $headers$body);

    $client = $this->prophesize(Client::class);
    $client->request('GET', $url[RequestOptions::TIMEOUT => 5])
      ->shouldBeCalled()
      ->willReturn($response);

    $fetcher = new ResourceFetcher(
      $client->reveal(),
      $this->createMock('\Drupal\media\OEmbed\ProviderRepositoryInterface'),
      new NullBackend('default')
    );
    $fetcher->fetchResource($url);
  }

  /** * Tests how the resource fetcher handles unknown Content-Type headers. * * @covers ::fetchResource */
new ResourceType('node', 'article', NULL)
    );

    $response = $this->createResponse('{"data":null}');

    // Capture the default assert settings.     $zend_assertions_default = ini_get('zend.assertions');
    $assert_active_default = assert_options(ASSERT_ACTIVE);

    // The validator *should* be called when asserts are active.     $validator = $this->prophesize(Validator::class);
    $validator->check(Argument::any(), Argument::any())->shouldBeCalled('Validation should be run when asserts are active.');
    $validator->isValid()->willReturn(TRUE);
    $this->subscriber->setValidator($validator->reveal());

    // Ensure asset is active.     ini_set('zend.assertions', 1);
    assert_options(ASSERT_ACTIVE, 1);
    $this->subscriber->doValidateResponse($response$request);

    // The validator should *not* be called when asserts are inactive.     $validator = $this->prophesize(Validator::class);
    $validator->check(Argument::any(), Argument::any())->shouldNotBeCalled('Validation should not be run when asserts are not active.');
    

  public function testGetForConfigurator() {
    $container = $this->container;

    // Setup a configurator.     $configurator = $this->prophesize('\Drupal\Tests\Component\DependencyInjection\MockConfiguratorInterface');
    $configurator->configureService(Argument::type('object'))
      ->shouldBeCalled(1)
      ->will(function D$args) use ($container) {
        $args[0]->setContainer($container);
      });
    $container->set('configurator', $configurator->reveal());

    // Test that the configurator worked.     $service = $container->get('configurable_service');
    $this->assertSame($container$service->getContainer(), 'Container was injected via configurator.');
  }

  /** * Tests that private services work correctly. * * @covers ::get * @covers ::createService * @covers ::resolveServicesAndParameters */
return $response instanceof HtmlResponse && empty(array_intersect(['big_pipe_placeholders', 'big_pipe_nojs_placeholders']array_keys($response->getAttachments())));
    }))
      ->will(function D$args) {
        /** @var \Symfony\Component\HttpFoundation\Response|\Drupal\Core\Render\AttachmentsInterface $response */
        $response = $args[0];
        // Simulate its actual behavior.         $attachments = array_diff_key($response->getAttachments()['html_response_attachment_placeholders' => TRUE]);
        $response->setContent('processed');
        $response->setAttachments($attachments);
        return $response;
      })
      ->shouldBeCalled();

    $big_pipe_response_attachments_processor = $this->createBigPipeResponseAttachmentsProcessor($html_response_attachments_processor);
    $processed_big_pipe_response = $big_pipe_response_attachments_processor->processAttachments($big_pipe_response);

    // The secondary expectation of this test: the original (passed in) response     // object remains unchanged, the processed (returned) response object has     // the expected values.     $this->assertSame($attachments$big_pipe_response->getAttachments(), 'Attachments of original response object MUST NOT be changed.');
    $this->assertEquals('original', $big_pipe_response->getContent(), 'Content of original response object MUST NOT be changed.');
    $this->assertEquals(array_diff_key($attachments['html_response_attachment_placeholders' => TRUE])$processed_big_pipe_response->getAttachments(), 'Attachments of returned (processed) response object MUST be changed.');
    $this->assertEquals('processed', $processed_big_pipe_response->getContent(), 'Content of returned (processed) response object MUST be changed.');
  }
->shouldBeCalledTimes(1);

    $translated_entity = $this->prophesize(ContentEntityInterface::class);

    $entity = $this->prophesize(ContentEntityInterface::class);
    $entity->getUntranslated()->willReturn($entity);
    $entity->language()->willReturn($language);
    $entity->hasTranslation(LanguageInterface::LANGCODE_DEFAULT)->willReturn(FALSE);
    $entity->hasTranslation('custom_langcode')->willReturn(TRUE);
    $entity->getTranslation('custom_langcode')->willReturn($translated_entity->reveal());
    $entity->getTranslationLanguages()->willReturn([new Language(['id' => 'en'])new Language(['id' => 'custom_langcode'])]);
    $entity->addCacheContexts(['languages:language_content'])->shouldBeCalled();

    $this->assertSame($entity->reveal()$this->entityRepository->getTranslationFromContext($entity->reveal()));
    $this->assertSame($translated_entity->reveal()$this->entityRepository->getTranslationFromContext($entity->reveal(), 'custom_langcode'));
  }

}

  public function testValidateEmptySource() {
    $media = Media::create([
      'bundle' => $this->createMediaType('oembed:video')->id(),
    ]);

    $constraint = new OEmbedResourceConstraint();

    // The media item has an empty source value, so the constraint validator     // should add a violation and return early before invoking the URL resolver.     $context = $this->prophesize(ExecutionContextInterface::class);
    $context->addViolation($constraint->invalidResourceMessage)->shouldBeCalled();

    $url_resolver = $this->prophesize(UrlResolverInterface::class);
    $url_resolver->getProviderByUrl(Argument::any())->shouldNotBeCalled();

    $validator = new OEmbedResourceConstraintValidator(
      $url_resolver->reveal(),
      $this->container->get('media.oembed.resource_fetcher'),
      $this->container->get('logger.factory')
    );
    $validator->initialize($context->reveal());
    $validator->validate($this->getValue($media)$constraint);
  }
Home | Imprint | This part of the site doesn't use cookies.