Commit 32742836 authored by alexpott's avatar alexpott
Browse files

Issue #1895018 by Berdir, danylevskyi, ceardach, alexpott: Convert token API...

Issue #1895018 by Berdir, danylevskyi, ceardach, alexpott: Convert token API and node token tests to DrupalUnitTestBase.
parent 1ec781db
......@@ -7,12 +7,24 @@
namespace Drupal\node\Tests;
use Drupal\Core\Language\Language;
use Drupal\system\Tests\System\TokenReplaceUnitTestBase;
use Drupal\Component\Utility\String;
/**
* Test node token replacement in strings.
*/
class NodeTokenReplaceTest extends NodeTestBase {
class NodeTokenReplaceTest extends TokenReplaceUnitTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('node', 'filter');
/**
* {@inheritdoc}
*/
public static function getInfo() {
return array(
'name' => 'Node token replacement',
......@@ -21,30 +33,39 @@ public static function getInfo() {
);
}
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->installSchema('node', array('node', 'node_field_revision', 'node_field_data', 'node_revision'));
$this->installConfig(array('filter'));
$node_type = entity_create('node_type', array('type' => 'article', 'name' => 'Article'));
$node_type->save();
node_add_body_field($node_type);
}
/**
* Creates a node, then tests the tokens generated from it.
*/
function testNodeTokenReplacement() {
$token_service = \Drupal::token();
$language_interface = language(Language::TYPE_INTERFACE);
$url_options = array(
'absolute' => TRUE,
'language' => $language_interface,
'language' => $this->languageInterface,
);
// Create a user and a node.
$account = $this->drupalCreateUser();
$settings = array(
$account = $this->createUser();
/* @var $node \Drupal\node\NodeInterface */
$node = entity_create('node', array(
'type' => 'article',
'tnid' => 0,
'uid' => $account->id(),
'title' => '<blink>Blinking Text</blink>',
'body' => array(array('value' => $this->randomName(32), 'summary' => $this->randomName(16))),
);
$node = $this->drupalCreateNode($settings);
// Load node so that the body and summary fields are structured properly.
$node = node_load($node->id());
$instance = field_info_instance('node', 'body', $node->getType());
'body' => array(array('value' => $this->randomName(32), 'summary' => $this->randomName(16), 'format' => 'plain_text')),
));
$node->save();
// Generate and test sanitized tokens.
$tests = array();
......@@ -58,41 +79,40 @@ function testNodeTokenReplacement() {
$tests['[node:langcode]'] = check_plain($node->language()->id);
$tests['[node:url]'] = url('node/' . $node->id(), $url_options);
$tests['[node:edit-url]'] = url('node/' . $node->id() . '/edit', $url_options);
$tests['[node:author]'] = check_plain(user_format_name($account));
$tests['[node:author]'] = String::checkPlain($account->getUsername());
$tests['[node:author:uid]'] = $node->getOwnerId();
$tests['[node:author:name]'] = check_plain(user_format_name($account));
$tests['[node:created:since]'] = format_interval(REQUEST_TIME - $node->getCreatedTime(), 2, $language_interface->id);
$tests['[node:changed:since]'] = format_interval(REQUEST_TIME - $node->getChangedTime(), 2, $language_interface->id);
$tests['[node:author:name]'] = String::checkPlain($account->getUsername());
$tests['[node:created:since]'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $node->getCreatedTime(), 2, $this->languageInterface->id);
$tests['[node:changed:since]'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $node->getChangedTime(), 2, $this->languageInterface->id);
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('node' => $node), array('langcode' => $language_interface->id));
$output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->languageInterface->id));
$this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input)));
}
// Generate and test unsanitized tokens.
$tests['[node:title]'] = $node->getTitle();
$tests['[node:title]'] = $node->label();
$tests['[node:body]'] = $node->body->value;
$tests['[node:summary]'] = $node->body->summary;
$tests['[node:langcode]'] = $node->language()->id;
$tests['[node:author:name]'] = user_format_name($account);
$tests['[node:author:name]'] = $account->getUsername();
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('node' => $node), array('langcode' => $language_interface->id, 'sanitize' => FALSE));
$output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->languageInterface->id, 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced.', array('%token' => $input)));
}
// Repeat for a node without a summary.
$settings['body'] = array(array('value' => $this->randomName(32), 'summary' => ''));
$node = $this->drupalCreateNode($settings);
// Load node (without summary) so that the body and summary fields are
// structured properly.
$node = node_load($node->id());
$instance = field_info_instance('node', 'body', $node->getType());
$node = entity_create('node', array(
'type' => 'article',
'uid' => $account->id(),
'title' => '<blink>Blinking Text</blink>',
'body' => array(array('value' => $this->randomName(32), 'format' => 'plain_text')),
));
$node->save();
// Generate and test sanitized token - use full body as expected value.
$tests = array();
......@@ -102,7 +122,7 @@ function testNodeTokenReplacement() {
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated for node without a summary.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('node' => $node), array('language' => $language_interface));
$output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->languageInterface));
$this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced for node without a summary.', array('%token' => $input)));
}
......@@ -110,8 +130,9 @@ function testNodeTokenReplacement() {
$tests['[node:summary]'] = $node->body->value;
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('node' => $node), array('language' => $language_interface, 'sanitize' => FALSE));
$output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->languageInterface, 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced for node without a summary.', array('%token' => $input)));
}
}
}
......@@ -2,85 +2,31 @@
/**
* @file
* Definition of Drupal\system\Tests\System\TokenReplaceTest.
* Contains \Drupal\system\Tests\System\TokenReplaceUnitTest.
*/
namespace Drupal\system\Tests\System;
use Drupal\Core\Language\Language;
use Drupal\simpletest\WebTestBase;
use Drupal\Component\Utility\String;
use Drupal\Component\Utility\Xss;
/**
* Test token replacement in strings.
*/
class TokenReplaceTest extends WebTestBase {
class TokenReplaceUnitTest extends TokenReplaceUnitTestBase {
public static function getInfo() {
return array(
'name' => 'Token replacement',
'name' => 'Token replacement unit test',
'description' => 'Generates text using placeholders for dummy content to check token replacement.',
'group' => 'System',
);
}
/**
* Creates a user and a node, then tests the tokens generated from them.
*/
function testTokenReplacement() {
$token_service = \Drupal::token();
// Create the initial objects.
$account = $this->drupalCreateUser();
$node = $this->drupalCreateNode(array('uid' => $account->id()));
$node->title = '<blink>Blinking Text</blink>';
global $user;
$language_interface = language(Language::TYPE_INTERFACE);
$source = '[node:title]'; // Title of the node we passed in
$source .= '[node:author:name]'; // Node author's name
$source .= '[node:created:since]'; // Time since the node was created
$source .= '[current-user:name]'; // Current user's name
$source .= '[date:short]'; // Short date format of REQUEST_TIME
$source .= '[user:name]'; // No user passed in, should be untouched
$source .= '[bogus:token]'; // Non-existent token
$target = check_plain($node->getTitle());
$target .= check_plain($account->getUsername());
$target .= format_interval(REQUEST_TIME - $node->getCreatedTime(), 2, $language_interface->id);
$target .= check_plain($user->getUsername());
$target .= format_date(REQUEST_TIME, 'short', '', NULL, $language_interface->id);
// Test that the clear parameter cleans out non-existent tokens.
$result = $token_service->replace($source, array('node' => $node), array('langcode' => $language_interface->id, 'clear' => TRUE));
$this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');
// Test without using the clear parameter (non-existent token untouched).
$target .= '[user:name]';
$target .= '[bogus:token]';
$result = $token_service->replace($source, array('node' => $node), array('langcode' => $language_interface->id));
$this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
// Check that the results of Token::generate are sanitized properly. This
// does NOT test the cleanliness of every token -- just that the $sanitize
// flag is being passed properly through the call stack and being handled
// correctly by a 'known' token, [node:title].
$raw_tokens = array('title' => '[node:title]');
$generated = $token_service->generate('node', $raw_tokens, array('node' => $node));
$this->assertEqual($generated['[node:title]'], check_plain($node->getTitle()), 'Token sanitized.');
$generated = $token_service->generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE));
$this->assertEqual($generated['[node:title]'], $node->getTitle(), 'Unsanitized token generated properly.');
// Test token replacement when the string contains no tokens.
$this->assertEqual($token_service->replace('No tokens here.'), 'No tokens here.');
}
/**
* Test whether token-replacement works in various contexts.
*/
function testSystemTokenRecognition() {
$token_service = \Drupal::token();
$language_interface = language(Language::TYPE_INTERFACE);
public function testSystemTokenRecognition() {
// Generate prefixes and suffixes for the token context.
$tests = array(
array('prefix' => 'this is the ', 'suffix' => ' site'),
......@@ -99,33 +45,64 @@ function testSystemTokenRecognition() {
foreach ($tests as $test) {
$input = $test['prefix'] . '[site:name]' . $test['suffix'];
$expected = $test['prefix'] . 'Drupal' . $test['suffix'];
$output = $token_service->replace($input, array(), array('langcode' => $language_interface->id));
$output = $this->tokenService->replace($input, array(), array('langcode' => $this->languageInterface->id));
$this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
}
// Test token replacement when the string contains no tokens.
$this->assertEqual($this->tokenService->replace('No tokens here.'), 'No tokens here.');
}
/**
* Tests the clear parameter.
*/
public function testClear() {
// Valid token.
$source = '[site:name]';
// No user passed in, should be untouched.
$source .= '[user:name]';
// Non-existing token.
$source .= '[bogus:token]';
// Replace with with the clear parameter, only the valid token should remain.
$target = String::checkPlain(config('system.site')->get('name'));
$result = $this->tokenService->replace($source, array(), array('langcode' => $this->languageInterface->id, 'clear' => TRUE));
$this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
$target .= '[user:name]';
$target .= '[bogus:token]';
$result = $this->tokenService->replace($source, array(), array('langcode' => $this->languageInterface->id));
$this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
}
/**
* Tests the generation of all system site information tokens.
*/
function testSystemSiteTokenReplacement() {
$token_service = \Drupal::token();
$language_interface = language(Language::TYPE_INTERFACE);
public function testSystemSiteTokenReplacement() {
// The use of the url() function requires the url_alias table to exist.
$this->installSchema('system', 'url_alias');
$url_options = array(
'absolute' => TRUE,
'language' => $language_interface,
'language' => $this->languageInterface,
);
$slogan = '<blink>Slogan</blink>';
$safe_slogan = Xss::filterAdmin($slogan);
// Set a few site variables.
\Drupal::config('system.site')
$config = $this->container->get('config.factory')->get('system.site');
$config
->set('name', '<strong>Drupal<strong>')
->set('slogan', '<blink>Slogan</blink>')
->set('slogan', $slogan)
->set('mail', 'simpletest@example.com')
->save();
// Generate and test sanitized tokens.
$tests = array();
$tests['[site:name]'] = check_plain(\Drupal::config('system.site')->get('name'));
$tests['[site:slogan]'] = filter_xss_admin(\Drupal::config('system.site')->get('slogan'));
$tests['[site:mail]'] = 'simpletest@example.com';
$tests['[site:name]'] = String::checkPlain($config->get('name'));
$tests['[site:slogan]'] = $safe_slogan;
$tests['[site:mail]'] = $config->get('mail');
$tests['[site:url]'] = url('<front>', $url_options);
$tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
$tests['[site:login-url]'] = url('user', $url_options);
......@@ -134,44 +111,53 @@ function testSystemSiteTokenReplacement() {
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array(), array('langcode' => $language_interface->id));
$output = $this->tokenService->replace($input, array(), array('langcode' => $this->languageInterface->id));
$this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
}
// Generate and test unsanitized tokens.
$tests['[site:name]'] = \Drupal::config('system.site')->get('name');
$tests['[site:slogan]'] = \Drupal::config('system.site')->get('slogan');
$tests['[site:name]'] = $config->get('name');
$tests['[site:slogan]'] = $config->get('slogan');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array(), array('langcode' => $language_interface->id, 'sanitize' => FALSE));
$output = $this->tokenService->replace($input, array(), array('langcode' => $this->languageInterface->id, 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
}
// Check that the results of Token::generate are sanitized properly. This
// does NOT test the cleanliness of every token -- just that the $sanitize
// flag is being passed properly through the call stack and being handled
// correctly by a 'known' token, [site:slogan].
$raw_tokens = array('slogan' => '[site:slogan]');
$generated = $this->tokenService->generate('site', $raw_tokens);
$this->assertEqual($generated['[site:slogan]'], $safe_slogan, 'Token sanitized.');
$generated = $this->tokenService->generate('site', $raw_tokens, array(), array('sanitize' => FALSE));
$this->assertEqual($generated['[site:slogan]'], $slogan, 'Unsanitized token generated properly.');
}
/**
* Tests the generation of all system date tokens.
*/
function testSystemDateTokenReplacement() {
$token_service = \Drupal::token();
$language_interface = language(Language::TYPE_INTERFACE);
public function testSystemDateTokenReplacement() {
// Set time to one hour before request.
$date = REQUEST_TIME - 3600;
// Generate and test tokens.
$tests = array();
$tests['[date:short]'] = format_date($date, 'short', '', NULL, $language_interface->id);
$tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language_interface->id);
$tests['[date:long]'] = format_date($date, 'long', '', NULL, $language_interface->id);
$tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language_interface->id);
$tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language_interface->id);
$tests['[date:raw]'] = filter_xss($date);
$date_service = \Drupal::service('date');
$tests['[date:short]'] = $date_service->format($date, 'short', '', NULL, $this->languageInterface->id);
$tests['[date:medium]'] = $date_service->format($date, 'medium', '', NULL, $this->languageInterface->id);
$tests['[date:long]'] = $date_service->format($date, 'long', '', NULL, $this->languageInterface->id);
$tests['[date:custom:m/j/Y]'] = $date_service->format($date, 'custom', 'm/j/Y', NULL, $this->languageInterface->id);
$tests['[date:since]'] = $date_service->formatInterval(REQUEST_TIME - $date, 2, $this->languageInterface->id);
$tests['[date:raw]'] = Xss::filter($date);
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('date' => $date), array('langcode' => $language_interface->id));
$output = $this->tokenService->replace($input, array('date' => $date), array('langcode' => $this->languageInterface->id));
$this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
}
}
......
<?php
/**
* @file
* Contains \Drupal\system\Tests\System\TokenReplaceUnitTestBase.
*/
namespace Drupal\system\Tests\System;
use Drupal\Core\Language\Language;
use Drupal\system\Tests\Entity\EntityUnitTestBase;
/**
* Test token replacement in strings.
*/
class TokenReplaceUnitTestBase extends EntityUnitTestBase {
/**
* The interface language.
*
* @var \Drupal\Core\Language\Language
*/
protected $languageInterface;
/**
* Token service.
*
* @var \Drupal\Core\Utility\Token
*/
protected $tokenService;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system');
public function setUp() {
parent::setUp();
// Install default system configuration.
$this->installConfig(array('system'));
$this->languageInterface = \Drupal::languageManager()->getCurrentLanguage();
$this->tokenService = \Drupal::token();
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment