assertRaw example

return $b['nid'] - $a['nid'];
      });
      $view = Views::getView('frontpage');
      $view->execute();
      $this->assertIdenticalResultset($view$expected_frontpage['nid' => 'nid']);

      $rendered_view = $view->render('page_1');
      $output = \Drupal::service('renderer')->renderRoot($rendered_view);
      $this->setRawContent($output);
      foreach ($expected_values as $expected_entity_values) {
        if ($expected_entity_values[$entity_keys['published']] === TRUE && $expected_entity_values['default_revision'] === TRUE) {
          $this->assertRaw($expected_entity_values[$entity_keys['label']]);
        }
        // Node 4 will always appear in the 'stage' workspace because it has         // both an unpublished revision as well as a published one.         elseif ($workspace_id != 'stage' && $expected_entity_values[$entity_keys['id']] != 4) {
          $this->assertNoRaw($expected_entity_values[$entity_keys['label']]);
        }
      }

      // Add a filter on a field that is stored in a dedicated table in order to       // test field joins with extra conditions (e.g. 'deleted' and 'langcode').       $view->destroy();
      
$expected = \Drupal::service('date.formatter')->format($value$date_format$custom_date_format$timezone);

      $component = $this->display->getComponent($this->fieldName);
      $component['type'] = 'timestamp';
      $component['settings'] = $settings;
      $this->display->setComponent($this->fieldName, $component);

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

      $this->renderEntityFields($entity$this->display);
      $this->assertRaw($expected);
    }
  }

  /** * Tests TimestampAgoFormatter. */
  public function testTimestampAgoFormatter() {
    $data = [];

    foreach ([1, 2, 3, 4, 5, 6] as $granularity) {
      $data[] = [
        
$request_stack->push($request);

    $form = \Drupal::formBuilder()->getForm($this);
    $markup = \Drupal::service('renderer')->renderRoot($form);
    $this->setRawContent($markup);

    $elements = $this->xpath('//form');
    $action = isset($elements[0]['action']) ? (string) $elements[0]['action'] : FALSE;
    $injected = isset($elements[0]['injected']) ? (string) $elements[0]['injected'] : FALSE;

    $this->assertSame('/test/"injected=\'attribute\'close="', $action);
    $this->assertRaw('action="/test/"injected='attribute'close=""');
    $this->assertNotSame('attribute', $injected);
  }

}
public function testMessages() {
    // Enable the Starterkit theme.     \Drupal::service('theme_installer')->install(['starterkit_theme']);
    $this->config('system.theme')->set('default', 'starterkit_theme')->save();

    \Drupal::messenger()->addError('An error occurred');
    \Drupal::messenger()->addStatus('But then something nice happened');
    $messages = [
      '#type' => 'status_messages',
    ];
    $this->render($messages);
    $this->assertRaw('messages messages--error');
    $this->assertRaw('messages messages--status');
    // Tests display of only one type of messages.     \Drupal::messenger()->addError('An error occurred');
    $messages = [
      '#type' => 'status_messages',
      '#display' => 'error',
    ];
    $this->render($messages);
    $this->assertRaw('messages messages--error');
  }

}

  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);
    // Ensure the content of the link is escaped.     $this->assertEscaped('<em>link with markup</em> <strong>Test!</strong>');

    
$request->setFormat('html', ['text/html']);

    /** @var \Symfony\Component\HttpKernel\HttpKernelInterface $kernel */
    $kernel = \Drupal::getContainer()->get('http_kernel');
    $response = $kernel->handle($request)->prepare($request);
    $this->assertEquals(Response::HTTP_INTERNAL_SERVER_ERROR, $response->getStatusCode());
    $this->assertEquals('text/html; charset=UTF-8', $response->headers->get('Content-type'));

    // Test message is properly escaped, and that the unescaped string is not     // output at all.     $this->setRawContent($response->getContent());
    $this->assertRaw(Html::escape('Escaped content: <p> <br> <h3>'));
    $this->assertNoRaw('<p> <br> <h3>');

    $string = '<script>alert(123);</script>';
    $request = Request::create('/router_test/test2?_format=json' . urlencode($string), 'GET');

    $kernel = \Drupal::getContainer()->get('http_kernel');
    $response = $kernel->handle($request)->prepare($request);
    // As the Content-type is text/plain the fact that the raw string is     // contained in the output would not matter, but because it is output by the     // final exception subscriber, it is printed as partial HTML, and hence     // escaped.
'relationship' => 'none',
        'operator' => '=',
        'value' => 'non-existing-name',
      ],
    ]);

    $this->executeView($view);
    $output = $view->render();
    $output = \Drupal::service('renderer')->renderRoot($output);
    $this->setRawContent($output);
    $this->assertText('start: 0 | end: 0 | total: 0 | label: test_area_result | per page: 0 | current page: 1 | current record count: 0 | page count: 1');
    $this->assertRaw('<header>');

    // Test that the area is not displayed if we have not checked the empty     // checkbox.     $view->setDisplay('page_1');

    $this->executeView($view);
    $output = $view->render();
    $output = \Drupal::service('renderer')->renderRoot($output);
    $this->setRawContent($output);
    $this->assertNoText('start: 0 | end: 0 | total: 0 | label: test_area_result | per page: 0 | current page: 1 | current record count: 0 | page count: 1');
    // Make sure the empty header region isn't rendered.
