3 namespace Drupal\Tests\pathauto\Kernel;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Language\Language;
8 use Drupal\Core\Language\LanguageInterface;
9 use Drupal\language\Entity\ConfigurableLanguage;
10 use Drupal\field\Entity\FieldConfig;
11 use Drupal\field\Entity\FieldStorageConfig;
12 use Drupal\node\Entity\NodeType;
13 use Drupal\pathauto\PathautoGeneratorInterface;
14 use Drupal\pathauto\PathautoState;
15 use Drupal\pathauto\Tests\PathautoTestHelperTrait;
16 use Drupal\KernelTests\KernelTestBase;
17 use Drupal\taxonomy\Entity\Term;
18 use Drupal\taxonomy\Entity\Vocabulary;
19 use Drupal\node\Entity\Node;
20 use Drupal\user\Entity\User;
23 * Unit tests for Pathauto functions.
27 class PathautoKernelTest extends KernelTestBase {
29 use PathautoTestHelperTrait;
31 public static $modules = array('system', 'field', 'text', 'user', 'node', 'path', 'pathauto', 'taxonomy', 'token', 'filter', 'ctools', 'language');
33 protected $currentUser;
36 * @var \Drupal\pathauto\PathautoPatternInterface
38 protected $nodePattern;
41 * @var \Drupal\pathauto\PathautoPatternInterface
43 protected $userPattern;
45 public function setUp() {
48 $this->installConfig(array('pathauto', 'taxonomy', 'system', 'node'));
50 $this->installEntitySchema('user');
51 $this->installEntitySchema('node');
52 $this->installEntitySchema('taxonomy_term');
54 ConfigurableLanguage::createFromLangcode('fr')->save();
56 $this->installSchema('node', array('node_access'));
57 $this->installSchema('system', array('url_alias', 'sequences', 'router'));
59 $type = NodeType::create(['type' => 'page']);
61 node_add_body_field($type);
63 $this->nodePattern = $this->createPattern('node', '/content/[node:title]');
64 $this->userPattern = $this->createPattern('user', '/users/[user:name]');
66 \Drupal::service('router.builder')->rebuild();
68 $this->currentUser = User::create(array('name' => $this->randomMachineName()));
69 $this->currentUser->save();
73 * Test _pathauto_get_schema_alias_maxlength().
75 public function testGetSchemaAliasMaxLength() {
76 $this->assertIdentical(\Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength(), 255);
80 * Test pathauto_pattern_load_by_entity().
82 public function testPatternLoadByEntity() {
83 $pattern = $this->createPattern('node', '/article/[node:title]', -1);
84 $this->addBundleCondition($pattern, 'node', 'article');
87 $pattern = $this->createPattern('node', '/article/en/[node:title]', -2);
88 $this->addBundleCondition($pattern, 'node', 'article');
89 $pattern->addSelectionCondition(
96 'context_mapping' => [
97 'language' => 'node:langcode:language',
102 $pattern->addRelationship('node:langcode:language');
105 $pattern = $this->createPattern('node', '/[node:title]', -1);
106 $this->addBundleCondition($pattern, 'node', 'page');
113 'title' => 'Article fr',
117 'expected' => '/article/[node:title]',
122 'title' => 'Article en',
126 'expected' => '/article/en/[node:title]',
131 'title' => 'Article und',
133 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
135 'expected' => '/article/[node:title]',
143 'expected' => '/[node:title]',
150 'expected' => '/users/[user:name]',
153 foreach ($tests as $test) {
154 $entity = \Drupal::entityTypeManager()->getStorage($test['entity'])->create($test['values']);
156 $actual = \Drupal::service('pathauto.generator')->getPatternByEntity($entity);
157 $this->assertIdentical($actual->getPattern(), $test['expected'], t("Correct pattern returned for @entity_type with @values", array(
158 '@entity' => $test['entity'],
159 '@values' => print_r($test['values'], TRUE),
165 * Test potential conflicts with the same alias in different languages.
167 public function testSameTitleDifferentLanguages() {
168 // Create two English articles with the same title.
170 'title' => 'Sample page',
174 $node1 = $this->drupalCreateNode($edit);
175 $this->assertEntityAlias($node1, '/content/sample-page', 'en');
177 $node2 = $this->drupalCreateNode($edit);
178 $this->assertEntityAlias($node2, '/content/sample-page-0', 'en');
180 // Now, create a French article with the same title, and verify that it gets
181 // the basic alias with the correct langcode.
182 $edit['langcode'] = 'fr';
183 $node3 = $this->drupalCreateNode($edit);
184 $this->assertEntityAlias($node3, '/content/sample-page', 'fr');
188 * Test pathauto_cleanstring().
190 public function testCleanString() {
192 // Test with default settings defined in pathauto.settings.yml.
193 $this->installConfig(array('pathauto'));
194 \Drupal::service('pathauto.generator')->resetCaches();
198 // Test the 'ignored words' removal.
199 $tests['this'] = 'this';
200 $tests['this with that'] = 'this-with-that';
201 $tests['this thing with that thing'] = 'thing-thing';
203 // Test 'ignored words' removal and duplicate separator removal.
204 $tests[' - Pathauto is the greatest - module ever - '] = 'pathauto-greatest-module-ever';
206 // Test length truncation and lowering of strings.
207 $long_string = $this->randomMachineName(120);
208 $tests[$long_string] = strtolower(substr($long_string, 0, 100));
210 // Test that HTML tags are removed.
211 $tests['This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.'] = 'text-has-html-tags';
212 $tests[Html::escape('This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.')] = 'text-has-html-tags';
215 $tests['ľščťžýáíéňô'] = 'lsctzyaieno';
217 foreach ($tests as $input => $expected) {
218 $output = \Drupal::service('pathauto.alias_cleaner')->cleanString($input);
219 $this->assertEqual($output, $expected, t("Drupal::service('pathauto.alias_cleaner')->cleanString('@input') expected '@expected', actual '@output'", array(
221 '@expected' => $expected,
222 '@output' => $output,
228 * Test pathauto_clean_alias().
230 public function testCleanAlias() {
232 $tests['one/two/three'] = '/one/two/three';
233 $tests['/one/two/three/'] = '/one/two/three';
234 $tests['one//two///three'] = '/one/two/three';
235 $tests['one/two--three/-/--/-/--/four---five'] = '/one/two-three/four-five';
236 $tests['one/-//three--/four'] = '/one/three/four';
238 foreach ($tests as $input => $expected) {
239 $output = \Drupal::service('pathauto.alias_cleaner')->cleanAlias($input);
240 $this->assertEqual($output, $expected, t("Drupal::service('pathauto.generator')->cleanAlias('@input') expected '@expected', actual '@output'", array(
242 '@expected' => $expected,
243 '@output' => $output,
249 * Test pathauto_path_delete_multiple().
251 public function testPathDeleteMultiple() {
252 $this->saveAlias('/node/1', '/node-1-alias');
253 $this->saveAlias('/node/1/view', '/node-1-alias/view');
254 $this->saveAlias('/node/1', '/node-1-alias-en', 'en');
255 $this->saveAlias('/node/1', '/node-1-alias-fr', 'fr');
256 $this->saveAlias('/node/2', '/node-2-alias');
257 $this->saveAlias('/node/10', '/node-10-alias');
259 \Drupal::service('pathauto.alias_storage_helper')->deleteBySourcePrefix('/node/1');
260 $this->assertNoAliasExists(array('source' => "/node/1"));
261 $this->assertNoAliasExists(array('source' => "/node/1/view"));
262 $this->assertAliasExists(array('source' => "/node/2"));
263 $this->assertAliasExists(array('source' => "/node/10"));
267 * Test the different update actions in \Drupal::service('pathauto.generator')->createEntityAlias().
269 public function testUpdateActions() {
270 $config = $this->config('pathauto.settings');
272 // Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'insert'.
273 $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW);
275 $node = $this->drupalCreateNode(array('title' => 'First title'));
276 $this->assertEntityAlias($node, '/content/first-title');
278 $node->path->pathauto = PathautoState::CREATE;
280 // Default action is PATHAUTO_UPDATE_ACTION_DELETE.
281 $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_DELETE);
283 $node->setTitle('Second title');
285 $this->assertEntityAlias($node, '/content/second-title');
286 $this->assertNoAliasExists(array('alias' => '/content/first-title'));
288 // Test PATHAUTO_UPDATE_ACTION_LEAVE
289 $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_LEAVE);
291 $node->setTitle('Third title');
293 $this->assertEntityAlias($node, '/content/third-title');
294 $this->assertAliasExists(array('source' => '/' . $node->toUrl()->getInternalPath(), 'alias' => '/content/second-title'));
296 $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_DELETE);
298 $node->setTitle('Fourth title');
300 $this->assertEntityAlias($node, '/content/fourth-title');
301 $this->assertNoAliasExists(array('alias' => '/content/third-title'));
302 // The older second alias is not deleted yet.
303 $older_path = $this->assertAliasExists(array('source' => '/' . $node->toUrl()->getInternalPath(), 'alias' => '/content/second-title'));
304 \Drupal::service('path.alias_storage')->delete($older_path);
306 $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW);
308 $node->setTitle('Fifth title');
310 $this->assertEntityAlias($node, '/content/fourth-title');
311 $this->assertNoAliasExists(array('alias' => '/content/fifth-title'));
313 // Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'update'.
314 $this->deleteAllAliases();
316 $this->assertEntityAlias($node, '/content/fifth-title');
318 // Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'bulkupdate'.
319 $this->deleteAllAliases();
320 $node->setTitle('Sixth title');
321 \Drupal::service('pathauto.generator')->updateEntityAlias($node, 'bulkupdate');
322 $this->assertEntityAlias($node, '/content/sixth-title');
326 * Test that \Drupal::service('pathauto.generator')->createEntityAlias() will not create an alias for a pattern
327 * that does not get any tokens replaced.
329 public function testNoTokensNoAlias() {
330 $this->installConfig(['filter']);
332 ->setPattern('/content/[node:body]')
335 $node = $this->drupalCreateNode();
336 $this->assertNoEntityAliasExists($node);
338 $node->body->value = 'hello';
340 $this->assertEntityAlias($node, '/content/hello');
344 * Test the handling of path vs non-path tokens in pathauto_clean_token_values().
346 public function testPathTokens() {
347 $this->createPattern('taxonomy_term', '/[term:parent:url:path]/[term:name]');
349 $vocab = $this->addVocabulary();
351 $term1 = $this->addTerm($vocab, array('name' => 'Parent term'));
352 $this->assertEntityAlias($term1, '/parent-term');
354 $term2 = $this->addTerm($vocab, array('name' => 'Child term', 'parent' => $term1->id()));
355 $this->assertEntityAlias($term2, '/parent-term/child-term');
357 $this->saveEntityAlias($term1, '/My Crazy/Alias/');
359 $this->assertEntityAlias($term2, '/My Crazy/Alias/child-term');
363 * Test using fields for path structures.
365 function testParentChildPathTokens() {
366 // First create a field which will be used to create the path. It must
367 // begin with a letter.
369 $this->installEntitySchema('taxonomy_term');
371 Vocabulary::create(['vid' => 'tags'])->save();
373 $fieldname = 'a' . Unicode::strtolower($this->randomMachineName());
374 $field_storage = FieldStorageConfig::create(['entity_type' => 'taxonomy_term', 'field_name' => $fieldname, 'type' => 'string']);
375 $field_storage->save();
376 $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'tags']);
379 $display = entity_get_display('taxonomy_term', 'tags', 'default');
380 $display->setComponent($fieldname, ['type' => 'string']);
383 // Make the path pattern of a field use the value of this field appended
384 // to the parent taxonomy term's pattern if there is one.
385 $this->createPattern('taxonomy_term', '/[term:parents:join-path]/[term:' . $fieldname . ']');
387 // Start by creating a parent term.
388 $parent = Term::create(['vid' => 'tags', $fieldname => $this->randomMachineName(), 'name' => $this->randomMachineName()]);
391 // Create the child term.
392 $child = Term::create(['vid' => 'tags', $fieldname => $this->randomMachineName(), 'parent' => $parent, 'name' => $this->randomMachineName()]);
394 $this->assertEntityAlias($child, '/' . Unicode::strtolower($parent->getName() . '/' . $child->$fieldname->value));
396 // Re-saving the parent term should not modify the child term's alias.
398 $this->assertEntityAlias($child, '/' . Unicode::strtolower($parent->getName() . '/' . $child->$fieldname->value));
402 * Tests aliases on taxonomy terms.
404 public function testTaxonomyPattern() {
405 // Create a vocabulary and test that it's pattern variable works.
406 $vocab = $this->addVocabulary(array('vid' => 'name'));
407 $this->createPattern('taxonomy_term', 'base');
408 $pattern = $this->createPattern('taxonomy_term', 'bundle', -1);
409 $this->addBundleCondition($pattern, 'taxonomy_term', 'name');
411 $this->assertEntityPattern('taxonomy_term', 'name', Language::LANGCODE_NOT_SPECIFIED, 'bundle');
414 function testNoExistingPathAliases() {
415 $this->config('pathauto.settings')
416 ->set('punctuation.period', PathautoGeneratorInterface::PUNCTUATION_DO_NOTHING)
420 ->setPattern('[node:title]')
423 // Check that Pathauto does not create an alias of '/admin'.
424 $node = $this->drupalCreateNode(array('title' => 'Admin', 'type' => 'page'));
425 $this->assertEntityAlias($node, '/admin-0');
427 // Check that Pathauto does not create an alias of '/modules'.
428 $node->setTitle('Modules');
430 $this->assertEntityAlias($node, '/modules-0');
432 // Check that Pathauto does not create an alias of '/index.php'.
433 $node->setTitle('index.php');
435 $this->assertEntityAlias($node, '/index.php-0');
437 // Check that a safe value gets an automatic alias. This is also a control
438 // to ensure the above tests work properly.
439 $node->setTitle('Safe value');
441 $this->assertEntityAlias($node, '/safe-value');
445 * Test programmatic entity creation for aliases.
447 function testProgrammaticEntityCreation() {
448 $this->createPattern('taxonomy_term', '/[term:vocabulary]/[term:name]');
449 $node = $this->drupalCreateNode(array('title' => 'Test node', 'path' => array('pathauto' => TRUE)));
450 $this->assertEntityAlias($node, '/content/test-node');
452 $vocabulary = $this->addVocabulary(array('name' => 'Tags'));
453 $term = $this->addTerm($vocabulary, array('name' => 'Test term', 'path' => array('pathauto' => TRUE)));
454 $this->assertEntityAlias($term, '/tags/test-term');
456 $edit['name'] = 'Test user';
457 $edit['mail'] = 'test-user@example.com';
458 $edit['pass'] = user_password();
459 $edit['path'] = array('pathauto' => TRUE);
461 $account = User::create($edit);
463 $this->assertEntityAlias($account, '/users/test-user');
467 * Tests word safe alias truncating.
469 function testPathAliasUniquifyWordsafe() {
470 $this->config('pathauto.settings')
471 ->set('max_length', 26)
474 $node_1 = $this->drupalCreateNode(array('title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page'));
475 $node_2 = $this->drupalCreateNode(array('title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page'));
477 // Check that alias uniquifying is truncating with $wordsafe param set to
479 // If it doesn't path alias result would be content/thequick-brownf-0
480 $this->assertEntityAlias($node_1, '/content/thequick-brownfox');
481 $this->assertEntityAlias($node_2, '/content/thequick-0');
485 * Test if aliases are (not) generated with enabled/disabled patterns.
487 function testPatternStatus() {
488 // Create a node to get an alias for.
489 $title = 'Pattern enabled';
490 $alias = '/content/pattern-enabled';
491 $node1 = $this->drupalCreateNode(['title' => $title, 'type' => 'page']);
492 $this->assertEntityAlias($node1, $alias);
494 // Disable the pattern, save the node again and make sure the alias is still
496 $this->nodePattern->setStatus(FALSE)->save();
499 $this->assertEntityAlias($node1, $alias);
501 // Create a new node with disabled pattern and make sure there is no new
503 $title = 'Pattern disabled';
504 $node2 = $this->drupalCreateNode(['title' => $title, 'type' => 'page']);
505 $this->assertNoEntityAlias($node2);
509 * Tests that enabled entity types genrates the necessary fields and plugins.
511 public function testSettingChangeInvalidatesCache() {
513 $this->installConfig(['pathauto']);
515 $this->enableModules(['entity_test']);
517 $definitions = \Drupal::service('plugin.manager.alias_type')->getDefinitions();
518 $this->assertFalse(isset($definitions['canonical_entities:entity_test']));
520 $fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('entity_test');
521 $this->assertFalse(isset($fields['path']));
523 $this->config('pathauto.settings')
524 ->set('enabled_entity_types', ['user', 'entity_test'])
527 $definitions = \Drupal::service('plugin.manager.alias_type')->getDefinitions();
528 $this->assertTrue(isset($definitions['canonical_entities:entity_test']));
530 $fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('entity_test');
531 $this->assertTrue(isset($fields['path']));
536 * Tests that aliases are only generated for default revisions.
538 public function testDefaultRevision() {
539 $node1 = $this->drupalCreateNode(['title' => 'Default revision', 'type' => 'page']);
540 $this->assertEntityAlias($node1, '/content/default-revision');
542 $node1->setNewRevision(TRUE);
543 $node1->isDefaultRevision(FALSE);
544 $node1->setTitle('New non-default-revision');
547 $this->assertEntityAlias($node1, '/content/default-revision');
551 * Tests that the pathauto state property gets set to CREATED for new nodes.
553 * In some cases, this can trigger $node->path to be set up with no default
554 * value for the pathauto property.
556 public function testCreateNodeWhileAccessingPath() {
557 $node = Node::create([
559 'title' => 'TestAlias',
561 $node->path->langcode;
563 $this->assertEntityAlias($node, '/content/testalias');
567 * Creates a node programmatically.
569 * @param array $settings
570 * The array of values for the node.
572 * @return \Drupal\node\Entity\Node
575 protected function drupalCreateNode(array $settings = array()) {
576 // Populate defaults array.
578 'title' => $this->randomMachineName(8),
582 $node = Node::create($settings);