ShortcutLinksTest.php 18.4 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\shortcut\Functional;
4

5
use Drupal\block_content\Entity\BlockContentType;
6
use Drupal\Component\Utility\SafeMarkup;
7
use Drupal\Component\Render\FormattableMarkup;
8
use Drupal\Core\Url;
9
use Drupal\shortcut\Entity\Shortcut;
10
use Drupal\shortcut\Entity\ShortcutSet;
11
use Drupal\Tests\block\Functional\AssertBlockAppearsTrait;
12
use Drupal\views\Entity\View;
13 14

/**
15 16 17
 * Create, view, edit, delete, and change shortcut links.
 *
 * @group shortcut
18 19 20
 */
class ShortcutLinksTest extends ShortcutTestBase {

21 22
  use AssertBlockAppearsTrait;

23 24 25 26 27
  /**
   * Modules to enable.
   *
   * @var array
   */
28
  public static $modules = ['router_test', 'views', 'block'];
29

30 31 32 33 34 35 36 37 38
  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->drupalPlaceBlock('page_title_block');
  }

39 40 41
  /**
   * Tests that creating a shortcut works properly.
   */
42
  public function testShortcutLinkAdd() {
43 44 45
    $set = $this->set;

    // Create an alias for the node so we can test aliases.
46
    $path = [
47 48
      'source' => '/node/' . $this->node->id(),
      'alias' => '/' . $this->randomMachineName(8),
49
    ];
50
    $this->container->get('path.alias_storage')->save($path['source'], $path['alias']);
51 52

    // Create some paths to test.
53
    $test_cases = [
54 55 56 57
      '/',
      '/admin',
      '/admin/config/system/site-information',
      '/node/' . $this->node->id() . '/edit',
58
      $path['alias'],
59 60
      '/router_test/test2',
      '/router_test/test3/value',
61
    ];
62

63
    $test_cases_non_access = [
64 65
      '/admin',
      '/admin/config/system/site-information',
66 67
    ];

68 69 70 71 72
    // Test the add shortcut form UI. Test that the base field description is
    // there.
    $this->drupalGet('admin/config/user-interface/shortcut/manage/' . $set->id() . '/add-link');
    $this->assertRaw('The location this shortcut points to.');

73
    // Check that each new shortcut links where it should.
74
    foreach ($test_cases as $test_path) {
75
      $title = $this->randomMachineName();
76
      $form_data = [
77
        'title[0][value]' => $title,
78
        'link[0][uri]' => $test_path,
79
      ];
80
      $this->drupalPostForm('admin/config/user-interface/shortcut/manage/' . $set->id() . '/add-link', $form_data, t('Save'));
81
      $this->assertResponse(200);
82
      $this->assertText(t('Added a shortcut for @title.', ['@title' => $title]));
83
      $saved_set = ShortcutSet::load($set->id());
84
      $paths = $this->getShortcutInformation($saved_set, 'link');
85
      $this->assertTrue(in_array('internal:' . $test_path, $paths), 'Shortcut created: ' . $test_path);
86 87

      if (in_array($test_path, $test_cases_non_access)) {
88
        $this->assertNoLink($title, SafeMarkup::format('Shortcut link %url not accessible on the page.', ['%url' => $test_path]));
89 90
      }
      else {
91
        $this->assertLink($title, 0, SafeMarkup::format('Shortcut link %url found on the page.', ['%url' => $test_path]));
92
      }
93
    }
94 95 96 97 98
    $saved_set = ShortcutSet::load($set->id());
    // Test that saving and re-loading a shortcut preserves its values.
    $shortcuts = $saved_set->getShortcuts();
    foreach ($shortcuts as $entity) {
      // Test the node routes with parameters.
99 100 101 102
      $entity->save();
      $loaded = Shortcut::load($entity->id());
      $this->assertEqual($entity->link->uri, $loaded->link->uri);
      $this->assertEqual($entity->link->options, $loaded->link->options);
103
    }
104

105
    // Log in as non admin user, to check that access is checked when creating
106
    // shortcuts.
107
    $this->drupalLogin($this->shortcutUser);
108 109 110
    $title = $this->randomMachineName();
    $form_data = [
      'title[0][value]' => $title,
111
      'link[0][uri]' => '/admin',
112 113 114
    ];
    $this->drupalPostForm('admin/config/user-interface/shortcut/manage/' . $set->id() . '/add-link', $form_data, t('Save'));
    $this->assertResponse(200);
115
    $this->assertRaw(t("The path '@link_path' is inaccessible.", ['@link_path' => '/admin']));
116 117 118

    $form_data = [
      'title[0][value]' => $title,
119
      'link[0][uri]' => '/node',
120 121 122
    ];
    $this->drupalPostForm('admin/config/user-interface/shortcut/manage/' . $set->id() . '/add-link', $form_data, t('Save'));
    $this->assertLink($title, 0, 'Shortcut link found on the page.');
123 124 125

    // Create a new shortcut set and add a link to it.
    $this->drupalLogin($this->adminUser);
126
    $edit = [
127 128
      'label' => $this->randomMachineName(),
      'id' => strtolower($this->randomMachineName()),
129
    ];
130 131 132 133 134 135 136 137
    $this->drupalPostForm('admin/config/user-interface/shortcut/add-set', $edit, t('Save'));
    $title = $this->randomMachineName();
    $form_data = [
      'title[0][value]' => $title,
      'link[0][uri]' => '/admin',
    ];
    $this->drupalPostForm('admin/config/user-interface/shortcut/manage/' . $edit['id'] . '/add-link', $form_data, t('Save'));
    $this->assertResponse(200);
138 139 140
  }

  /**
141
   * Tests that the "add to shortcut" and "remove from shortcut" links work.
142
   */
