You are here

public function BlockTest::testAddBlockFromLibraryWithWeight in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/block/tests/src/Functional/BlockTest.php \Drupal\Tests\block\Functional\BlockTest::testAddBlockFromLibraryWithWeight()

Tests adding a block from the library page with a weight query string.

File

core/modules/block/tests/src/Functional/BlockTest.php, line 148

Class

BlockTest
Tests basic block functionality.

Namespace

Drupal\Tests\block\Functional

Code

public function testAddBlockFromLibraryWithWeight() {
  $default_theme = $this
    ->config('system.theme')
    ->get('default');

  // Test one positive, zero, and one negative weight.
  foreach ([
    '7',
    '0',
    '-9',
  ] as $weight) {
    $options = [
      'query' => [
        'region' => 'sidebar_first',
        'weight' => $weight,
      ],
    ];
    $this
      ->drupalGet(Url::fromRoute('block.admin_library', [
      'theme' => $default_theme,
    ], $options));
    $block_name = 'system_powered_by_block';
    $add_url = Url::fromRoute('block.admin_add', [
      'plugin_id' => $block_name,
      'theme' => $default_theme,
    ]);

    // Verify that one link is found, with the the expected link text.
    $xpath = $this
      ->assertSession()
      ->buildXPathQuery('//a[contains(@href, :href)]', [
      ':href' => $add_url
        ->toString(),
    ]);
    $this
      ->assertSession()
      ->elementsCount('xpath', $xpath, 1);
    $this
      ->assertSession()
      ->elementTextEquals('xpath', $xpath, 'Place block');
    $link = $this
      ->getSession()
      ->getPage()
      ->find('xpath', $xpath);
    list($path, $query_string) = explode('?', $link
      ->getAttribute('href'), 2);
    parse_str($query_string, $query_parts);
    $this
      ->assertEquals($weight, $query_parts['weight'], 'Found the expected weight query string.');

    // Create a random title for the block.
    $title = $this
      ->randomMachineName(8);
    $block_id = strtolower($this
      ->randomMachineName(8));
    $edit = [
      'id' => $block_id,
      'settings[label]' => $title,
    ];

    // Create the block using the link parsed from the library page.
    $this
      ->drupalGet($this
      ->getAbsoluteUrl($link
      ->getAttribute('href')));
    $this
      ->submitForm($edit, 'Save block');

    // Ensure that the block was created with the expected weight.

    /** @var \Drupal\block\BlockInterface $block */
    $block = Block::load($block_id);
    $this
      ->assertEquals($weight, $block
      ->getWeight(), 'Found the block with expected weight.');
  }
}