'label' => 'above',
      'type' => 'field_test_default',
      'settings' => [
        'test_formatter_setting' => $formatter_setting_2,
      ],
    ];
    $display->setComponent($this->fieldTestData->field_name_2, $display_options_2);

    // View all fields.     $content = $display->build($entity);
    $this->render($content);
    $this->assertRaw($this->fieldTestData->field->getLabel(), "First field's label is displayed.");
    foreach ($values as $delta => $value) {
      $this->assertRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
    }
    $this->assertRaw($this->fieldTestData->field_2->getLabel(), "Second field's label is displayed.");
    foreach ($values_2 as $delta => $value) {
      $this->assertRaw("$formatter_setting_2|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
    }

    // Label hidden.     $entity = clone($entity_init);
    $display_options['label'] = 'hidden';
    
public function testStringFormatter() {
    $value = $this->randomString();
    $value .= "\n\n<strong>" . $this->randomString() . '</strong>';
    $value .= "\n\n" . $this->randomString();

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

    // Verify that all HTML is escaped and newlines are retained.     $this->renderEntityFields($entity$this->display);
    $this->assertNoRaw($value);
    $this->assertRaw(nl2br(Html::escape($value)));

    // Verify the cache tags.     $build = $entity->{$this->fieldName}->view();
    $this->assertTrue(!isset($build[0]['#cache']), 'The string formatter has no cache tags.');

    $value = $this->randomMachineName();
    $entity->{$this->fieldName}->value = $value;
    $entity->save();

    // Set the formatter to link to the entity.     $this->display->setComponent($this->fieldName, [
      
$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;
    $display->setComponent('body', $display_options)
      ->save();

    // Render the node as a teaser again and check that the summary is now only     // 200 characters in length and so does not include 'What is a Drupalism?'.
    $display = [
      'label' => 'visually_hidden',
      'type' => 'field_test_multiple',
      'settings' => [
        'test_formatter_setting_multiple' => $this->randomMachineName(),
        'alter' => TRUE,
      ],
    ];
    $build = $items->view($display);
    $this->render($build);
    $setting = $display['settings']['test_formatter_setting_multiple'];
    $this->assertRaw('visually-hidden', 'Label was visually hidden.');
    $this->assertText('field_test_entity_display_build_alter', 'Alter fired, display passed.');
    $this->assertText('entity language is en', 'Language is placed onto the context.');
    $array = [];
    foreach ($this->values as $delta => $value) {
      $array[] = $delta . ':' . $value['value'];
    }
    $this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');

    // Check the prepare_view steps are invoked.     $display = [
      'label' => 'hidden',
      
/** * 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 the error message when failing to fetch data without dblog enabled. * * @see template_preprocess_update_fetch_error_message() */
  public function testTemplatePreprocessUpdateFetchErrorMessageNoDblog() {
    $build = [
      '#theme' => 'update_fetch_error_message',
    ];
    $this->render($build);
    $this->assertRaw('Failed to fetch available update data:<ul><li>See <a href="https://www.drupal.org/node/3170647">PHP OpenSSL requirements</a> in the Drupal.org handbook for possible reasons this could happen and what you can do to resolve them.</li><li>Check your local system logs for additional error messages.</li></ul>');

    \Drupal::moduleHandler()->loadInclude('update', 'inc', 'update.report');
    $variables = [];
    template_preprocess_update_fetch_error_message($variables);
    $this->assertArrayHasKey('error_message', $variables);
    $this->assertEquals('Failed to fetch available update data:', $variables['error_message']['message']['#markup']);
    $this->assertArrayHasKey('documentation_link', $variables['error_message']['items']['#items']);
    $this->assertArrayHasKey('logs', $variables['error_message']['items']['#items']);
    $this->assertArrayNotHasKey('dblog', $variables['error_message']['items']['#items']);
  }

  

        'expected' => '<div id="quotes-here"><span class="gray-like-a-bunny bem__ized--top-feature" id="quotes-here">ID and class. Having the same ID twice is not valid markup but we want to make sure the filter doesn\'t use \Drupal\Component\Utility\Html::getUniqueId().</span></div>',
        'message' => 'Class and ID filtered.',
      ],
      [
        'expected' => '<div><strong>Rendered author string length:</strong> 24.</div>',
        'message' => 'Render filter string\'s length.',
      ],
    ];

    foreach ($elements as $element) {
      $this->assertRaw($element['expected']$element['message']);
    }
  }

}
$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()));
  }

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