143
  public function testShortcutQuickLink() {
144
    \Drupal::service('theme_handler')->install(['seven']);
145 146
    $this->config('system.theme')->set('admin', 'seven')->save();
    $this->config('node.settings')->set('use_admin_theme', '1')->save();
147
    $this->container->get('router.builder')->rebuild();
148

149
    $this->drupalLogin($this->rootUser);
150
    $this->drupalGet('admin/config/system/cron');
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    // Test the "Add to shortcuts" link.
    $this->clickLink('Add to Default shortcuts');
    $this->assertText('Added a shortcut for Cron.');
    $this->assertLink('Cron', 0, 'Shortcut link found on page');

    $this->drupalGet('admin/structure');
    $this->assertLink('Cron', 0, 'Shortcut link found on different page');

    // Test the "Remove from shortcuts" link.
    $this->clickLink('Cron');
    $this->clickLink('Remove from Default shortcuts');
    $this->assertText('The shortcut Cron has been deleted.');
    $this->assertNoLink('Cron', 'Shortcut link removed from page');

    $this->drupalGet('admin/structure');
    $this->assertNoLink('Cron', 'Shortcut link removed from different page');
168 169 170 171 172 173

    $this->drupalGet('admin/people');

    // Test the "Add to shortcuts" link for a page generated by views.
    $this->clickLink('Add to Default shortcuts');
    $this->assertText('Added a shortcut for People.');
174
    $this->assertShortcutQuickLink('Remove from Default shortcuts');
175 176 177 178

    // Test the "Remove from  shortcuts" link for a page generated by views.
    $this->clickLink('Remove from Default shortcuts');
    $this->assertText('The shortcut People has been deleted.');
179
    $this->assertShortcutQuickLink('Add to Default shortcuts');
180 181 182 183 184 185 186 187

    // Test two pages which use same route name but different route parameters.
    $this->drupalGet('node/add/page');
    // Add Shortcut for Basic Page.
    $this->clickLink('Add to Default shortcuts');
    $this->assertText('Added a shortcut for Create Basic page.');
    // Assure that Article does not have its shortcut indicated as set.
    $this->drupalGet('node/add/article');
188
    $link = $this->xpath('//a[normalize-space()=:label]', [':label' => 'Remove from Default shortcuts']);
189 190 191 192
    $this->assertTrue(empty($link), 'Link Remove to Default shortcuts not found for Create Article page.');
    // Add Shortcut for Article.
    $this->clickLink('Add to Default shortcuts');
    $this->assertText('Added a shortcut for Create Article.');
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

    $this->config('system.theme')->set('default', 'seven')->save();
    $this->drupalGet('node/' . $this->node->id());
    $title = $this->node->getTitle();

    // Test the "Add to shortcuts" link for node view route.
    $this->clickLink('Add to Default shortcuts');
    $this->assertText(new FormattableMarkup('Added a shortcut for @title.', ['@title' => $title]));
    $this->assertShortcutQuickLink('Remove from Default shortcuts');

    // Test the "Remove from shortcuts" link for node view route.
    $this->clickLink('Remove from Default shortcuts');
    $this->assertText(new FormattableMarkup('The shortcut @title has been deleted.', ['@title' => $title]));
    $this->assertShortcutQuickLink('Add to Default shortcuts');

    \Drupal::service('module_installer')->install(['block_content']);
209
    BlockContentType::create([
210 211 212
      'id' => 'basic',
      'label' => 'Basic block',
      'revision' => FALSE,
213
    ])->save();
214 215 216 217 218 219 220 221 222 223
    // Test page with HTML tags in title.
    $this->drupalGet('admin/structure/block/block-content/manage/basic');
    $page_title = new FormattableMarkup('Edit %label custom block type', ['%label' => 'Basic block']);
    $this->assertRaw($page_title);
    // Add shortcut to this page.
    $this->clickLink('Add to Default shortcuts');
    $this->assertRaw(new FormattableMarkup('Added a shortcut for %title.', [
      '%title' => trim(strip_tags($page_title)),
    ]));

224 225 226 227 228
  }

  /**
   * Tests that shortcut links can be renamed.
   */
