setRawContent example

// Create the base element that we'll use in the tests below.     $path = $this->randomMachineName();
    $base_element = [
      '#theme' => 'image_formatter',
      '#image_style' => 'test',
      '#item' => $entity->image_test,
      '#url' => Url::fromUri('base:' . $path),
    ];

    // Test using theme_image_formatter() with a NULL value for the alt option.     $element = $base_element;
    $this->setRawContent($renderer->renderRoot($element));
    $elements = $this->xpath('//a[@href=:path]/img[@src=:url and @width=:width and @height=:height]', [':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()]);
    $this->assertCount(1, $elements, 'theme_image_formatter() correctly renders with a NULL value for the alt option.');

    // Test using theme_image_formatter() without an image title, alt text, or     // link options.     $element = $base_element;
    $element['#item']->alt = '';
    $this->setRawContent($renderer->renderRoot($element));
    $elements = $this->xpath('//a[@href=:path]/img[@src=:url and @width=:width and @height=:height and @alt=""]', [':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()]);
    $this->assertCount(1, $elements, 'theme_image_formatter() correctly renders without title, alt, or path options.');

    
public function testMissingEntityIndicator($uuid, array $filter_ids, array $additional_attributes) {
    $content = $this->createEmbedCode([
      'data-entity-type' => 'media',
      'data-entity-uuid' => $uuid,
      'data-view-mode' => 'foobar',
    ] + $additional_attributes);

    // If the UUID being used in the embed is that of the sample entity, first     // assert that it currently results in a functional embed, then delete it.     if ($uuid === static::EMBEDDED_ENTITY_UUID) {
      $result = $this->processText($content, 'en', $filter_ids);
      $this->setRawContent($result->getProcessedText());
      $this->assertCount(1, $this->cssSelect('div[data-media-embed-test-view-mode="foobar"]'));
      $this->embeddedEntity->delete();
    }
    $result = $this->processText($content, 'en', $filter_ids);
    $this->setRawContent($result->getProcessedText());
    $this->assertCount(0, $this->cssSelect('div[data-media-embed-test-view-mode="foobar"]'));
    $this->assertCount(1, $this->cssSelect('div.this-error-message-is-themeable'));
    if (in_array('filter_align', $filter_ids, TRUE) && !empty($additional_attributes['data-align'])) {
      $this->assertCount(1, $this->cssSelect('div.align-' . $additional_attributes['data-align']));
    }

  }
$route = $route_provider->getRouteByName('entity.entity_test_mul.delete_form');
    $this->assertEquals('entity_test_mul.delete', $route->getDefault('_entity_form'));
    $this->assertEquals('\Drupal\Core\Entity\Controller\EntityController::deleteTitle', $route->getDefault('_title_callback'));
    $this->assertEquals('entity_test_mul.delete', $route->getRequirement('_entity_access'));
    $this->assertFalse($route->hasOption('_admin_route'));

    $entity = EntityTestMul::create([
      'name' => 'Test title',
    ]);
    $entity->save();

    $this->setRawContent($this->httpKernelHandle($entity->toUrl()->toString()));
    $this->assertTitle('Test title | ');

    $this->setRawContent($this->httpKernelHandle($entity->toUrl('edit-form')->toString()));
    $this->assertTitle('Edit Test title | ');

    $this->setRawContent($this->httpKernelHandle($entity->toUrl('delete-form')->toString()));
    $this->assertTitle('Are you sure you want to delete the test entity - data table Test title? | ');
  }

  /** * @covers \Drupal\Core\Entity\Routing\AdminHtmlRouteProvider::getEditFormRoute * @covers \Drupal\Core\Entity\Routing\AdminHtmlRouteProvider::getDeleteFormRoute */

  public function validateForm(array &$form, FormStateInterface $form_state) {}

  /** * Tests that values are returned. */
  public function testTextFormatElement() {
    /** @var \Drupal\Core\Form\FormBuilder $form_builder */
    $form_builder = $this->container->get('form_builder');
    $form = $form_builder->getForm($this);
    $output = $this->render($form);
    $this->setRawContent($output);
    $this->assertFieldByName('textformat[value]');
    $this->assertRaw('<h4>Full HTML</h4>');
    $this->assertRaw('<h4>Filtered HTML</h4>');
    $this->assertRaw('<h4>Test format</h4>');
    $this->assertNoPattern('|<h4[^>]*></h4>|', 'No empty H4 element found.');
  }

}


  /** * Tests block view altering. * * @see hook_block_view_alter() * @see hook_block_view_BASE_BLOCK_ID_alter() */
  public function testBlockViewBuilderViewAlter() {
    // Establish baseline.     $build = $this->getBlockRenderArray();
    $this->setRawContent((string) $this->renderer->renderRoot($build));
    $this->assertSame('Llamas > unicorns!', trim((string) $this->cssSelect('div')[0]));

    // Enable the block view alter hook that adds a foo=bar attribute.     \Drupal::state()->set('block_test_view_alter_suffix', TRUE);
    Cache::invalidateTags($this->block->getCacheTagsToInvalidate());
    $build = $this->getBlockRenderArray();
    $this->setRawContent((string) $this->renderer->renderRoot($build));
    $this->assertSame('Llamas > unicorns!', trim((string) $this->cssSelect('[foo=bar]')[0]));
    \Drupal::state()->set('block_test_view_alter_suffix', FALSE);

    \Drupal::state()->set('block_test.content', NULL);
    
$user3->setLastAccessTime($inactive_time);
    $user3->save();

    // Test block output.     \Drupal::currentUser()->setAccount($user1);

    // Test the rendering of a block.     $entity = Block::load('views_block__who_s_online_who_s_online_block');
    $output = \Drupal::entityTypeManager()
      ->getViewBuilder($entity->getEntityTypeId())
      ->view($entity, 'block');
    $this->setRawContent($this->renderer->renderRoot($output));
    $this->assertRaw('2 users', 'Correct number of online users (2 users).');
    $this->assertText($user1->getAccountName(), 'Active user 1 found in online list.');
    $this->assertText($user2->getAccountName(), 'Active user 2 found in online list.');
    $this->assertNoText($user3->getAccountName(), 'Inactive user not found in online list.');
    // Verify that online users are ordered correctly.     $this->assertGreaterThan(strpos($this->getRawContent()$user2->getAccountName())strpos($this->getRawContent()$user1->getAccountName()));
  }

}
/** @var \Drupal\entity_test\EntityTestViewBuilder $view_builder */
    $view_builder = $this->container->get('entity_type.manager')->getViewBuilder('entity_test');

    /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
    $storage = $this->container->get('entity_type.manager')->getStorage('entity_test');
    $storage->resetCache();
    $entities = $storage->loadMultiple($entity_ids);

    $build = $view_builder->viewMultiple($entities);

    $output = $renderer->renderRoot($build);
    $this->setRawContent($output->__toString());
    // Confirm that the content added in     // entity_test_entity_display_build_alter() appears multiple times, not     // just for the final entity.     foreach ($entity_ids as $id) {
      $this->assertText('Content added in hook_entity_display_build_alter for entity id ' . $id);
    }
  }

}
/** * Tests rendering the entity area handler. * * @param \Drupal\Core\Entity\EntityInterface[] $entities * The entities. */
  public function doTestRender($entities) {
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');
    $view = Views::getView('test_entity_area');
    $preview = $view->preview('default', [$entities[1]->id()]);
    $this->setRawContent(\Drupal::service('renderer')->renderRoot($preview));
    $view_class = 'js-view-dom-id-' . $view->dom_id;
    $header_xpath = '//div[@class = "' . $view_class . '"]/header[1]';
    $footer_xpath = '//div[@class = "' . $view_class . '"]/footer[1]';

    $result = $this->xpath($header_xpath);
    $this->assertStringContainsString($entities[0]->label()(string) $result[0], 'The rendered entity appears in the header of the view.');
    $this->assertStringContainsString('full', (string) $result[0], 'The rendered entity appeared in the right view mode.');

    $result = $this->xpath($footer_xpath);
    $this->assertStringContainsString($entities[1]->label()(string) $result[0], 'The rendered entity appears in the footer of the view.');
    $this->assertStringContainsString('full', (string) $result[0], 'The rendered entity appeared in the right view mode.');

    

  protected function assertGrid(ViewExecutable $view, string $alignment, int $columns): void {
    $view->setDisplay('default');
    $view->initStyle();
    $view->initHandlers();
    $view->initQuery();
    $view->style_plugin->options['alignment'] = $alignment;
    $view->style_plugin->options['columns'] = $columns;
    $this->executeView($view);
    $output = $view->preview();
    $output = \Drupal::service('renderer')->renderRoot($output);
    $this->setRawContent($output);
    if (!in_array($alignment$this->alignmentsTested)) {
      $result = $this->xpath('//div[contains(@class, "views-view-grid") and contains(@class, :alignment) and contains(@class, :columns)]', [':alignment' => $alignment, ':columns' => 'cols-' . $columns]);
      $this->assertGreaterThan(0, count($result)ucfirst($alignment) . " grid markup detected.");
      $this->alignmentsTested[] = $alignment;
    }
    $width = '0';
    switch ($columns) {
      case 5: $width = '20';
        break;

      case 4: $width = '25';
        
    $settings = [
      // cSpell:disable-next-line       'body' => [['value' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vitae arcu at leo cursus laoreet. Curabitur dui tortor, adipiscing malesuada tempor in, bibendum ac diam. Cras non tellus a libero pellentesque condimentum. What is a Drupalism? Suspendisse ac lacus libero. Ut non est vel nisl faucibus interdum nec sed leo. Pellentesque sem risus, vulputate eu semper eget, auctor in libero. Ut fermentum est vitae metus convallis scelerisque. Phasellus pellentesque rhoncus tellus, eu dignissim purus posuere id. Quisque eu fringilla ligula. Morbi ullamcorper, lorem et mattis egestas, tortor neque pretium velit, eget eleifend odio turpis eu purus. Donec vitae metus quis leo pretium tincidunt a pulvinar sem. Morbi adipiscing laoreet mauris vel placerat. Nullam elementum, nisl sit amet scelerisque malesuada, dolor nunc hendrerit quam, eu ultrices erat est in orci. Curabitur feugiat egestas nisl sed accumsan.']],
      'promote' => 1,
    ];
    $node = $this->drupalCreateNode($settings);
    $this->assertNotEmpty(Node::load($node->id()), 'Node created.');

    // Render the node as a teaser.     $content = $this->drupalBuildEntityView($node, 'teaser');
    $this->assertLessThan(600, strlen($content['body'][0]['#markup']));
    $this->setRawContent($renderer->renderRoot($content));
    // The string 'What is a Drupalism?' is between the 200th and 600th     // characters of the node body, so it should be included if the summary is     // 600 characters long.     $expected = 'What is a Drupalism?';
    $this->assertRaw($expected);

    // Change the teaser length for "Basic page" content type.     $display = \Drupal::service('entity_display.repository')
      ->getViewDisplay('node', $node->getType(), 'teaser');
    $display_options = $display->getComponent('body');
    $display_options['settings']['trim_length'] = 200;
    
'label' => 'visually_hidden',
      'settings' => [],
    ])->save();

    $entity = EntityTestRev::create([]);
    $entity->{$this->fieldName}->value = $value;
    $entity->save();

    $build = $this->display->build($entity);
    $renderer = \Drupal::service('renderer');
    $content = $renderer->renderPlain($build);
    $this->setRawContent((string) $content);

    $css_selector_converter = new CssSelectorConverter();
    $elements = $this->xpath($css_selector_converter->toXPath('.visually-hidden'));
    $this->assertCount(1, $elements$content);
  }

}

  public function testViewsFormMainFormPreRender() {
    $element = [
      'output' => [
        '#plain_text' => '<!--will-be-escaped--><!--will-be-not-escaped-->',
      ],
      '#substitutions' => ['#value' => []],
    ];
    $element = \Drupal::service('renderer')->executeInRenderContext(new RenderContext()function D) use ($element) {
      return ViewsFormMainForm::preRenderViewsForm($element);
    });
    $this->setRawContent((string) $element['output']['#markup']);
    $this->assertEscaped('<em>escaped</em>');
    $this->assertRaw('<em>unescaped</em>');
  }

  /** * Test that hook_views_invalidate_cache() is called when a view is deleted. */
  public function testViewsInvalidateCacheOnDelete() {
    $this->container->get('state')->set('views_hook_test_views_invalidate_cache', FALSE);
    $view = $this->viewStorage->load('test_view');
    $view->delete();
    
/** * Tests how hook_link_alter() can affect escaping of the link text. */
  public function testHookLinkAlter() {
    $url = Url::fromUri('http://example.com');
    $renderer = \Drupal::service('renderer');

    $link = $renderer->executeInRenderContext(new RenderContext()function D) use ($url) {
      return \Drupal::service('link_generator')->generate(['#markup' => '<em>link with markup</em>']$url);
    });
    $this->setRawContent($link);
    $this->assertInstanceOf(MarkupInterface::class$link);
    // Ensure the content of the link is not escaped.     $this->assertRaw('<em>link with markup</em>');

    // Test just adding text to an already safe string.     \Drupal::state()->set('link_generation_test_link_alter', TRUE);
    $link = $renderer->executeInRenderContext(new RenderContext()function D) use ($url) {
      return \Drupal::service('link_generator')->generate(['#markup' => '<em>link with markup</em>']$url);
    });
    $this->setRawContent($link);
    $this->assertInstanceOf(MarkupInterface::class$link);
    
