BlockRenderOrderTest.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace Drupal\Tests\block\Functional;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Tests\BrowserTestBase;
  5. /**
  6. * Tests blocks are being rendered in order by weight.
  7. *
  8. * @group block
  9. */
  10. class BlockRenderOrderTest extends BrowserTestBase {
  11. /**
  12. * Modules to install.
  13. *
  14. * @var array
  15. */
  16. public static $modules = ['node', 'block'];
  17. protected function setUp() {
  18. parent::setUp();
  19. // Create a test user.
  20. $end_user = $this->drupalCreateUser([
  21. 'access content',
  22. ]);
  23. $this->drupalLogin($end_user);
  24. }
  25. /**
  26. * Tests the render order of the blocks.
  27. */
  28. public function testBlockRenderOrder() {
  29. // Enable test blocks and place them in the same region.
  30. $region = 'header';
  31. $test_blocks = [
  32. 'stark_powered' => [
  33. 'weight' => '-3',
  34. 'id' => 'stark_powered',
  35. 'label' => 'Test block A',
  36. ],
  37. 'stark_by' => [
  38. 'weight' => '3',
  39. 'id' => 'stark_by',
  40. 'label' => 'Test block C',
  41. ],
  42. 'stark_drupal' => [
  43. 'weight' => '3',
  44. 'id' => 'stark_drupal',
  45. 'label' => 'Test block B',
  46. ],
  47. ];
  48. // Place the test blocks.
  49. foreach ($test_blocks as $test_block) {
  50. $this->drupalPlaceBlock('system_powered_by_block', [
  51. 'label' => $test_block['label'],
  52. 'region' => $region,
  53. 'weight' => $test_block['weight'],
  54. 'id' => $test_block['id'],
  55. ]);
  56. }
  57. $this->drupalGet('');
  58. $test_content = $this->getSession()->getPage()->getContent();
  59. $controller = $this->container->get('entity_type.manager')->getStorage('block');
  60. foreach ($controller->loadMultiple() as $return_block) {
  61. $id = $return_block->id();
  62. if ($return_block_weight = $return_block->getWeight()) {
  63. $this->assertTrue($test_blocks[$id]['weight'] == $return_block_weight, 'Block weight is set as "' . $return_block_weight . '" for ' . $id . ' block.');
  64. $position[$id] = strpos($test_content, Html::getClass('block-' . $test_blocks[$id]['id']));
  65. }
  66. }
  67. $this->assertTrue($position['stark_powered'] < $position['stark_by'], 'Blocks with different weight are rendered in the correct order.');
  68. $this->assertTrue($position['stark_drupal'] < $position['stark_by'], 'Blocks with identical weight are rendered in alphabetical order.');
  69. }
  70. }