229
  public function testShortcutLinkRename() {
230 231 232
    $set = $this->set;

    // Attempt to rename shortcut link.
233
    $new_link_name = $this->randomMachineName();
234

235 236
    $shortcuts = $set->getShortcuts();
    $shortcut = reset($shortcuts);
237
    $this->drupalPostForm('admin/config/user-interface/shortcut/link/' . $shortcut->id(), ['title[0][value]' => $new_link_name], t('Save'));
238
    $saved_set = ShortcutSet::load($set->id());
239
    $titles = $this->getShortcutInformation($saved_set, 'title');
240 241
    $this->assertTrue(in_array($new_link_name, $titles), 'Shortcut renamed: ' . $new_link_name);
    $this->assertLink($new_link_name, 0, 'Renamed shortcut link appears on the page.');
242
    $this->assertText(t('The shortcut @link has been updated.', ['@link' => $new_link_name]));
243 244 245 246 247
  }

  /**
   * Tests that changing the path of a shortcut link works.
   */
248
  public function testShortcutLinkChangePath() {
249 250 251
    $set = $this->set;

    // Tests changing a shortcut path.
252
    $new_link_path = '/admin/config';
253

254 255
    $shortcuts = $set->getShortcuts();
    $shortcut = reset($shortcuts);
256
    $this->drupalPostForm('admin/config/user-interface/shortcut/link/' . $shortcut->id(), ['title[0][value]' => $shortcut->getTitle(), 'link[0][uri]' => $new_link_path], t('Save'));
257
    $saved_set = ShortcutSet::load($set->id());
258
    $paths = $this->getShortcutInformation($saved_set, 'link');
259
    $this->assertTrue(in_array('internal:' . $new_link_path, $paths), 'Shortcut path changed: ' . $new_link_path);
260
    $this->assertLinkByHref($new_link_path, 0, 'Shortcut with new path appears on the page.');
261
    $this->assertText(t('The shortcut @link has been updated.', ['@link' => $shortcut->getTitle()]));
262 263
  }

264 265 266 267
  /**
   * Tests that changing the route of a shortcut link works.
   */
  public function testShortcutLinkChangeRoute() {
268
    $this->drupalLogin($this->rootUser);
269 270 271
    $this->drupalGet('admin/content');
    $this->assertResponse(200);
    // Disable the view.
272
    View::load('content')->disable()->save();
273 274 275
    /** @var \Drupal\Core\Routing\RouteBuilderInterface $router_builder */
    $router_builder = \Drupal::service('router.builder');
    $router_builder->rebuildIfNeeded();
276 277 278 279
    $this->drupalGet('admin/content');
    $this->assertResponse(200);
  }

