bootstrap.test 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. <?php
  2. class BootstrapIPAddressTestCase extends DrupalWebTestCase {
  3. public static function getInfo() {
  4. return array(
  5. 'name' => 'IP address and HTTP_HOST test',
  6. 'description' => 'Get the IP address from the current visitor from the server variables, check hostname validation.',
  7. 'group' => 'Bootstrap'
  8. );
  9. }
  10. function setUp() {
  11. $this->oldserver = $_SERVER;
  12. $this->remote_ip = '127.0.0.1';
  13. $this->proxy_ip = '127.0.0.2';
  14. $this->proxy2_ip = '127.0.0.3';
  15. $this->forwarded_ip = '127.0.0.4';
  16. $this->cluster_ip = '127.0.0.5';
  17. $this->untrusted_ip = '0.0.0.0';
  18. drupal_static_reset('ip_address');
  19. $_SERVER['REMOTE_ADDR'] = $this->remote_ip;
  20. unset($_SERVER['HTTP_X_FORWARDED_FOR']);
  21. unset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']);
  22. parent::setUp();
  23. }
  24. function tearDown() {
  25. $_SERVER = $this->oldserver;
  26. drupal_static_reset('ip_address');
  27. parent::tearDown();
  28. }
  29. /**
  30. * test IP Address and hostname
  31. */
  32. function testIPAddressHost() {
  33. // Test the normal IP address.
  34. $this->assertTrue(
  35. ip_address() == $this->remote_ip,
  36. 'Got remote IP address.'
  37. );
  38. // Proxy forwarding on but no proxy addresses defined.
  39. variable_set('reverse_proxy', 1);
  40. $this->assertTrue(
  41. ip_address() == $this->remote_ip,
  42. 'Proxy forwarding without trusted proxies got remote IP address.'
  43. );
  44. // Proxy forwarding on and proxy address not trusted.
  45. variable_set('reverse_proxy_addresses', array($this->proxy_ip, $this->proxy2_ip));
  46. drupal_static_reset('ip_address');
  47. $_SERVER['REMOTE_ADDR'] = $this->untrusted_ip;
  48. $this->assertTrue(
  49. ip_address() == $this->untrusted_ip,
  50. 'Proxy forwarding with untrusted proxy got remote IP address.'
  51. );
  52. // Proxy forwarding on and proxy address trusted.
  53. $_SERVER['REMOTE_ADDR'] = $this->proxy_ip;
  54. $_SERVER['HTTP_X_FORWARDED_FOR'] = $this->forwarded_ip;
  55. drupal_static_reset('ip_address');
  56. $this->assertTrue(
  57. ip_address() == $this->forwarded_ip,
  58. 'Proxy forwarding with trusted proxy got forwarded IP address.'
  59. );
  60. // Multi-tier architecture with comma separated values in header.
  61. $_SERVER['REMOTE_ADDR'] = $this->proxy_ip;
  62. $_SERVER['HTTP_X_FORWARDED_FOR'] = implode(', ', array($this->untrusted_ip, $this->forwarded_ip, $this->proxy2_ip));
  63. drupal_static_reset('ip_address');
  64. $this->assertTrue(
  65. ip_address() == $this->forwarded_ip,
  66. 'Proxy forwarding with trusted 2-tier proxy got forwarded IP address.'
  67. );
  68. // Custom client-IP header.
  69. variable_set('reverse_proxy_header', 'HTTP_X_CLUSTER_CLIENT_IP');
  70. $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'] = $this->cluster_ip;
  71. drupal_static_reset('ip_address');
  72. $this->assertTrue(
  73. ip_address() == $this->cluster_ip,
  74. 'Cluster environment got cluster client IP.'
  75. );
  76. // Verifies that drupal_valid_http_host() prevents invalid characters.
  77. $this->assertFalse(drupal_valid_http_host('security/.drupal.org:80'), 'HTTP_HOST with / is invalid');
  78. $this->assertFalse(drupal_valid_http_host('security\\.drupal.org:80'), 'HTTP_HOST with \\ is invalid');
  79. $this->assertFalse(drupal_valid_http_host('security<.drupal.org:80'), 'HTTP_HOST with &lt; is invalid');
  80. $this->assertFalse(drupal_valid_http_host('security..drupal.org:80'), 'HTTP_HOST with .. is invalid');
  81. // Verifies that host names are shorter than 1000 characters.
  82. $this->assertFalse(drupal_valid_http_host(str_repeat('x', 1001)), 'HTTP_HOST with more than 1000 characters is invalid.');
  83. $this->assertFalse(drupal_valid_http_host(str_repeat('.', 101)), 'HTTP_HOST with more than 100 subdomains is invalid.');
  84. $this->assertFalse(drupal_valid_http_host(str_repeat(':', 101)), 'HTTP_HOST with more than 100 portseparators is invalid.');
  85. // IPv6 loopback address
  86. $this->assertTrue(drupal_valid_http_host('[::1]:80'), 'HTTP_HOST containing IPv6 loopback is valid');
  87. }
  88. }
  89. class BootstrapPageCacheTestCase extends DrupalWebTestCase {
  90. public static function getInfo() {
  91. return array(
  92. 'name' => 'Page cache test',
  93. 'description' => 'Enable the page cache and test it with various HTTP requests.',
  94. 'group' => 'Bootstrap'
  95. );
  96. }
  97. function setUp() {
  98. parent::setUp('system_test');
  99. }
  100. /**
  101. * Test support for requests containing If-Modified-Since and If-None-Match headers.
  102. */
  103. function testConditionalRequests() {
  104. variable_set('cache', 1);
  105. // Fill the cache.
  106. $this->drupalGet('');
  107. $this->drupalHead('');
  108. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  109. $etag = $this->drupalGetHeader('ETag');
  110. $last_modified = $this->drupalGetHeader('Last-Modified');
  111. $this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified, 'If-None-Match: ' . $etag));
  112. $this->assertResponse(304, 'Conditional request returned 304 Not Modified.');
  113. $this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC822, strtotime($last_modified)), 'If-None-Match: ' . $etag));
  114. $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
  115. $this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC850, strtotime($last_modified)), 'If-None-Match: ' . $etag));
  116. $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
  117. $this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified));
  118. $this->assertResponse(200, 'Conditional request without If-None-Match returned 200 OK.');
  119. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  120. $this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC7231, strtotime($last_modified) + 1), 'If-None-Match: ' . $etag));
  121. $this->assertResponse(200, 'Conditional request with new a If-Modified-Since date newer than Last-Modified returned 200 OK.');
  122. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  123. $user = $this->drupalCreateUser();
  124. $this->drupalLogin($user);
  125. $this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified, 'If-None-Match: ' . $etag));
  126. $this->assertResponse(200, 'Conditional request returned 200 OK for authenticated user.');
  127. $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Absence of Page was not cached.');
  128. $this->assertFalse($this->drupalGetHeader('ETag'), 'ETag HTTP headers are not present for logged in users.');
  129. $this->assertFalse($this->drupalGetHeader('Last-Modified'), 'Last-Modified HTTP headers are not present for logged in users.');
  130. }
  131. /**
  132. * Test cache headers.
  133. */
  134. function testPageCache() {
  135. variable_set('cache', 1);
  136. // Fill the cache.
  137. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
  138. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  139. $this->assertEqual($this->drupalGetHeader('Vary'), 'Cookie,Accept-Encoding', 'Vary header was sent.');
  140. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'public, max-age=0', 'Cache-Control header was sent.');
  141. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  142. $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
  143. // Check cache.
  144. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
  145. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  146. $this->assertEqual($this->drupalGetHeader('Vary'), 'Cookie,Accept-Encoding', 'Vary: Cookie header was sent.');
  147. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'public, max-age=0', 'Cache-Control header was sent.');
  148. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  149. $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
  150. // Check replacing default headers.
  151. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Expires', 'value' => 'Fri, 19 Nov 2008 05:00:00 GMT')));
  152. $this->assertEqual($this->drupalGetHeader('Expires'), 'Fri, 19 Nov 2008 05:00:00 GMT', 'Default header was replaced.');
  153. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Vary', 'value' => 'User-Agent')));
  154. $this->assertEqual($this->drupalGetHeader('Vary'), 'User-Agent,Accept-Encoding', 'Default header was replaced.');
  155. // Check that authenticated users bypass the cache.
  156. $user = $this->drupalCreateUser();
  157. $this->drupalLogin($user);
  158. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
  159. $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Caching was bypassed.');
  160. $this->assertTrue(strpos($this->drupalGetHeader('Vary'), 'Cookie') === FALSE, 'Vary: Cookie header was not sent.');
  161. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate, post-check=0, pre-check=0', 'Cache-Control header was sent.');
  162. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  163. $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
  164. }
  165. /**
  166. * Test page compression.
  167. *
  168. * The test should pass even if zlib.output_compression is enabled in php.ini,
  169. * .htaccess or similar, or if compression is done outside PHP, e.g. by the
  170. * mod_deflate Apache module.
  171. */
  172. function testPageCompression() {
  173. variable_set('cache', 1);
  174. // Fill the cache and verify that output is compressed.
  175. $this->drupalGet('', array(), array('Accept-Encoding: gzip,deflate'));
  176. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  177. $this->drupalSetContent(gzinflate(substr($this->drupalGetContent(), 10, -8)));
  178. $this->assertRaw('</html>', 'Page was gzip compressed.');
  179. // Verify that cached output is compressed.
  180. $this->drupalGet('', array(), array('Accept-Encoding: gzip,deflate'));
  181. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  182. $this->assertEqual($this->drupalGetHeader('Content-Encoding'), 'gzip', 'A Content-Encoding header was sent.');
  183. $this->drupalSetContent(gzinflate(substr($this->drupalGetContent(), 10, -8)));
  184. $this->assertRaw('</html>', 'Page was gzip compressed.');
  185. // Verify that a client without compression support gets an uncompressed page.
  186. $this->drupalGet('');
  187. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  188. $this->assertFalse($this->drupalGetHeader('Content-Encoding'), 'A Content-Encoding header was not sent.');
  189. $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
  190. $this->assertRaw('</html>', 'Page was not compressed.');
  191. // Disable compression mode.
  192. variable_set('page_compression', FALSE);
  193. // Verify if cached page is still available for a client with compression support.
  194. $this->drupalGet('', array(), array('Accept-Encoding: gzip,deflate'));
  195. $this->drupalSetContent(gzinflate(substr($this->drupalGetContent(), 10, -8)));
  196. $this->assertRaw('</html>', 'Page was delivered after compression mode is changed (compression support enabled).');
  197. // Verify if cached page is still available for a client without compression support.
  198. $this->drupalGet('');
  199. $this->assertRaw('</html>', 'Page was delivered after compression mode is changed (compression support disabled).');
  200. }
  201. }
  202. class BootstrapVariableTestCase extends DrupalWebTestCase {
  203. function setUp() {
  204. parent::setUp('system_test');
  205. }
  206. public static function getInfo() {
  207. return array(
  208. 'name' => 'Variable test',
  209. 'description' => 'Make sure the variable system functions correctly.',
  210. 'group' => 'Bootstrap'
  211. );
  212. }
  213. /**
  214. * testVariable
  215. */
  216. function testVariable() {
  217. // Setting and retrieving values.
  218. $variable = $this->randomName();
  219. variable_set('simpletest_bootstrap_variable_test', $variable);
  220. $this->assertIdentical($variable, variable_get('simpletest_bootstrap_variable_test'), 'Setting and retrieving values');
  221. // Make sure the variable persists across multiple requests.
  222. $this->drupalGet('system-test/variable-get');
  223. $this->assertText($variable, 'Variable persists across multiple requests');
  224. // Deleting variables.
  225. $default_value = $this->randomName();
  226. variable_del('simpletest_bootstrap_variable_test');
  227. $variable = variable_get('simpletest_bootstrap_variable_test', $default_value);
  228. $this->assertIdentical($variable, $default_value, 'Deleting variables');
  229. }
  230. /**
  231. * Makes sure that the default variable parameter is passed through okay.
  232. */
  233. function testVariableDefaults() {
  234. // Tests passing nothing through to the default.
  235. $this->assertIdentical(NULL, variable_get('simpletest_bootstrap_variable_test'), 'Variables are correctly defaulting to NULL.');
  236. // Tests passing 5 to the default parameter.
  237. $this->assertIdentical(5, variable_get('simpletest_bootstrap_variable_test', 5), 'The default variable parameter is passed through correctly.');
  238. }
  239. }
  240. /**
  241. * Tests the auto-loading behavior of the code registry.
  242. */
  243. class BootstrapAutoloadTestCase extends DrupalWebTestCase {
  244. public static function getInfo() {
  245. return array(
  246. 'name' => 'Code registry',
  247. 'description' => 'Test that the code registry functions correctly.',
  248. 'group' => 'Bootstrap',
  249. );
  250. }
  251. function setUp() {
  252. parent::setUp('drupal_autoload_test');
  253. }
  254. /**
  255. * Tests that autoloader name matching is not case sensitive.
  256. */
  257. function testAutoloadCase() {
  258. // Test interface autoloader.
  259. $this->assertTrue(drupal_autoload_interface('drupalautoloadtestinterface'), 'drupal_autoload_interface() recognizes <em>DrupalAutoloadTestInterface</em> in lower case.');
  260. // Test class autoloader.
  261. $this->assertTrue(drupal_autoload_class('drupalautoloadtestclass'), 'drupal_autoload_class() recognizes <em>DrupalAutoloadTestClass</em> in lower case.');
  262. // Test trait autoloader.
  263. if (version_compare(PHP_VERSION, '5.4') >= 0) {
  264. $this->assertTrue(drupal_autoload_trait('drupalautoloadtesttrait'), 'drupal_autoload_trait() recognizes <em>DrupalAutoloadTestTrait</em> in lower case.');
  265. }
  266. }
  267. }
  268. /**
  269. * Test hook_boot() and hook_exit().
  270. */
  271. class HookBootExitTestCase extends DrupalWebTestCase {
  272. public static function getInfo() {
  273. return array(
  274. 'name' => 'Boot and exit hook invocation',
  275. 'description' => 'Test that hook_boot() and hook_exit() are called correctly.',
  276. 'group' => 'Bootstrap',
  277. );
  278. }
  279. function setUp() {
  280. parent::setUp('system_test', 'dblog');
  281. }
  282. /**
  283. * Test calling of hook_boot() and hook_exit().
  284. */
  285. function testHookBootExit() {
  286. // Test with cache disabled. Boot and exit should always fire.
  287. variable_set('cache', 0);
  288. $this->drupalGet('');
  289. $calls = 1;
  290. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot called with disabled cache.'));
  291. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit called with disabled cache.'));
  292. // Test with normal cache. Boot and exit should be called.
  293. variable_set('cache', 1);
  294. $this->drupalGet('');
  295. $calls++;
  296. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot called with normal cache.'));
  297. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit called with normal cache.'));
  298. // Boot and exit should not fire since the page is cached.
  299. variable_set('page_cache_invoke_hooks', FALSE);
  300. $this->assertTrue(cache_get(url('', array('absolute' => TRUE)), 'cache_page'), t('Page has been cached.'));
  301. $this->drupalGet('');
  302. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot not called with aggressive cache and a cached page.'));
  303. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit not called with aggressive cache and a cached page.'));
  304. // Test with page cache cleared, boot and exit should be called.
  305. $this->assertTrue(db_delete('cache_page')->execute(), t('Page cache cleared.'));
  306. $this->drupalGet('');
  307. $calls++;
  308. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot called with aggressive cache and no cached page.'));
  309. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit called with aggressive cache and no cached page.'));
  310. }
  311. }
  312. /**
  313. * Test drupal_get_filename()'s availability.
  314. */
  315. class BootstrapGetFilenameTestCase extends DrupalUnitTestCase {
  316. public static function getInfo() {
  317. return array(
  318. 'name' => 'Get filename test',
  319. 'description' => 'Test that drupal_get_filename() works correctly when the file is not found in the database.',
  320. 'group' => 'Bootstrap',
  321. );
  322. }
  323. /**
  324. * Test that drupal_get_filename() works correctly when the file is not found in the database.
  325. */
  326. function testDrupalGetFilename() {
  327. // Reset the static cache so we can test the "db is not active" code of
  328. // drupal_get_filename().
  329. drupal_static_reset('drupal_get_filename');
  330. // Retrieving the location of a module.
  331. $this->assertIdentical(drupal_get_filename('module', 'php'), 'modules/php/php.module', t('Retrieve module location.'));
  332. // Retrieving the location of a theme.
  333. $this->assertIdentical(drupal_get_filename('theme', 'stark'), 'themes/stark/stark.info', t('Retrieve theme location.'));
  334. // Retrieving the location of a theme engine.
  335. $this->assertIdentical(drupal_get_filename('theme_engine', 'phptemplate'), 'themes/engines/phptemplate/phptemplate.engine', t('Retrieve theme engine location.'));
  336. // Retrieving the location of a profile. Profiles are a special case with
  337. // a fixed location and naming.
  338. $this->assertIdentical(drupal_get_filename('profile', 'standard'), 'profiles/standard/standard.profile', t('Retrieve install profile location.'));
  339. // When a file is not found in the database cache, drupal_get_filename()
  340. // searches several locations on the filesystem, including the DRUPAL_ROOT
  341. // directory. We use the '.script' extension below because this is a
  342. // non-existent filetype that will definitely not exist in the database.
  343. // Since there is already a scripts directory, drupal_get_filename() will
  344. // automatically check there for 'script' files, just as it does for (e.g.)
  345. // 'module' files in modules.
  346. $this->assertIdentical(drupal_get_filename('script', 'test'), 'scripts/test.script', t('Retrieve test script location.'));
  347. }
  348. }
  349. class BootstrapTimerTestCase extends DrupalUnitTestCase {
  350. public static function getInfo() {
  351. return array(
  352. 'name' => 'Timer test',
  353. 'description' => 'Test that timer_read() works both when a timer is running and when a timer is stopped.',
  354. 'group' => 'Bootstrap',
  355. );
  356. }
  357. /**
  358. * Test timer_read() to ensure it properly accumulates time when the timer
  359. * started and stopped multiple times.
  360. * @return
  361. */
  362. function testTimer() {
  363. timer_start('test');
  364. sleep(1);
  365. $this->assertTrue(timer_read('test') >= 1000, 'Timer measured 1 second of sleeping while running.');
  366. sleep(1);
  367. timer_stop('test');
  368. $this->assertTrue(timer_read('test') >= 2000, 'Timer measured 2 seconds of sleeping after being stopped.');
  369. timer_start('test');
  370. sleep(1);
  371. $this->assertTrue(timer_read('test') >= 3000, 'Timer measured 3 seconds of sleeping after being restarted.');
  372. sleep(1);
  373. $timer = timer_stop('test');
  374. $this->assertTrue(timer_read('test') >= 4000, 'Timer measured 4 seconds of sleeping after being stopped for a second time.');
  375. $this->assertEqual($timer['count'], 2, 'Timer counted 2 instances of being started.');
  376. }
  377. }
  378. /**
  379. * Test that resetting static variables works.
  380. */
  381. class BootstrapResettableStaticTestCase extends DrupalUnitTestCase {
  382. public static function getInfo() {
  383. return array(
  384. 'name' => 'Resettable static variables test',
  385. 'description' => 'Test that drupal_static() and drupal_static_reset() work.',
  386. 'group' => 'Bootstrap',
  387. );
  388. }
  389. /**
  390. * Test that a variable reference returned by drupal_static() gets reset when
  391. * drupal_static_reset() is called.
  392. */
  393. function testDrupalStatic() {
  394. $name = __CLASS__ . '_' . __METHOD__;
  395. $var = &drupal_static($name, 'foo');
  396. $this->assertEqual($var, 'foo', 'Variable returned by drupal_static() was set to its default.');
  397. // Call the specific reset and the global reset each twice to ensure that
  398. // multiple resets can be issued without odd side effects.
  399. $var = 'bar';
  400. drupal_static_reset($name);
  401. $this->assertEqual($var, 'foo', 'Variable was reset after first invocation of name-specific reset.');
  402. $var = 'bar';
  403. drupal_static_reset($name);
  404. $this->assertEqual($var, 'foo', 'Variable was reset after second invocation of name-specific reset.');
  405. $var = 'bar';
  406. drupal_static_reset();
  407. $this->assertEqual($var, 'foo', 'Variable was reset after first invocation of global reset.');
  408. $var = 'bar';
  409. drupal_static_reset();
  410. $this->assertEqual($var, 'foo', 'Variable was reset after second invocation of global reset.');
  411. }
  412. }
  413. /**
  414. * Test miscellaneous functions in bootstrap.inc.
  415. */
  416. class BootstrapMiscTestCase extends DrupalUnitTestCase {
  417. public static function getInfo() {
  418. return array(
  419. 'name' => 'Miscellaneous bootstrap unit tests',
  420. 'description' => 'Test miscellaneous functions in bootstrap.inc.',
  421. 'group' => 'Bootstrap',
  422. );
  423. }
  424. /**
  425. * Test miscellaneous functions in bootstrap.inc.
  426. */
  427. function testMisc() {
  428. // Test drupal_array_merge_deep().
  429. $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => 'X', 'class' => array('a', 'b')), 'language' => 'en');
  430. $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => 'Y', 'class' => array('c', 'd')), 'html' => TRUE);
  431. $expected = array('fragment' => 'y', 'attributes' => array('title' => 'Y', 'class' => array('a', 'b', 'c', 'd')), 'language' => 'en', 'html' => TRUE);
  432. $this->assertIdentical(drupal_array_merge_deep($link_options_1, $link_options_2), $expected, 'drupal_array_merge_deep() returned a properly merged array.');
  433. }
  434. /**
  435. * Tests that the drupal_check_memory_limit() function works as expected.
  436. */
  437. function testCheckMemoryLimit() {
  438. $memory_limit = ini_get('memory_limit');
  439. // Test that a very reasonable amount of memory is available.
  440. $this->assertTrue(drupal_check_memory_limit('30MB'), '30MB of memory tested available.');
  441. // Get the available memory and multiply it by two to make it unreasonably
  442. // high.
  443. $twice_avail_memory = ($memory_limit * 2) . 'MB';
  444. // The function should always return true if the memory limit is set to -1.
  445. $this->assertTrue(drupal_check_memory_limit($twice_avail_memory, -1), 'drupal_check_memory_limit() returns TRUE when a limit of -1 (none) is supplied');
  446. // Test that even though we have 30MB of memory available - the function
  447. // returns FALSE when given an upper limit for how much memory can be used.
  448. $this->assertFalse(drupal_check_memory_limit('30MB', '16MB'), 'drupal_check_memory_limit() returns FALSE with a 16MB upper limit on a 30MB requirement.');
  449. // Test that an equal amount of memory to the amount requested returns TRUE.
  450. $this->assertTrue(drupal_check_memory_limit('30MB', '30MB'), 'drupal_check_memory_limit() returns TRUE when requesting 30MB on a 30MB requirement.');
  451. }
  452. }
  453. /**
  454. * Tests for overriding server variables via the API.
  455. */
  456. class BootstrapOverrideServerVariablesTestCase extends DrupalUnitTestCase {
  457. public static function getInfo() {
  458. return array(
  459. 'name' => 'Overriding server variables',
  460. 'description' => 'Test that drupal_override_server_variables() works correctly.',
  461. 'group' => 'Bootstrap',
  462. );
  463. }
  464. /**
  465. * Test providing a direct URL to to drupal_override_server_variables().
  466. */
  467. function testDrupalOverrideServerVariablesProvidedURL() {
  468. $tests = array(
  469. 'http://example.com' => array(
  470. 'HTTP_HOST' => 'example.com',
  471. 'SCRIPT_NAME' => isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : NULL,
  472. ),
  473. 'http://example.com/index.php' => array(
  474. 'HTTP_HOST' => 'example.com',
  475. 'SCRIPT_NAME' => '/index.php',
  476. ),
  477. 'http://example.com/subdirectory/index.php' => array(
  478. 'HTTP_HOST' => 'example.com',
  479. 'SCRIPT_NAME' => '/subdirectory/index.php',
  480. ),
  481. );
  482. foreach ($tests as $url => $expected_server_values) {
  483. // Remember the original value of $_SERVER, since the function call below
  484. // will modify it.
  485. $original_server = $_SERVER;
  486. // Call drupal_override_server_variables() and ensure that all expected
  487. // $_SERVER variables were modified correctly.
  488. drupal_override_server_variables(array('url' => $url));
  489. foreach ($expected_server_values as $key => $value) {
  490. $this->assertIdentical($_SERVER[$key], $value);
  491. }
  492. // Restore the original value of $_SERVER.
  493. $_SERVER = $original_server;
  494. }
  495. }
  496. }
  497. /**
  498. * Tests for $_GET['destination'] and $_REQUEST['destination'] validation.
  499. */
  500. class BootstrapDestinationTestCase extends DrupalWebTestCase {
  501. public static function getInfo() {
  502. return array(
  503. 'name' => 'URL destination validation',
  504. 'description' => 'Test that $_GET[\'destination\'] and $_REQUEST[\'destination\'] cannot contain external URLs.',
  505. 'group' => 'Bootstrap',
  506. );
  507. }
  508. function setUp() {
  509. parent::setUp('system_test');
  510. }
  511. /**
  512. * Tests that $_GET/$_REQUEST['destination'] only contain internal URLs.
  513. *
  514. * @see _drupal_bootstrap_variables()
  515. * @see system_test_get_destination()
  516. * @see system_test_request_destination()
  517. */
  518. public function testDestination() {
  519. $test_cases = array(
  520. array(
  521. 'input' => 'node',
  522. 'output' => 'node',
  523. 'message' => "Standard internal example node path is present in the 'destination' parameter.",
  524. ),
  525. array(
  526. 'input' => '/example.com',
  527. 'output' => '/example.com',
  528. 'message' => 'Internal path with one leading slash is allowed.',
  529. ),
  530. array(
  531. 'input' => '//example.com/test',
  532. 'output' => '',
  533. 'message' => 'External URL without scheme is not allowed.',
  534. ),
  535. array(
  536. 'input' => 'example:test',
  537. 'output' => 'example:test',
  538. 'message' => 'Internal URL using a colon is allowed.',
  539. ),
  540. array(
  541. 'input' => 'http://example.com',
  542. 'output' => '',
  543. 'message' => 'External URL is not allowed.',
  544. ),
  545. array(
  546. 'input' => 'javascript:alert(0)',
  547. 'output' => 'javascript:alert(0)',
  548. 'message' => 'Javascript URL is allowed because it is treated as an internal URL.',
  549. ),
  550. );
  551. foreach ($test_cases as $test_case) {
  552. // Test $_GET['destination'].
  553. $this->drupalGet('system-test/get-destination', array('query' => array('destination' => $test_case['input'])));
  554. $this->assertIdentical($test_case['output'], $this->drupalGetContent(), $test_case['message']);
  555. // Test $_REQUEST['destination']. There's no form to submit to, so
  556. // drupalPost() won't work here; this just tests a direct $_POST request
  557. // instead.
  558. $curl_parameters = array(
  559. CURLOPT_URL => $this->getAbsoluteUrl('system-test/request-destination'),
  560. CURLOPT_POST => TRUE,
  561. CURLOPT_POSTFIELDS => 'destination=' . urlencode($test_case['input']),
  562. CURLOPT_HTTPHEADER => array(),
  563. );
  564. $post_output = $this->curlExec($curl_parameters);
  565. $this->assertIdentical($test_case['output'], $post_output, $test_case['message']);
  566. }
  567. // Make sure that 404 pages do not populate $_GET['destination'] with
  568. // external URLs.
  569. variable_set('site_404', 'system-test/get-destination');
  570. $this->drupalGet('http://example.com', array('external' => FALSE));
  571. $this->assertIdentical('', $this->drupalGetContent(), 'External URL is not allowed on 404 pages.');
  572. }
  573. }