\Drupal::request()->query->set('page', 0);
    $entities[1]->name->value = $random_name = $this->randomMachineName();
    $entities[1]->save();
    $build = $this->assertViewsCacheTags($view$tags_page_1$do_assert_views_caches$tags_page_1);
    $this->assertViewsCacheTagsFromStaticRenderArray($view$tags_page_1$do_assert_views_caches);
    $this->assertStringContainsString($random_name(string) $build['#markup']);
    $view->destroy();

    // Setup arguments to ensure that render caching also varies by them.     // Custom assert for a single result row.     $single_entity_assertions = function Darray $build, EntityInterface $entity) {
      $this->setRawContent($build['#markup']);

      $result = $this->cssSelect('div.views-row');
      $count = count($result);
      $this->assertEquals(1, $count);

      $this->assertEquals((string) $entity->id()(string) $result[0]->div->span);
    };

    // Execute the view once with a static renderable and one with a full     // prepared render array.     $tags_argument = Cache::mergeTags($base_tags$entities[0]->getCacheTags());
    
$comment = $this->comments[0];
    $comment_anonymous = $this->comments[1];
    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $account_switcher->switchTo($this->adminUser);
    $executable = Views::getView('comment');
    $build = $executable->preview($display_id);
    $this->setRawContent($renderer->renderRoot($build));

    // Assert the exposed filters on the admin page.     $this->assertField('subject');
    $this->assertField('author_name');
    $this->assertField('langcode');

    $elements = $this->cssSelect('input[type="checkbox"]');
    $this->assertCount(2, $elements, 'There are two comments on the page.');
    $this->assertText($comment->label());
    $this->assertText($comment_anonymous->label());
    $executable->destroy();

    
Home | Imprint | This part of the site doesn't use cookies.