280 281 282
  /**
   * Tests deleting a shortcut link.
   */
283
  public function testShortcutLinkDelete() {
284 285
    $set = $this->set;

286 287
    $shortcuts = $set->getShortcuts();
    $shortcut = reset($shortcuts);
288
    $this->drupalPostForm('admin/config/user-interface/shortcut/link/' . $shortcut->id() . '/delete', [], 'Delete');
289
    $saved_set = ShortcutSet::load($set->id());
290 291
    $ids = $this->getShortcutInformation($saved_set, 'id');
    $this->assertFalse(in_array($shortcut->id(), $ids), 'Successfully deleted a shortcut.');
292

293 294
    // Delete all the remaining shortcut links.
    entity_delete_multiple('shortcut', array_filter($ids));
295 296 297

    // Get the front page to check that no exceptions occur.
    $this->drupalGet('');
298 299 300 301 302 303 304 305
  }

  /**
   * Tests that the add shortcut link is not displayed for 404/403 errors.
   *
   * Tests that the "Add to shortcuts" link is not displayed on a page not
   * found or a page the user does not have access to.
   */
306
  public function testNoShortcutLink() {
307
    // Change to a theme that displays shortcuts.
308
    \Drupal::service('theme_handler')->install(['seven']);
309
    $this->config('system.theme')
310 311
      ->set('default', 'seven')
      ->save();
312 313

    $this->drupalGet('page-that-does-not-exist');
314
    $result = $this->xpath('//a[contains(@class, "shortcut-action--add")]');
315
    $this->assertTrue(empty($result), 'Add to shortcuts link was not shown on a page not found.');
316 317 318

    // The user does not have access to this path.
    $this->drupalGet('admin/modules');
319
    $result = $this->xpath('//a[contains(@class, "shortcut-action--add")]');
320
    $this->assertTrue(empty($result), 'Add to shortcuts link was not shown on a page the user does not have access to.');
321

322 323 324 325
    // Verify that the testing mechanism works by verifying the shortcut link
    // appears on admin/content.
    $this->drupalGet('admin/content');
    $result = $this->xpath('//a[contains(@class, "shortcut-action--remove")]');
326 327 328 329
    $this->assertTrue(!empty($result), 'Remove from shortcuts link was shown on a page the user does have access to.');

    // Verify that the shortcut link appears on routing only pages.
    $this->drupalGet('router_test/test2');
330
    $result = $this->xpath('//a[contains(@class, "shortcut-action--add")]');
331
    $this->assertTrue(!empty($result), 'Add to shortcuts link was shown on a page the user does have access to.');
332
  }
333

334 335 336 337 338
  /**
   * Tests that the 'access shortcuts' permissions works properly.
   */
  public function testAccessShortcutsPermission() {
    // Change to a theme that displays shortcuts.
339
    \Drupal::service('theme_handler')->install(['seven']);
340
    $this->config('system.theme')
341 342 343 344
      ->set('default', 'seven')
      ->save();

    // Add cron to the default shortcut set.
345
    $this->drupalLogin($this->rootUser);
346 347 348 349 350
    $this->drupalGet('admin/config/system/cron');
    $this->clickLink('Add to Default shortcuts');

    // Verify that users without the 'access shortcuts' permission can't see the
    // shortcuts.
351
    $this->drupalLogin($this->drupalCreateUser(['access toolbar']));
352 353 354 355
    $this->assertNoLink('Shortcuts', 'Shortcut link not found on page.');

    // Verify that users without the 'administer site configuration' permission
    // can't see the cron shortcuts.
356
    $this->drupalLogin($this->drupalCreateUser(['access toolbar', 'access shortcuts']));
357 358
    $this->assertNoLink('Shortcuts', 'Shortcut link not found on page.');
    $this->assertNoLink('Cron', 'Cron shortcut link not found on page.');
359 360 361

    // Verify that users with the 'access shortcuts' permission can see the
    // shortcuts.
362
    $this->drupalLogin($this->drupalCreateUser([
363
      'access toolbar', 'access shortcuts', 'administer site configuration',
364
    ]));
365 366 367 368 369 370
    $this->clickLink('Shortcuts', 0, 'Shortcut link found on page.');
    $this->assertLink('Cron', 0, 'Cron shortcut link found on page.');

    $this->verifyAccessShortcutsPermissionForEditPages();
  }

