You are here

public function TwigSandboxTest::testEntitySafeMethods in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php \Drupal\Tests\Core\Template\TwigSandboxTest::testEntitySafeMethods()
  2. 10 core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php \Drupal\Tests\Core\Template\TwigSandboxTest::testEntitySafeMethods()

Tests that valid methods can be called from within Twig templates.

Currently the following methods are whitelisted: id, label, bundle, and get.

File

core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php, line 113
Contains \Drupal\Tests\Core\Template\TwigSandboxTest.

Class

TwigSandboxTest
Tests the twig sandbox policy.

Namespace

Drupal\Tests\Core\Template

Code

public function testEntitySafeMethods() {
  $entity = $this
    ->getMockBuilder('Drupal\\Core\\Entity\\ContentEntityBase')
    ->disableOriginalConstructor()
    ->getMock();
  $entity
    ->expects($this
    ->atLeastOnce())
    ->method('get')
    ->with('title')
    ->willReturn('test');
  $result = $this->twig
    ->render('{{ entity.get("title") }}', [
    'entity' => $entity,
  ]);
  $this
    ->assertEquals('test', $result, 'Sandbox policy allows get() to be called.');
  $entity = $this
    ->createMock('Drupal\\Core\\Entity\\EntityInterface');
  $entity
    ->expects($this
    ->atLeastOnce())
    ->method('id')
    ->willReturn('1234');
  $result = $this->twig
    ->render('{{ entity.id }}', [
    'entity' => $entity,
  ]);
  $this
    ->assertEquals('1234', $result, 'Sandbox policy allows get() to be called.');
  $entity = $this
    ->createMock('Drupal\\Core\\Entity\\EntityInterface');
  $entity
    ->expects($this
    ->atLeastOnce())
    ->method('label')
    ->willReturn('testing');
  $result = $this->twig
    ->render('{{ entity.label }}', [
    'entity' => $entity,
  ]);
  $this
    ->assertEquals('testing', $result, 'Sandbox policy allows get() to be called.');
  $entity = $this
    ->createMock('Drupal\\Core\\Entity\\EntityInterface');
  $entity
    ->expects($this
    ->atLeastOnce())
    ->method('bundle')
    ->willReturn('testing');
  $result = $this->twig
    ->render('{{ entity.bundle }}', [
    'entity' => $entity,
  ]);
  $this
    ->assertEquals('testing', $result, 'Sandbox policy allows get() to be called.');
}