block.test

  1. 7.x drupal/modules/block/block.test
  2. 8.x drupal/core/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block.test

Tests for block.module.

Classes

Namesort descending Description
BlockAdminThemeTestCase Test the block system with admin themes.
BlockCacheTestCase Test block caching.
BlockHashTestCase Tests that block rehashing works correctly.
BlockHiddenRegionTestCase Tests that hidden regions do not inherit blocks when a theme is enabled.
BlockHTMLIdTestCase Test block HTML id validity.
BlockInvalidRegionTestCase Tests that a block assigned to an invalid region triggers the warning.
BlockTemplateSuggestionsUnitTest Unit tests for template_preprocess_block().
BlockTestCase
BlockViewModuleDeltaAlterWebTest Tests for hook_block_view_MODULE_DELTA_alter().
NewDefaultThemeBlocks Test blocks correctly initialized when picking a new default theme.
NonDefaultBlockAdmin

File

drupal/modules/block/block.test
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tests for block.module.
  5. */
  6. class BlockTestCase extends DrupalWebTestCase {
  7. protected $regions;
  8. protected $admin_user;
  9. public static function getInfo() {
  10. return array(
  11. 'name' => 'Block functionality',
  12. 'description' => 'Add, edit and delete custom block. Configure and move a module-defined block.',
  13. 'group' => 'Block',
  14. );
  15. }
  16. function setUp() {
  17. parent::setUp();
  18. // Create and log in an administrative user having access to the Full HTML
  19. // text format.
  20. $full_html_format = filter_format_load('full_html');
  21. $this->admin_user = $this->drupalCreateUser(array(
  22. 'administer blocks',
  23. filter_permission_name($full_html_format),
  24. 'access administration pages',
  25. ));
  26. $this->drupalLogin($this->admin_user);
  27. // Define the existing regions
  28. $this->regions = array();
  29. $this->regions[] = 'header';
  30. $this->regions[] = 'sidebar_first';
  31. $this->regions[] = 'content';
  32. $this->regions[] = 'sidebar_second';
  33. $this->regions[] = 'footer';
  34. }
  35. /**
  36. * Test creating custom block, moving it to a specific region and then deleting it.
  37. */
  38. function testCustomBlock() {
  39. // Confirm that the add block link appears on block overview pages.
  40. $this->drupalGet('admin/structure/block');
  41. $this->assertRaw(l('Add block', 'admin/structure/block/add'), 'Add block link is present on block overview page for default theme.');
  42. $this->drupalGet('admin/structure/block/list/seven');
  43. $this->assertRaw(l('Add block', 'admin/structure/block/list/seven/add'), 'Add block link is present on block overview page for non-default theme.');
  44. // Confirm that hidden regions are not shown as options for block placement
  45. // when adding a new block.
  46. theme_enable(array('stark'));
  47. $themes = list_themes();
  48. $this->drupalGet('admin/structure/block/add');
  49. foreach ($themes as $key => $theme) {
  50. if ($theme->status) {
  51. foreach ($theme->info['regions_hidden'] as $hidden_region) {
  52. $elements = $this->xpath('//select[@id=:id]//option[@value=:value]', array(':id' => 'edit-regions-' . $key, ':value' => $hidden_region));
  53. $this->assertFalse(isset($elements[0]), format_string('The hidden region @region is not available for @theme.', array('@region' => $hidden_region, '@theme' => $key)));
  54. }
  55. }
  56. }
  57. // Add a new custom block by filling out the input form on the admin/structure/block/add page.
  58. $custom_block = array();
  59. $custom_block['info'] = $this->randomName(8);
  60. $custom_block['title'] = $this->randomName(8);
  61. $custom_block['body[value]'] = $this->randomName(32);
  62. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  63. // Confirm that the custom block has been created, and then query the created bid.
  64. $this->assertText(t('The block has been created.'), 'Custom block successfully created.');
  65. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  66. // Check to see if the custom block was created by checking that it's in the database.
  67. $this->assertTrue($bid, 'Custom block found in database');
  68. // Check that block_block_view() returns the correct title and content.
  69. $data = block_block_view($bid);
  70. $format = db_query("SELECT format FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchField();
  71. $this->assertTrue(array_key_exists('subject', $data) && empty($data['subject']), 'block_block_view() provides an empty block subject, since custom blocks do not have default titles.');
  72. $this->assertEqual(check_markup($custom_block['body[value]'], $format), $data['content'], 'block_block_view() provides correct block content.');
  73. // Check whether the block can be moved to all available regions.
  74. $custom_block['module'] = 'block';
  75. $custom_block['delta'] = $bid;
  76. foreach ($this->regions as $region) {
  77. $this->moveBlockToRegion($custom_block, $region);
  78. }
  79. // Verify presence of configure and delete links for custom block.
  80. $this->drupalGet('admin/structure/block');
  81. $this->assertLinkByHref('admin/structure/block/manage/block/' . $bid . '/configure', 0, 'Custom block configure link found.');
  82. $this->assertLinkByHref('admin/structure/block/manage/block/' . $bid . '/delete', 0, 'Custom block delete link found.');
  83. // Set visibility only for authenticated users, to verify delete functionality.
  84. $edit = array();
  85. $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = TRUE;
  86. $this->drupalPost('admin/structure/block/manage/block/' . $bid . '/configure', $edit, t('Save block'));
  87. // Delete the created custom block & verify that it's been deleted and no longer appearing on the page.
  88. $this->clickLink(t('delete'));
  89. $this->drupalPost('admin/structure/block/manage/block/' . $bid . '/delete', array(), t('Delete'));
  90. $this->assertRaw(t('The block %title has been removed.', array('%title' => $custom_block['info'])), 'Custom block successfully deleted.');
  91. $this->assertNoText(t($custom_block['title']), 'Custom block no longer appears on page.');
  92. $count = db_query("SELECT 1 FROM {block_role} WHERE module = :module AND delta = :delta", array(':module' => $custom_block['module'], ':delta' => $custom_block['delta']))->fetchField();
  93. $this->assertFalse($count, 'Table block_role being cleaned.');
  94. }
  95. /**
  96. * Test creating custom block using Full HTML.
  97. */
  98. function testCustomBlockFormat() {
  99. // Add a new custom block by filling out the input form on the admin/structure/block/add page.
  100. $custom_block = array();
  101. $custom_block['info'] = $this->randomName(8);
  102. $custom_block['title'] = $this->randomName(8);
  103. $custom_block['body[value]'] = '<h1>Full HTML</h1>';
  104. $full_html_format = filter_format_load('full_html');
  105. $custom_block['body[format]'] = $full_html_format->format;
  106. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  107. // Set the created custom block to a specific region.
  108. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  109. $edit = array();
  110. $edit['blocks[block_' . $bid . '][region]'] = $this->regions[1];
  111. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  112. // Confirm that the custom block is being displayed using configured text format.
  113. $this->drupalGet('node');
  114. $this->assertRaw('<h1>Full HTML</h1>', 'Custom block successfully being displayed using Full HTML.');
  115. // Confirm that a user without access to Full HTML can not see the body field,
  116. // but can still submit the form without errors.
  117. $block_admin = $this->drupalCreateUser(array('administer blocks'));
  118. $this->drupalLogin($block_admin);
  119. $this->drupalGet('admin/structure/block/manage/block/' . $bid . '/configure');
  120. $this->assertFieldByXPath("//textarea[@name='body[value]' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Body field contains denied message');
  121. $this->drupalPost('admin/structure/block/manage/block/' . $bid . '/configure', array(), t('Save block'));
  122. $this->assertNoText(t('Ensure that each block description is unique.'));
  123. // Confirm that the custom block is still being displayed using configured text format.
  124. $this->drupalGet('node');
  125. $this->assertRaw('<h1>Full HTML</h1>', 'Custom block successfully being displayed using Full HTML.');
  126. }
  127. /**
  128. * Test block visibility.
  129. */
  130. function testBlockVisibility() {
  131. $block = array();
  132. // Create a random title for the block
  133. $title = $this->randomName(8);
  134. // Create the custom block
  135. $custom_block = array();
  136. $custom_block['info'] = $this->randomName(8);
  137. $custom_block['title'] = $title;
  138. $custom_block['body[value]'] = $this->randomName(32);
  139. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  140. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  141. $block['module'] = 'block';
  142. $block['delta'] = $bid;
  143. $block['title'] = $title;
  144. // Set the block to be hidden on any user path, and to be shown only to
  145. // authenticated users.
  146. $edit = array();
  147. $edit['pages'] = 'user*';
  148. $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = TRUE;
  149. $this->drupalPost('admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure', $edit, t('Save block'));
  150. // Move block to the first sidebar.
  151. $this->moveBlockToRegion($block, $this->regions[1]);
  152. $this->drupalGet('');
  153. $this->assertText($title, 'Block was displayed on the front page.');
  154. $this->drupalGet('user');
  155. $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
  156. $this->drupalGet('USER/' . $this->admin_user->uid);
  157. $this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
  158. // Confirm that the block is not displayed to anonymous users.
  159. $this->drupalLogout();
  160. $this->drupalGet('');
  161. $this->assertNoText($title, 'Block was not displayed to anonymous users.');
  162. }
  163. /**
  164. * Test block visibility when using "pages" restriction but leaving
  165. * "pages" textarea empty
  166. */
  167. function testBlockVisibilityListedEmpty() {
  168. $block = array();
  169. // Create a random title for the block
  170. $title = $this->randomName(8);
  171. // Create the custom block
  172. $custom_block = array();
  173. $custom_block['info'] = $this->randomName(8);
  174. $custom_block['title'] = $title;
  175. $custom_block['body[value]'] = $this->randomName(32);
  176. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  177. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  178. $block['module'] = 'block';
  179. $block['delta'] = $bid;
  180. $block['title'] = $title;
  181. // Move block to the first sidebar.
  182. $this->moveBlockToRegion($block, $this->regions[1]);
  183. // Set the block to be hidden on any user path, and to be shown only to
  184. // authenticated users.
  185. $edit = array();
  186. $edit['visibility'] = BLOCK_VISIBILITY_LISTED;
  187. $this->drupalPost('admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure', $edit, t('Save block'));
  188. $this->drupalGet('');
  189. $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
  190. $this->drupalGet('user');
  191. $this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
  192. // Confirm that the block is not displayed to anonymous users.
  193. $this->drupalLogout();
  194. $this->drupalGet('');
  195. $this->assertNoText($title, 'Block was not displayed to anonymous users.');
  196. }
  197. /**
  198. * Test user customization of block visibility.
  199. */
  200. function testBlockVisibilityPerUser() {
  201. $block = array();
  202. // Create a random title for the block.
  203. $title = $this->randomName(8);
  204. // Create our custom test block.
  205. $custom_block = array();
  206. $custom_block['info'] = $this->randomName(8);
  207. $custom_block['title'] = $title;
  208. $custom_block['body[value]'] = $this->randomName(32);
  209. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  210. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  211. $block['module'] = 'block';
  212. $block['delta'] = $bid;
  213. $block['title'] = $title;
  214. // Move block to the first sidebar.
  215. $this->moveBlockToRegion($block, $this->regions[1]);
  216. // Set the block to be customizable per user, visible by default.
  217. $edit = array();
  218. $edit['custom'] = BLOCK_CUSTOM_ENABLED;
  219. $this->drupalPost('admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure', $edit, t('Save block'));
  220. // Disable block visibility for the admin user.
  221. $edit = array();
  222. $edit['block[' . $block['module'] . '][' . $block['delta'] . ']'] = FALSE;
  223. $this->drupalPost('user/' . $this->admin_user->uid . '/edit', $edit, t('Save'));
  224. $this->drupalGet('');
  225. $this->assertNoText($block['title'], 'Block was not displayed according to per user block visibility setting.');
  226. // Set the block to be customizable per user, hidden by default.
  227. $edit = array();
  228. $edit['custom'] = BLOCK_CUSTOM_DISABLED;
  229. $this->drupalPost('admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure', $edit, t('Save block'));
  230. // Enable block visibility for the admin user.
  231. $edit = array();
  232. $edit['block[' . $block['module'] . '][' . $block['delta'] . ']'] = TRUE;
  233. $this->drupalPost('user/' . $this->admin_user->uid . '/edit', $edit, t('Save'));
  234. $this->drupalGet('');
  235. $this->assertText($block['title'], 'Block was displayed according to per user block visibility setting.');
  236. }
  237. /**
  238. * Test configuring and moving a module-define block to specific regions.
  239. */
  240. function testBlock() {
  241. // Select the Navigation block to be configured and moved.
  242. $block = array();
  243. $block['module'] = 'system';
  244. $block['delta'] = 'management';
  245. $block['title'] = $this->randomName(8);
  246. // Set block title to confirm that interface works and override any custom titles.
  247. $this->drupalPost('admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure', array('title' => $block['title']), t('Save block'));
  248. $this->assertText(t('The block configuration has been saved.'), 'Block title set.');
  249. $bid = db_query("SELECT bid FROM {block} WHERE module = :module AND delta = :delta", array(
  250. ':module' => $block['module'],
  251. ':delta' => $block['delta'],
  252. ))->fetchField();
  253. // Check to see if the block was created by checking that it's in the database.
  254. $this->assertTrue($bid, 'Block found in database');
  255. // Check whether the block can be moved to all available regions.
  256. foreach ($this->regions as $region) {
  257. $this->moveBlockToRegion($block, $region);
  258. }
  259. // Set the block to the disabled region.
  260. $edit = array();
  261. $edit['blocks[' . $block['module'] . '_' . $block['delta'] . '][region]'] = '-1';
  262. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  263. // Confirm that the block was moved to the proper region.
  264. $this->assertText(t('The block settings have been updated.'), 'Block successfully move to disabled region.');
  265. $this->assertNoText(t($block['title']), 'Block no longer appears on page.');
  266. // Confirm that the region's xpath is not available.
  267. $xpath = $this->buildXPathQuery('//div[@id=:id]/*', array(':id' => 'block-block-' . $bid));
  268. $this->assertNoFieldByXPath($xpath, FALSE, 'Custom block found in no regions.');
  269. // For convenience of developers, put the navigation block back.
  270. $edit = array();
  271. $edit['blocks[' . $block['module'] . '_' . $block['delta'] . '][region]'] = $this->regions[1];
  272. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  273. $this->assertText(t('The block settings have been updated.'), 'Block successfully move to first sidebar region.');
  274. $this->drupalPost('admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure', array('title' => 'Navigation'), t('Save block'));
  275. $this->assertText(t('The block configuration has been saved.'), 'Block title set.');
  276. }
  277. function moveBlockToRegion($block, $region) {
  278. // Set the created block to a specific region.
  279. $edit = array();
  280. $edit['blocks[' . $block['module'] . '_' . $block['delta'] . '][region]'] = $region;
  281. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  282. // Confirm that the block was moved to the proper region.
  283. $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', array( '%region_name' => $region)));
  284. // Confirm that the block is being displayed.
  285. $this->drupalGet('node');
  286. $this->assertText(t($block['title']), 'Block successfully being displayed on the page.');
  287. // Confirm that the custom block was found at the proper region.
  288. $xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', array(
  289. ':region-class' => 'region region-' . str_replace('_', '-', $region),
  290. ':block-id' => 'block-' . $block['module'] . '-' . $block['delta'],
  291. ));
  292. $this->assertFieldByXPath($xpath, NULL, format_string('Custom block found in %region_name region.', array('%region_name' => $region)));
  293. }
  294. /**
  295. * Test _block_rehash().
  296. */
  297. function testBlockRehash() {
  298. module_enable(array('block_test'));
  299. $this->assertTrue(module_exists('block_test'), 'Test block module enabled.');
  300. // Our new block should be inserted in the database when we visit the
  301. // block management page.
  302. $this->drupalGet('admin/structure/block');
  303. // Our test block's caching should default to DRUPAL_CACHE_PER_ROLE.
  304. $current_caching = db_query("SELECT cache FROM {block} WHERE module = 'block_test' AND delta = 'test_cache'")->fetchField();
  305. $this->assertEqual($current_caching, DRUPAL_CACHE_PER_ROLE, 'Test block cache mode defaults to DRUPAL_CACHE_PER_ROLE.');
  306. // Disable caching for this block.
  307. variable_set('block_test_caching', DRUPAL_NO_CACHE);
  308. // Flushing all caches should call _block_rehash().
  309. drupal_flush_all_caches();
  310. // Verify that the database is updated with the new caching mode.
  311. $current_caching = db_query("SELECT cache FROM {block} WHERE module = 'block_test' AND delta = 'test_cache'")->fetchField();
  312. $this->assertEqual($current_caching, DRUPAL_NO_CACHE, "Test block's database entry updated to DRUPAL_NO_CACHE.");
  313. }
  314. }
  315. class NonDefaultBlockAdmin extends DrupalWebTestCase {
  316. public static function getInfo() {
  317. return array(
  318. 'name' => 'Non default theme admin',
  319. 'description' => 'Check the administer page for non default theme.',
  320. 'group' => 'Block',
  321. );
  322. }
  323. /**
  324. * Test non-default theme admin.
  325. */
  326. function testNonDefaultBlockAdmin() {
  327. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes'));
  328. $this->drupalLogin($admin_user);
  329. theme_enable(array('stark'));
  330. $this->drupalGet('admin/structure/block/list/stark');
  331. }
  332. }
  333. /**
  334. * Test blocks correctly initialized when picking a new default theme.
  335. */
  336. class NewDefaultThemeBlocks extends DrupalWebTestCase {
  337. public static function getInfo() {
  338. return array(
  339. 'name' => 'New default theme blocks',
  340. 'description' => 'Checks that the new default theme gets blocks.',
  341. 'group' => 'Block',
  342. );
  343. }
  344. /**
  345. * Check the enabled Bartik blocks are correctly copied over.
  346. */
  347. function testNewDefaultThemeBlocks() {
  348. // Create administrative user.
  349. $admin_user = $this->drupalCreateUser(array('administer themes'));
  350. $this->drupalLogin($admin_user);
  351. // Ensure no other theme's blocks are in the block table yet.
  352. $themes = array();
  353. $themes['default'] = variable_get('theme_default', 'bartik');
  354. if ($admin_theme = variable_get('admin_theme')) {
  355. $themes['admin'] = $admin_theme;
  356. }
  357. $count = db_query_range('SELECT 1 FROM {block} WHERE theme NOT IN (:themes)', 0, 1, array(':themes' => $themes))->fetchField();
  358. $this->assertFalse($count, 'Only the default theme and the admin theme have blocks.');
  359. // Populate list of all blocks for matching against new theme.
  360. $blocks = array();
  361. $result = db_query('SELECT * FROM {block} WHERE theme = :theme', array(':theme' => $themes['default']));
  362. foreach ($result as $block) {
  363. // $block->theme and $block->bid will not match, so remove them.
  364. unset($block->theme, $block->bid);
  365. $blocks[$block->module][$block->delta] = $block;
  366. }
  367. // Turn on the Stark theme and ensure that it contains all of the blocks
  368. // the default theme had.
  369. theme_enable(array('stark'));
  370. variable_set('theme_default', 'stark');
  371. $result = db_query('SELECT * FROM {block} WHERE theme = :theme', array(':theme' => 'stark'));
  372. foreach ($result as $block) {
  373. unset($block->theme, $block->bid);
  374. $this->assertEqual($blocks[$block->module][$block->delta], $block, format_string('Block %name matched', array('%name' => $block->module . '-' . $block->delta)));
  375. }
  376. }
  377. }
  378. /**
  379. * Test the block system with admin themes.
  380. */
  381. class BlockAdminThemeTestCase extends DrupalWebTestCase {
  382. public static function getInfo() {
  383. return array(
  384. 'name' => 'Admin theme block admin accessibility',
  385. 'description' => "Check whether the block administer page for a disabled theme accessible if and only if it's the admin theme.",
  386. 'group' => 'Block',
  387. );
  388. }
  389. /**
  390. * Check for the accessibility of the admin theme on the block admin page.
  391. */
  392. function testAdminTheme() {
  393. // Create administrative user.
  394. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes'));
  395. $this->drupalLogin($admin_user);
  396. // Ensure that access to block admin page is denied when theme is disabled.
  397. $this->drupalGet('admin/structure/block/list/stark');
  398. $this->assertResponse(403, 'The block admin page for a disabled theme can not be accessed');
  399. // Enable admin theme and confirm that tab is accessible.
  400. $edit['admin_theme'] = 'stark';
  401. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  402. $this->drupalGet('admin/structure/block/list/stark');
  403. $this->assertResponse(200, 'The block admin page for the admin theme can be accessed');
  404. }
  405. }
  406. /**
  407. * Test block caching.
  408. */
  409. class BlockCacheTestCase extends DrupalWebTestCase {
  410. protected $admin_user;
  411. protected $normal_user;
  412. protected $normal_user_alt;
  413. public static function getInfo() {
  414. return array(
  415. 'name' => 'Block caching',
  416. 'description' => 'Test block caching.',
  417. 'group' => 'Block',
  418. );
  419. }
  420. function setUp() {
  421. parent::setUp('block_test');
  422. // Create an admin user, log in and enable test blocks.
  423. $this->admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
  424. $this->drupalLogin($this->admin_user);
  425. // Create additional users to test caching modes.
  426. $this->normal_user = $this->drupalCreateUser();
  427. $this->normal_user_alt = $this->drupalCreateUser();
  428. // Sync the roles, since drupalCreateUser() creates separate roles for
  429. // the same permission sets.
  430. user_save($this->normal_user_alt, array('roles' => $this->normal_user->roles));
  431. $this->normal_user_alt->roles = $this->normal_user->roles;
  432. // Enable block caching.
  433. variable_set('block_cache', TRUE);
  434. // Enable our test block.
  435. $edit['blocks[block_test_test_cache][region]'] = 'sidebar_first';
  436. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  437. }
  438. /**
  439. * Test DRUPAL_CACHE_PER_ROLE.
  440. */
  441. function testCachePerRole() {
  442. $this->setCacheMode(DRUPAL_CACHE_PER_ROLE);
  443. // Enable our test block. Set some content for it to display.
  444. $current_content = $this->randomName();
  445. variable_set('block_test_content', $current_content);
  446. $this->drupalLogin($this->normal_user);
  447. $this->drupalGet('');
  448. $this->assertText($current_content, 'Block content displays.');
  449. // Change the content, but the cached copy should still be served.
  450. $old_content = $current_content;
  451. $current_content = $this->randomName();
  452. variable_set('block_test_content', $current_content);
  453. $this->drupalGet('');
  454. $this->assertText($old_content, 'Block is served from the cache.');
  455. // Clear the cache and verify that the stale data is no longer there.
  456. cache_clear_all();
  457. $this->drupalGet('');
  458. $this->assertNoText($old_content, 'Block cache clear removes stale cache data.');
  459. $this->assertText($current_content, 'Fresh block content is displayed after clearing the cache.');
  460. // Test whether the cached data is served for the correct users.
  461. $old_content = $current_content;
  462. $current_content = $this->randomName();
  463. variable_set('block_test_content', $current_content);
  464. $this->drupalLogout();
  465. $this->drupalGet('');
  466. $this->assertNoText($old_content, 'Anonymous user does not see content cached per-role for normal user.');
  467. $this->drupalLogin($this->normal_user_alt);
  468. $this->drupalGet('');
  469. $this->assertText($old_content, 'User with the same roles sees per-role cached content.');
  470. $this->drupalLogin($this->admin_user);
  471. $this->drupalGet('');
  472. $this->assertNoText($old_content, 'Admin user does not see content cached per-role for normal user.');
  473. $this->drupalLogin($this->normal_user);
  474. $this->drupalGet('');
  475. $this->assertText($old_content, 'Block is served from the per-role cache.');
  476. }
  477. /**
  478. * Test DRUPAL_CACHE_GLOBAL.
  479. */
  480. function testCacheGlobal() {
  481. $this->setCacheMode(DRUPAL_CACHE_GLOBAL);
  482. $current_content = $this->randomName();
  483. variable_set('block_test_content', $current_content);
  484. $this->drupalGet('');
  485. $this->assertText($current_content, 'Block content displays.');
  486. $old_content = $current_content;
  487. $current_content = $this->randomName();
  488. variable_set('block_test_content', $current_content);
  489. $this->drupalLogout();
  490. $this->drupalGet('user');
  491. $this->assertText($old_content, 'Block content served from global cache.');
  492. }
  493. /**
  494. * Test DRUPAL_NO_CACHE.
  495. */
  496. function testNoCache() {
  497. $this->setCacheMode(DRUPAL_NO_CACHE);
  498. $current_content = $this->randomName();
  499. variable_set('block_test_content', $current_content);
  500. // If DRUPAL_NO_CACHE has no effect, the next request would be cached.
  501. $this->drupalGet('');
  502. $this->assertText($current_content, 'Block content displays.');
  503. // A cached copy should not be served.
  504. $current_content = $this->randomName();
  505. variable_set('block_test_content', $current_content);
  506. $this->drupalGet('');
  507. $this->assertText($current_content, 'DRUPAL_NO_CACHE prevents blocks from being cached.');
  508. }
  509. /**
  510. * Test DRUPAL_CACHE_PER_USER.
  511. */
  512. function testCachePerUser() {
  513. $this->setCacheMode(DRUPAL_CACHE_PER_USER);
  514. $current_content = $this->randomName();
  515. variable_set('block_test_content', $current_content);
  516. $this->drupalLogin($this->normal_user);
  517. $this->drupalGet('');
  518. $this->assertText($current_content, 'Block content displays.');
  519. $old_content = $current_content;
  520. $current_content = $this->randomName();
  521. variable_set('block_test_content', $current_content);
  522. $this->drupalGet('');
  523. $this->assertText($old_content, 'Block is served from per-user cache.');
  524. $this->drupalLogin($this->normal_user_alt);
  525. $this->drupalGet('');
  526. $this->assertText($current_content, 'Per-user block cache is not served for other users.');
  527. $this->drupalLogin($this->normal_user);
  528. $this->drupalGet('');
  529. $this->assertText($old_content, 'Per-user block cache is persistent.');
  530. }
  531. /**
  532. * Test DRUPAL_CACHE_PER_PAGE.
  533. */
  534. function testCachePerPage() {
  535. $this->setCacheMode(DRUPAL_CACHE_PER_PAGE);
  536. $current_content = $this->randomName();
  537. variable_set('block_test_content', $current_content);
  538. $this->drupalGet('node');
  539. $this->assertText($current_content, 'Block content displays on the node page.');
  540. $old_content = $current_content;
  541. $current_content = $this->randomName();
  542. variable_set('block_test_content', $current_content);
  543. $this->drupalGet('user');
  544. $this->assertNoText($old_content, 'Block content cached for the node page does not show up for the user page.');
  545. $this->drupalGet('node');
  546. $this->assertText($old_content, 'Block content cached for the node page.');
  547. }
  548. /**
  549. * Private helper method to set the test block's cache mode.
  550. */
  551. private function setCacheMode($cache_mode) {
  552. db_update('block')
  553. ->fields(array('cache' => $cache_mode))
  554. ->condition('module', 'block_test')
  555. ->execute();
  556. $current_mode = db_query("SELECT cache FROM {block} WHERE module = 'block_test'")->fetchField();
  557. if ($current_mode != $cache_mode) {
  558. $this->fail(t('Unable to set cache mode to %mode. Current mode: %current_mode', array('%mode' => $cache_mode, '%current_mode' => $current_mode)));
  559. }
  560. }
  561. }
  562. /**
  563. * Test block HTML id validity.
  564. */
  565. class BlockHTMLIdTestCase extends DrupalWebTestCase {
  566. public static function getInfo() {
  567. return array(
  568. 'name' => 'Block HTML id',
  569. 'description' => 'Test block HTML id validity.',
  570. 'group' => 'Block',
  571. );
  572. }
  573. function setUp() {
  574. parent::setUp('block_test');
  575. // Create an admin user, log in and enable test blocks.
  576. $this->admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
  577. $this->drupalLogin($this->admin_user);
  578. // Enable our test block.
  579. $edit['blocks[block_test_test_html_id][region]'] = 'sidebar_first';
  580. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  581. // Make sure the block has some content so it will appear
  582. $current_content = $this->randomName();
  583. variable_set('block_test_content', $current_content);
  584. }
  585. /**
  586. * Test valid HTML id.
  587. */
  588. function testHTMLId() {
  589. $this->drupalGet('');
  590. $this->assertRaw('block-block-test-test-html-id', 'HTML id for test block is valid.');
  591. }
  592. }
  593. /**
  594. * Unit tests for template_preprocess_block().
  595. */
  596. class BlockTemplateSuggestionsUnitTest extends DrupalUnitTestCase {
  597. public static function getInfo() {
  598. return array(
  599. 'name' => 'Block template suggestions',
  600. 'description' => 'Test the template_preprocess_block() function.',
  601. 'group' => 'Block',
  602. );
  603. }
  604. /**
  605. * Test if template_preprocess_block() handles the suggestions right.
  606. */
  607. function testBlockThemeHookSuggestions() {
  608. // Define block delta with underscore to be preprocessed
  609. $block1 = new stdClass();
  610. $block1->module = 'block';
  611. $block1->delta = 'underscore_test';
  612. $block1->region = 'footer';
  613. $variables1 = array();
  614. $variables1['elements']['#block'] = $block1;
  615. $variables1['elements']['#children'] = '';
  616. template_preprocess_block($variables1);
  617. $this->assertEqual($variables1['theme_hook_suggestions'], array('block__footer', 'block__block', 'block__block__underscore_test'), 'Found expected block suggestions for delta with underscore');
  618. // Define block delta with hyphens to be preprocessed. Hyphens should be
  619. // replaced with underscores.
  620. $block2 = new stdClass();
  621. $block2->module = 'block';
  622. $block2->delta = 'hyphen-test';
  623. $block2->region = 'footer';
  624. $variables2 = array();
  625. $variables2['elements']['#block'] = $block2;
  626. $variables2['elements']['#children'] = '';
  627. template_preprocess_block($variables2);
  628. $this->assertEqual($variables2['theme_hook_suggestions'], array('block__footer', 'block__block', 'block__block__hyphen_test'), 'Hyphens (-) in block delta were replaced by underscore (_)');
  629. }
  630. }
  631. /**
  632. * Tests for hook_block_view_MODULE_DELTA_alter().
  633. */
  634. class BlockViewModuleDeltaAlterWebTest extends DrupalWebTestCase {
  635. public static function getInfo() {
  636. return array(
  637. 'name' => 'Block view module delta alter',
  638. 'description' => 'Test the hook_block_view_MODULE_DELTA_alter() hook.',
  639. 'group' => 'Block',
  640. );
  641. }
  642. public function setUp() {
  643. parent::setUp(array('block_test'));
  644. }
  645. /**
  646. * Tests that the alter hook is called, even if the delta contains a hyphen.
  647. */
  648. public function testBlockViewModuleDeltaAlter() {
  649. $block = new stdClass;
  650. $block->module = 'block_test';
  651. $block->delta = 'test_underscore';
  652. $block->title = '';
  653. $render_array = _block_render_blocks(array('region' => $block));
  654. $render = array_pop($render_array);
  655. $test_underscore = $render->content['#markup'];
  656. $this->assertEqual($test_underscore, 'hook_block_view_MODULE_DELTA_alter', 'Found expected altered block content for delta with underscore');
  657. $block = new stdClass;
  658. $block->module = 'block_test';
  659. $block->delta = 'test-hyphen';
  660. $block->title = '';
  661. $render_array = _block_render_blocks(array('region' => $block));
  662. $render = array_pop($render_array);
  663. $test_hyphen = $render->content['#markup'];
  664. $this->assertEqual($test_hyphen, 'hook_block_view_MODULE_DELTA_alter', 'Hyphens (-) in block delta were replaced by underscore (_)');
  665. }
  666. }
  667. /**
  668. * Tests that hidden regions do not inherit blocks when a theme is enabled.
  669. */
  670. class BlockHiddenRegionTestCase extends DrupalWebTestCase {
  671. public static function getInfo() {
  672. return array(
  673. 'name' => 'Blocks not in hidden region',
  674. 'description' => 'Checks that a newly enabled theme does not inherit blocks to its hidden regions.',
  675. 'group' => 'Block',
  676. );
  677. }
  678. function setUp() {
  679. parent::setUp(array('block_test'));
  680. }
  681. /**
  682. * Tests that hidden regions do not inherit blocks when a theme is enabled.
  683. */
  684. function testBlockNotInHiddenRegion() {
  685. // Create administrative user.
  686. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes', 'search content'));
  687. $this->drupalLogin($admin_user);
  688. // Enable "block_test_theme" and set it as the default theme.
  689. $theme = 'block_test_theme';
  690. theme_enable(array($theme));
  691. variable_set('theme_default', $theme);
  692. menu_rebuild();
  693. // Ensure that "block_test_theme" is set as the default theme.
  694. $this->drupalGet('admin/structure/block');
  695. $this->assertText('Block test theme(' . t('active tab') . ')', 'Default local task on blocks admin page is the block test theme.');
  696. // Ensure that the search form block is displayed.
  697. $this->drupalGet('');
  698. $this->assertText('Search form', 'Block was displayed on the front page.');
  699. }
  700. }
  701. /**
  702. * Tests that a block assigned to an invalid region triggers the warning.
  703. */
  704. class BlockInvalidRegionTestCase extends DrupalWebTestCase {
  705. public static function getInfo() {
  706. return array(
  707. 'name' => 'Blocks in invalid regions',
  708. 'description' => 'Checks that an active block assigned to a non-existing region triggers the warning message and is disabled.',
  709. 'group' => 'Block',
  710. );
  711. }
  712. function setUp() {
  713. parent::setUp(array('block', 'block_test'));
  714. // Create an admin user.
  715. $admin_user = $this->drupalCreateUser(array('administer site configuration', 'access administration pages'));
  716. $this->drupalLogin($admin_user);
  717. }
  718. /**
  719. * Tests that blocks assigned to invalid regions work correctly.
  720. */
  721. function testBlockInInvalidRegion() {
  722. // Enable a test block in the default theme and place it in an invalid region.
  723. db_merge('block')
  724. ->key(array(
  725. 'module' => 'block_test',
  726. 'delta' => 'test_html_id',
  727. 'theme' => variable_get('theme_default', 'stark'),
  728. ))
  729. ->fields(array(
  730. 'status' => 1,
  731. 'region' => 'invalid_region',
  732. 'cache' => DRUPAL_NO_CACHE,
  733. ))
  734. ->execute();
  735. $warning_message = t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => t('Test block html id'), '%region' => 'invalid_region'));
  736. // Clearing the cache should disable the test block placed in the invalid region.
  737. $this->drupalPost('admin/config/development/performance', array(), 'Clear all caches');
  738. $this->assertRaw($warning_message, 'Enabled block was in the invalid region and has been disabled.');
  739. // Clear the cache to check if the warning message is not triggered.
  740. $this->drupalPost('admin/config/development/performance', array(), 'Clear all caches');
  741. $this->assertNoRaw($warning_message, 'Disabled block in the invalid region will not trigger the warning.');
  742. // Place disabled test block in the invalid region of the default theme.
  743. db_merge('block')
  744. ->key(array(
  745. 'module' => 'block_test',
  746. 'delta' => 'test_html_id',
  747. 'theme' => variable_get('theme_default', 'stark'),
  748. ))
  749. ->fields(array(
  750. 'region' => 'invalid_region',
  751. 'cache' => DRUPAL_NO_CACHE,
  752. ))
  753. ->execute();
  754. // Clear the cache to check if the warning message is not triggered.
  755. $this->drupalPost('admin/config/development/performance', array(), 'Clear all caches');
  756. $this->assertNoRaw($warning_message, 'Disabled block in the invalid region will not trigger the warning.');
  757. }
  758. }
  759. /**
  760. * Tests that block rehashing works correctly.
  761. */
  762. class BlockHashTestCase extends DrupalWebTestCase {
  763. public static function getInfo() {
  764. return array(
  765. 'name' => 'Block rehash',
  766. 'description' => 'Checks _block_rehash() functionality.',
  767. 'group' => 'Block',
  768. );
  769. }
  770. function setUp() {
  771. parent::setUp(array('block'));
  772. }
  773. /**
  774. * Tests that block rehashing does not write to the database too often.
  775. */
  776. function testBlockRehash() {
  777. // No hook_block_info_alter(), no save.
  778. $this->doRehash();
  779. module_enable(array('block_test'), FALSE);
  780. // Save the new blocks, check that the new blocks exist by checking weight.
  781. _block_rehash();
  782. $this->assertWeight(0);
  783. // Now hook_block_info_alter() exists but no blocks are saved on a second
  784. // rehash.
  785. $this->doRehash();
  786. $this->assertWeight(0);
  787. // Now hook_block_info_alter() exists and is changing one block which
  788. // should be saved.
  789. $GLOBALS['conf']['block_test_info_alter'] = 1;
  790. $this->doRehash(TRUE);
  791. $this->assertWeight(10000);
  792. // Now hook_block_info_alter() exists but already changed the block's
  793. // weight before, so it should not be saved again.
  794. $this->doRehash();
  795. $this->assertWeight(10000);
  796. }
  797. /**
  798. * Performs a block rehash and checks several related assertions.
  799. *
  800. * @param $alter_active
  801. * Set to TRUE if the block_test module's hook_block_info_alter()
  802. * implementation is expected to make a change that results in an existing
  803. * block needing to be resaved to the database. Defaults to FALSE.
  804. */
  805. function doRehash($alter_active = FALSE) {
  806. $saves = 0;
  807. foreach (_block_rehash() as $block) {
  808. $module = $block['module'];
  809. $delta = $block['delta'];
  810. if ($alter_active && $module == 'block_test' && $delta == 'test_html_id') {
  811. $this->assertFalse(empty($block['saved']), "$module $delta saved");
  812. $saves++;
  813. }
  814. else {
  815. $this->assertTrue(empty($block['saved']), "$module $delta not saved");
  816. }
  817. }
  818. $this->assertEqual($alter_active, $saves);
  819. }
  820. /**
  821. * Asserts that the block_test module's block has a given weight.
  822. *
  823. * @param $weight
  824. * The expected weight.
  825. */
  826. function assertWeight($weight) {
  827. $db_weight = db_query('SELECT weight FROM {block} WHERE module = :module AND delta = :delta', array(':module' => 'block_test', ':delta' => 'test_html_id'))->fetchField();
  828. // By casting to string the assert fails on FALSE.
  829. $this->assertIdentical((string) $db_weight, (string) $weight);
  830. }
  831. }