371 372 373 374
  /**
   * Tests the shortcuts are correctly ordered by weight in the toolbar.
   */
  public function testShortcutLinkOrder() {
375
    // Ensure to give permissions to access the shortcuts.
376
    $this->drupalLogin($this->drupalCreateUser(['access toolbar', 'access shortcuts', 'access content overview', 'administer content types']));
377
    $this->drupalGet(Url::fromRoute('<front>'));
378
    $shortcuts = $this->cssSelect('#toolbar-item-shortcuts-tray .toolbar-menu a');
379 380
    $this->assertEqual($shortcuts[0]->getText(), 'Add content');
    $this->assertEqual($shortcuts[1]->getText(), 'All content');
381
    foreach ($this->set->getShortcuts() as $shortcut) {
382 383 384
      $shortcut->setWeight($shortcut->getWeight() * -1)->save();
    }
    $this->drupalGet(Url::fromRoute('<front>'));
385
    $shortcuts = $this->cssSelect('#toolbar-item-shortcuts-tray .toolbar-menu a');
386 387
    $this->assertEqual($shortcuts[0]->getText(), 'All content');
    $this->assertEqual($shortcuts[1]->getText(), 'Add content');
388 389
  }

390 391 392 393 394 395 396
  /**
   * Tests that the 'access shortcuts' permission is required for shortcut set
   * administration page access.
   */
  private function verifyAccessShortcutsPermissionForEditPages() {
    // Create a user with customize links and switch sets permissions  but
    // without the 'access shortcuts' permission.
397
    $test_permissions = [
398 399
      'customize shortcut links',
      'switch shortcut sets',
400
    ];
401 402 403 404 405
    $noaccess_user = $this->drupalCreateUser($test_permissions);
    $this->drupalLogin($noaccess_user);

    // Verify that set administration pages are inaccessible without the
    // 'access shortcuts' permission.
406
    $edit_paths = [
407 408 409
      'admin/config/user-interface/shortcut/manage/default/customize',
      'admin/config/user-interface/shortcut/manage/default',
      'user/' . $noaccess_user->id() . '/shortcuts',
410
    ];
411 412 413

    foreach ($edit_paths as $path) {
      $this->drupalGet($path);
414
      $message = format_string('Access is denied on %s', ['%s' => $path]);
415 416 417 418
      $this->assertResponse(403, $message);
    }
  }

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  /**
   * Tests that the 'access shortcuts' permission is required to access the
   * shortcut block.
   */
  public function testShortcutBlockAccess() {
    // Creates a block instance and place in a region through api.
    $block = $this->drupalPlaceBlock('shortcuts');

    // Verify that users with the 'access shortcuts' permission can see the
    // shortcut block.
    $this->drupalLogin($this->shortcutUser);
    $this->drupalGet('');
    $this->assertBlockAppears($block);

    $this->drupalLogout();

    // Verify that users without the 'access shortcuts' permission can see the
    // shortcut block.
437
    $this->drupalLogin($this->drupalCreateUser([]));
438 439 440 441
    $this->drupalGet('');
    $this->assertNoBlockAppears($block);
  }

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  /**
   * Passes if a shortcut quick link with the specified label is found.
   *
   * An optional link index may be passed.
   *
   * @param string $label
   *   Text between the anchor tags.
   * @param int $index
   *   Link position counting from zero.
   * @param string $message
   *   (optional) A message to display with the assertion. Do not translate
   *   messages: use format_string() to embed variables in the message text, not
   *   t(). If left blank, a default message will be displayed.
   * @param string $group
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
   *
   * @return bool
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertShortcutQuickLink($label, $index = 0, $message = '', $group = 'Other') {
465 466
    $links = $this->xpath('//a[normalize-space()=:label]', [':label' => $label]);
    $message = ($message ? $message : SafeMarkup::format('Shortcut quick link with label %label found.', ['%label' => $label]));
467 468 469
    return $this->assert(isset($links[$index]), $message, $group);
  }

470
}