PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/simpletest/drupal_web_test_case.php

https://bitbucket.org/Schnitzel/osec
PHP | 2633 lines | 1075 code | 220 blank | 1338 comment | 171 complexity | 8a9cd757a72687efb698fabb5e58a772 MD5 | raw file
Possible License(s): AGPL-1.0, BSD-3-Clause, GPL-2.0, AGPL-3.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // $Id: drupal_web_test_case.php,v 1.2.2.3.2.46 2009/11/06 21:23:32 boombatower Exp $
  3. // Core: Id: drupal_web_test_case.php,v 1.146 2009/08/31 18:30:26 webchick Exp $
  4. /**
  5. * @file
  6. * Provide required modifications to Drupal 7 core DrupalWebTestCase in order
  7. * for it to function properly in Drupal 6.
  8. *
  9. * Copyright 2008-2009 by Jimmy Berry ("boombatower", http://drupal.org/user/214218)
  10. */
  11. module_load_include('function.inc', 'simpletest');
  12. /**
  13. * Base class for Drupal tests.
  14. *
  15. * Do not extend this class, use one of the subclasses in this file.
  16. */
  17. abstract class DrupalTestCase {
  18. /**
  19. * The test run ID.
  20. *
  21. * @var string
  22. */
  23. protected $testId;
  24. /**
  25. * The original database prefix, before it was changed for testing purposes.
  26. *
  27. * @var string
  28. */
  29. protected $originalPrefix = NULL;
  30. /**
  31. * The original file directory, before it was changed for testing purposes.
  32. *
  33. * @var string
  34. */
  35. protected $originalFileDirectory = NULL;
  36. /**
  37. * Time limit for the test.
  38. */
  39. protected $timeLimit = 180;
  40. /**
  41. * Current results of this test case.
  42. *
  43. * @var Array
  44. */
  45. public $results = array(
  46. '#pass' => 0,
  47. '#fail' => 0,
  48. '#exception' => 0,
  49. '#debug' => 0,
  50. );
  51. /**
  52. * Assertions thrown in that test case.
  53. *
  54. * @var Array
  55. */
  56. protected $assertions = array();
  57. /**
  58. * This class is skipped when looking for the source of an assertion.
  59. *
  60. * When displaying which function an assert comes from, it's not too useful
  61. * to see "drupalWebTestCase->drupalLogin()', we would like to see the test
  62. * that called it. So we need to skip the classes defining these helper
  63. * methods.
  64. */
  65. protected $skipClasses = array(__CLASS__ => TRUE);
  66. /**
  67. * Constructor for DrupalWebTestCase.
  68. *
  69. * @param $test_id
  70. * Tests with the same id are reported together.
  71. */
  72. public function __construct($test_id = NULL) {
  73. $this->testId = $test_id;
  74. }
  75. /**
  76. * Internal helper: stores the assert.
  77. *
  78. * @param $status
  79. * Can be 'pass', 'fail', 'exception'.
  80. * TRUE is a synonym for 'pass', FALSE for 'fail'.
  81. * @param $message
  82. * The message string.
  83. * @param $group
  84. * Which group this assert belongs to.
  85. * @param $caller
  86. * By default, the assert comes from a function whose name starts with
  87. * 'test'. Instead, you can specify where this assert originates from
  88. * by passing in an associative array as $caller. Key 'file' is
  89. * the name of the source file, 'line' is the line number and 'function'
  90. * is the caller function itself.
  91. */
  92. protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
  93. global $db_prefix;
  94. // Convert boolean status to string status.
  95. if (is_bool($status)) {
  96. $status = $status ? 'pass' : 'fail';
  97. }
  98. // Increment summary result counter.
  99. $this->results['#' . $status]++;
  100. // Get the function information about the call to the assertion method.
  101. if (!$caller) {
  102. $caller = $this->getAssertionCall();
  103. }
  104. // Switch to non-testing database to store results in.
  105. $current_db_prefix = $db_prefix;
  106. $db_prefix = $this->originalPrefix;
  107. // Creation assertion array that can be displayed while tests are running.
  108. $this->assertions[] = $assertion = array(
  109. 'test_id' => $this->testId,
  110. 'test_class' => get_class($this),
  111. 'status' => $status,
  112. 'message' => $message,
  113. 'message_group' => $group,
  114. 'function' => $caller['function'],
  115. 'line' => $caller['line'],
  116. 'file' => $caller['file'],
  117. );
  118. // Store assertion for display after the test has completed.
  119. // db_insert('simpletest')
  120. // ->fields($assertion)
  121. // ->execute();
  122. db_query("INSERT INTO {simpletest}
  123. (test_id, test_class, status, message, message_group, function, line, file)
  124. VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, '%s')", array_values($assertion));
  125. // Return to testing prefix.
  126. $db_prefix = $current_db_prefix;
  127. // We do not use a ternary operator here to allow a breakpoint on
  128. // test failure.
  129. if ($status == 'pass') {
  130. return TRUE;
  131. }
  132. else {
  133. return FALSE;
  134. }
  135. }
  136. /**
  137. * Store an assertion from outside the testing context.
  138. *
  139. * This is useful for inserting assertions that can only be recorded after
  140. * the test case has been destroyed, such as PHP fatal errors. The caller
  141. * information is not automatically gathered since the caller is most likely
  142. * inserting the assertion on behalf of other code. In all other respects
  143. * the method behaves just like DrupalTestCase::assert() in terms of storing
  144. * the assertion.
  145. *
  146. * @see DrupalTestCase::assert()
  147. */
  148. public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
  149. // Convert boolean status to string status.
  150. if (is_bool($status)) {
  151. $status = $status ? 'pass' : 'fail';
  152. }
  153. $caller += array(
  154. 'function' => t('Unknown'),
  155. 'line' => 0,
  156. 'file' => t('Unknown'),
  157. );
  158. $assertion = array(
  159. 'test_id' => $test_id,
  160. 'test_class' => $test_class,
  161. 'status' => $status,
  162. 'message' => $message,
  163. 'message_group' => $group,
  164. 'function' => $caller['function'],
  165. 'line' => $caller['line'],
  166. 'file' => $caller['file'],
  167. );
  168. // db_insert('simpletest')
  169. // ->fields($assertion)
  170. // ->execute();
  171. db_query("INSERT INTO {simpletest}
  172. (test_id, test_class, status, message, message_group, function, line, file)
  173. VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, '%s')", array_values($assertion));
  174. }
  175. /**
  176. * Cycles through backtrace until the first non-assertion method is found.
  177. *
  178. * @return
  179. * Array representing the true caller.
  180. */
  181. protected function getAssertionCall() {
  182. $backtrace = debug_backtrace();
  183. // The first element is the call. The second element is the caller.
  184. // We skip calls that occurred in one of the methods of our base classes
  185. // or in an assertion function.
  186. while (($caller = $backtrace[1]) &&
  187. ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
  188. substr($caller['function'], 0, 6) == 'assert')) {
  189. // We remove that call.
  190. array_shift($backtrace);
  191. }
  192. return _drupal_get_last_caller($backtrace);
  193. }
  194. /**
  195. * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
  196. *
  197. * @param $value
  198. * The value on which the assertion is to be done.
  199. * @param $message
  200. * The message to display along with the assertion.
  201. * @param $group
  202. * The type of assertion - examples are "Browser", "PHP".
  203. * @return
  204. * TRUE if the assertion succeeded, FALSE otherwise.
  205. */
  206. protected function assertTrue($value, $message = '', $group = 'Other') {
  207. return $this->assert((bool) $value, $message ? $message : t('Value is TRUE'), $group);
  208. }
  209. /**
  210. * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
  211. *
  212. * @param $value
  213. * The value on which the assertion is to be done.
  214. * @param $message
  215. * The message to display along with the assertion.
  216. * @param $group
  217. * The type of assertion - examples are "Browser", "PHP".
  218. * @return
  219. * TRUE if the assertion succeeded, FALSE otherwise.
  220. */
  221. protected function assertFalse($value, $message = '', $group = 'Other') {
  222. return $this->assert(!$value, $message ? $message : t('Value is FALSE'), $group);
  223. }
  224. /**
  225. * Check to see if a value is NULL.
  226. *
  227. * @param $value
  228. * The value on which the assertion is to be done.
  229. * @param $message
  230. * The message to display along with the assertion.
  231. * @param $group
  232. * The type of assertion - examples are "Browser", "PHP".
  233. * @return
  234. * TRUE if the assertion succeeded, FALSE otherwise.
  235. */
  236. protected function assertNull($value, $message = '', $group = 'Other') {
  237. return $this->assert(!isset($value), $message ? $message : t('Value is NULL'), $group);
  238. }
  239. /**
  240. * Check to see if a value is not NULL.
  241. *
  242. * @param $value
  243. * The value on which the assertion is to be done.
  244. * @param $message
  245. * The message to display along with the assertion.
  246. * @param $group
  247. * The type of assertion - examples are "Browser", "PHP".
  248. * @return
  249. * TRUE if the assertion succeeded, FALSE otherwise.
  250. */
  251. protected function assertNotNull($value, $message = '', $group = 'Other') {
  252. return $this->assert(isset($value), $message ? $message : t('Value is not NULL'), $group);
  253. }
  254. /**
  255. * Check to see if two values are equal.
  256. *
  257. * @param $first
  258. * The first value to check.
  259. * @param $second
  260. * The second value to check.
  261. * @param $message
  262. * The message to display along with the assertion.
  263. * @param $group
  264. * The type of assertion - examples are "Browser", "PHP".
  265. * @return
  266. * TRUE if the assertion succeeded, FALSE otherwise.
  267. */
  268. protected function assertEqual($first, $second, $message = '', $group = 'Other') {
  269. return $this->assert($first == $second, $message ? $message : t('First value is equal to second value'), $group);
  270. }
  271. /**
  272. * Check to see if two values are not equal.
  273. *
  274. * @param $first
  275. * The first value to check.
  276. * @param $second
  277. * The second value to check.
  278. * @param $message
  279. * The message to display along with the assertion.
  280. * @param $group
  281. * The type of assertion - examples are "Browser", "PHP".
  282. * @return
  283. * TRUE if the assertion succeeded, FALSE otherwise.
  284. */
  285. protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
  286. return $this->assert($first != $second, $message ? $message : t('First value is not equal to second value'), $group);
  287. }
  288. /**
  289. * Check to see if two values are identical.
  290. *
  291. * @param $first
  292. * The first value to check.
  293. * @param $second
  294. * The second value to check.
  295. * @param $message
  296. * The message to display along with the assertion.
  297. * @param $group
  298. * The type of assertion - examples are "Browser", "PHP".
  299. * @return
  300. * TRUE if the assertion succeeded, FALSE otherwise.
  301. */
  302. protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
  303. return $this->assert($first === $second, $message ? $message : t('First value is identical to second value'), $group);
  304. }
  305. /**
  306. * Check to see if two values are not identical.
  307. *
  308. * @param $first
  309. * The first value to check.
  310. * @param $second
  311. * The second value to check.
  312. * @param $message
  313. * The message to display along with the assertion.
  314. * @param $group
  315. * The type of assertion - examples are "Browser", "PHP".
  316. * @return
  317. * TRUE if the assertion succeeded, FALSE otherwise.
  318. */
  319. protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
  320. return $this->assert($first !== $second, $message ? $message : t('First value is not identical to second value'), $group);
  321. }
  322. /**
  323. * Fire an assertion that is always positive.
  324. *
  325. * @param $message
  326. * The message to display along with the assertion.
  327. * @param $group
  328. * The type of assertion - examples are "Browser", "PHP".
  329. * @return
  330. * TRUE.
  331. */
  332. protected function pass($message = NULL, $group = 'Other') {
  333. return $this->assert(TRUE, $message, $group);
  334. }
  335. /**
  336. * Fire an assertion that is always negative.
  337. *
  338. * @param $message
  339. * The message to display along with the assertion.
  340. * @param $group
  341. * The type of assertion - examples are "Browser", "PHP".
  342. * @return
  343. * FALSE.
  344. */
  345. protected function fail($message = NULL, $group = 'Other') {
  346. return $this->assert(FALSE, $message, $group);
  347. }
  348. /**
  349. * Fire an error assertion.
  350. *
  351. * @param $message
  352. * The message to display along with the assertion.
  353. * @param $group
  354. * The type of assertion - examples are "Browser", "PHP".
  355. * @param $caller
  356. * The caller of the error.
  357. * @return
  358. * FALSE.
  359. */
  360. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  361. if ($group == 'User notice') {
  362. // Since 'User notice' is set by trigger_error() which is used for debug
  363. // set the message to a status of 'debug'.
  364. return $this->assert('debug', $message, 'Debug', $caller);
  365. }
  366. return $this->assert('exception', $message, $group, $caller);
  367. }
  368. /**
  369. * Run all tests in this class.
  370. */
  371. public function run() {
  372. // Initialize verbose debugging.
  373. simpletest_verbose(NULL, file_directory_path(), get_class($this));
  374. // HTTP auth settings (<username>:<password>) for the simpletest browser
  375. // when sending requests to the test site.
  376. $username = variable_get('simpletest_username', NULL);
  377. $password = variable_get('simpletest_password', NULL);
  378. if ($username && $password) {
  379. $this->httpauth_credentials = $username . ':' . $password;
  380. }
  381. set_error_handler(array($this, 'errorHandler'));
  382. $methods = array();
  383. // Iterate through all the methods in this class.
  384. foreach (get_class_methods(get_class($this)) as $method) {
  385. // If the current method starts with "test", run it - it's a test.
  386. if (strtolower(substr($method, 0, 4)) == 'test') {
  387. $this->setUp();
  388. try {
  389. $this->$method();
  390. // Finish up.
  391. }
  392. catch (Exception $e) {
  393. $this->exceptionHandler($e);
  394. }
  395. $this->tearDown();
  396. }
  397. }
  398. // Clear out the error messages and restore error handler.
  399. drupal_get_messages();
  400. restore_error_handler();
  401. }
  402. /**
  403. * Handle errors.
  404. *
  405. * Because this is registered in set_error_handler(), it has to be public.
  406. * @see set_error_handler
  407. *
  408. */
  409. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  410. if ($severity & error_reporting()) {
  411. $error_map = array(
  412. E_STRICT => 'Run-time notice',
  413. E_WARNING => 'Warning',
  414. E_NOTICE => 'Notice',
  415. E_CORE_ERROR => 'Core error',
  416. E_CORE_WARNING => 'Core warning',
  417. E_USER_ERROR => 'User error',
  418. E_USER_WARNING => 'User warning',
  419. E_USER_NOTICE => 'User notice',
  420. E_RECOVERABLE_ERROR => 'Recoverable error',
  421. );
  422. $backtrace = debug_backtrace();
  423. $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
  424. }
  425. return TRUE;
  426. }
  427. /**
  428. * Handle exceptions.
  429. *
  430. * @see set_exception_handler
  431. */
  432. protected function exceptionHandler($exception) {
  433. $backtrace = $exception->getTrace();
  434. // Push on top of the backtrace the call that generated the exception.
  435. array_unshift($backtrace, array(
  436. 'line' => $exception->getLine(),
  437. 'file' => $exception->getFile(),
  438. ));
  439. $this->error($exception->getMessage(), 'Uncaught exception', _drupal_get_last_caller($backtrace));
  440. }
  441. /**
  442. * Generates a random string of ASCII characters of codes 32 to 126.
  443. *
  444. * The generated string includes alpha-numeric characters and common misc
  445. * characters. Use this method when testing general input where the content
  446. * is not restricted.
  447. *
  448. * @param $length
  449. * Length of random string to generate which will be appended to $db_prefix.
  450. * @return
  451. * Randomly generated string.
  452. */
  453. public static function randomString($length = 8) {
  454. global $db_prefix;
  455. $str = '';
  456. for ($i = 0; $i < $length; $i++) {
  457. $str .= chr(mt_rand(32, 126));
  458. }
  459. return str_replace('simpletest', 's', $db_prefix) . $str;
  460. }
  461. /**
  462. * Generates a random string containing letters and numbers.
  463. *
  464. * The letters may be upper or lower case. This method is better for
  465. * restricted inputs that do not accept certain characters. For example,
  466. * when testing input fields that require machine readable values (ie without
  467. * spaces and non-standard characters) this method is best.
  468. *
  469. * @param $length
  470. * Length of random string to generate which will be appended to $db_prefix.
  471. * @return
  472. * Randomly generated string.
  473. */
  474. public static function randomName($length = 8) {
  475. global $db_prefix;
  476. $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
  477. $max = count($values) - 1;
  478. $str = '';
  479. for ($i = 0; $i < $length; $i++) {
  480. $str .= chr($values[mt_rand(0, $max)]);
  481. }
  482. return str_replace('simpletest', 's', $db_prefix) . $str;
  483. }
  484. }
  485. /**
  486. * Test case for Drupal unit tests.
  487. *
  488. * These tests can not access the database nor files. Calling any Drupal
  489. * function that needs the database will throw exceptions. These include
  490. * watchdog(), function_exists(), module_implements(),
  491. * module_invoke_all() etc.
  492. */
  493. class DrupalUnitTestCase extends DrupalTestCase {
  494. /**
  495. * Constructor for DrupalUnitTestCase.
  496. */
  497. function __construct($test_id = NULL) {
  498. parent::__construct($test_id);
  499. $this->skipClasses[__CLASS__] = TRUE;
  500. }
  501. function setUp() {
  502. global $db_prefix, $conf;
  503. // Store necessary current values before switching to prefixed database.
  504. $this->originalPrefix = $db_prefix;
  505. $this->originalFileDirectory = file_directory_path();
  506. // Generate temporary prefixed database to ensure that tests have a clean starting point.
  507. // $db_prefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
  508. $db_prefix = $db_prefix . 'simpletest' . mt_rand(1000, 1000000);
  509. // $conf['file_public_path'] = $this->originalFileDirectory . '/' . $db_prefix;
  510. $conf['file_directory_path'] = $this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10);
  511. // If locale is enabled then t() will try to access the database and
  512. // subsequently will fail as the database is not accessible.
  513. $module_list = module_list();
  514. if (isset($module_list['locale'])) {
  515. $this->originalModuleList = $module_list;
  516. unset($module_list['locale']);
  517. module_list(TRUE, FALSE, FALSE, $module_list);
  518. }
  519. }
  520. function tearDown() {
  521. global $db_prefix, $conf;
  522. if (preg_match('/simpletest\d+/', $db_prefix)) {
  523. // $conf['file_public_path'] = $this->originalFileDirectory;
  524. $conf['file_directory_path'] = $this->originalFileDirectory;
  525. // Return the database prefix to the original.
  526. $db_prefix = $this->originalPrefix;
  527. // Restore modules if necessary.
  528. if (isset($this->originalModuleList)) {
  529. module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
  530. }
  531. }
  532. }
  533. }
  534. /**
  535. * Test case for typical Drupal tests.
  536. */
  537. class DrupalWebTestCase extends DrupalTestCase {
  538. /**
  539. * The URL currently loaded in the internal browser.
  540. *
  541. * @var string
  542. */
  543. protected $url;
  544. /**
  545. * The handle of the current cURL connection.
  546. *
  547. * @var resource
  548. */
  549. protected $curlHandle;
  550. /**
  551. * The headers of the page currently loaded in the internal browser.
  552. *
  553. * @var Array
  554. */
  555. protected $headers;
  556. /**
  557. * The content of the page currently loaded in the internal browser.
  558. *
  559. * @var string
  560. */
  561. protected $content;
  562. /**
  563. * The content of the page currently loaded in the internal browser (plain text version).
  564. *
  565. * @var string
  566. */
  567. protected $plainTextContent;
  568. /**
  569. * The parsed version of the page.
  570. *
  571. * @var SimpleXMLElement
  572. */
  573. protected $elements = NULL;
  574. /**
  575. * The current user logged in using the internal browser.
  576. *
  577. * @var bool
  578. */
  579. protected $loggedInUser = FALSE;
  580. /**
  581. * The current cookie file used by cURL.
  582. *
  583. * We do not reuse the cookies in further runs, so we do not need a file
  584. * but we still need cookie handling, so we set the jar to NULL.
  585. */
  586. protected $cookieFile = NULL;
  587. /**
  588. * Additional cURL options.
  589. *
  590. * DrupalWebTestCase itself never sets this but always obeys what is set.
  591. */
  592. protected $additionalCurlOptions = array();
  593. /**
  594. * The original user, before it was changed to a clean uid = 1 for testing purposes.
  595. *
  596. * @var object
  597. */
  598. protected $originalUser = NULL;
  599. /**
  600. * HTTP authentication credentials (<username>:<password>).
  601. */
  602. protected $httpauth_credentials = NULL;
  603. /**
  604. * The current session name, if available.
  605. */
  606. protected $session_name = NULL;
  607. /**
  608. * The current session ID, if available.
  609. */
  610. protected $session_id = NULL;
  611. /**
  612. * Constructor for DrupalWebTestCase.
  613. */
  614. function __construct($test_id = NULL) {
  615. parent::__construct($test_id);
  616. $this->skipClasses[__CLASS__] = TRUE;
  617. }
  618. /**
  619. * Get a node from the database based on its title.
  620. *
  621. * @param title
  622. * A node title, usually generated by $this->randomName().
  623. *
  624. * @return
  625. * A node object matching $title.
  626. */
  627. function drupalGetNodeByTitle($title) {
  628. // $nodes = node_load_multiple(array(), array('title' => $title));
  629. // // Load the first node returned from the database.
  630. // $returned_node = reset($nodes);
  631. // return $returned_node;
  632. return node_load(array('title' => $title));
  633. }
  634. /**
  635. * Creates a node based on default settings.
  636. *
  637. * @param $settings
  638. * An associative array of settings to change from the defaults, keys are
  639. * node properties, for example 'title' => 'Hello, world!'.
  640. * @return
  641. * Created node object.
  642. */
  643. protected function drupalCreateNode($settings = array()) {
  644. // Populate defaults array.
  645. $settings += array(
  646. // 'body' => array(FIELD_LANGUAGE_NONE => array(array())),
  647. 'body' => $this->randomName(32),
  648. 'title' => $this->randomName(8),
  649. 'comment' => 2,
  650. // 'changed' => REQUEST_TIME,
  651. 'changed' => time(),
  652. 'format' => FILTER_FORMAT_DEFAULT,
  653. 'moderate' => 0,
  654. 'promote' => 0,
  655. 'revision' => 1,
  656. 'log' => '',
  657. 'status' => 1,
  658. 'sticky' => 0,
  659. 'type' => 'page',
  660. 'revisions' => NULL,
  661. 'taxonomy' => NULL,
  662. );
  663. // Use the original node's created time for existing nodes.
  664. if (isset($settings['created']) && !isset($settings['date'])) {
  665. $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
  666. }
  667. // If the node's user uid is not specified manually, use the currently
  668. // logged in user if available, or else the user running the test.
  669. if (!isset($settings['uid'])) {
  670. if ($this->loggedInUser) {
  671. $settings['uid'] = $this->loggedInUser->uid;
  672. }
  673. else {
  674. global $user;
  675. $settings['uid'] = $user->uid;
  676. }
  677. }
  678. // // Merge body field value and format separately.
  679. // $body = array(
  680. // 'value' => $this->randomName(32),
  681. // 'format' => FILTER_FORMAT_DEFAULT
  682. // );
  683. // $settings['body'][FIELD_LANGUAGE_NONE][0] += $body;
  684. $node = (object) $settings;
  685. node_save($node);
  686. // Small hack to link revisions to our test user.
  687. // db_update('node_revision')
  688. // ->fields(array('uid' => $node->uid))
  689. // ->condition('vid', $node->vid)
  690. // ->execute();
  691. db_query('UPDATE {node_revisions} SET uid = %d WHERE vid = %d', $node->uid, $node->vid);
  692. return $node;
  693. }
  694. /**
  695. * Creates a custom content type based on default settings.
  696. *
  697. * @param $settings
  698. * An array of settings to change from the defaults.
  699. * Example: 'type' => 'foo'.
  700. * @return
  701. * Created content type.
  702. */
  703. protected function drupalCreateContentType($settings = array()) {
  704. // Find a non-existent random type name.
  705. do {
  706. // $name = strtolower($this->randomName(8));
  707. // } while (node_type_get_type($name));
  708. $name = strtolower($this->randomName(3, 'type_'));
  709. } while (node_get_types('type', $name));
  710. // Populate defaults array.
  711. $defaults = array(
  712. 'type' => $name,
  713. 'name' => $name,
  714. 'description' => '',
  715. 'help' => '',
  716. 'min_word_count' => 0, // Drupal 6.
  717. 'title_label' => 'Title',
  718. 'body_label' => 'Body',
  719. 'has_title' => 1,
  720. 'has_body' => 1,
  721. );
  722. // Imposed values for a custom type.
  723. $forced = array(
  724. 'orig_type' => '',
  725. 'old_type' => '',
  726. 'module' => 'node',
  727. 'custom' => 1,
  728. 'modified' => 1,
  729. 'locked' => 0,
  730. );
  731. $type = $forced + $settings + $defaults;
  732. $type = (object)$type;
  733. $saved_type = node_type_save($type);
  734. node_types_rebuild();
  735. menu_rebuild(); // Drupal 6.
  736. $this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
  737. // Reset permissions so that permissions for this content type are available.
  738. $this->checkPermissions(array(), TRUE);
  739. return $type;
  740. }
  741. /**
  742. * Get a list files that can be used in tests.
  743. *
  744. * @param $type
  745. * File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
  746. * @param $size
  747. * File size in bytes to match. Please check the tests/files folder.
  748. * @return
  749. * List of files that match filter.
  750. */
  751. protected function drupalGetTestFiles($type, $size = NULL) {
  752. $files = array();
  753. // Make sure type is valid.
  754. if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
  755. // Use original file directory instead of one created during setUp().
  756. $path = $this->originalFileDirectory . '/simpletest';
  757. // $files = file_scan_directory($path, '/' . $type . '\-.*/');
  758. $files = file_scan_directory($path, '' . $type . '\-.*');
  759. // If size is set then remove any files that are not of that size.
  760. if ($size !== NULL) {
  761. foreach ($files as $file) {
  762. // $stats = stat($file->uri);
  763. $stats = stat($file->filename);
  764. if ($stats['size'] != $size) {
  765. // unset($files[$file->uri]);
  766. unset($files[$file->filename]);
  767. }
  768. }
  769. }
  770. }
  771. usort($files, array($this, 'drupalCompareFiles'));
  772. return $files;
  773. }
  774. /**
  775. * Compare two files based on size and file name.
  776. */
  777. protected function drupalCompareFiles($file1, $file2) {
  778. // $compare_size = filesize($file1->uri) - filesize($file2->uri);
  779. $compare_size = filesize($file1->filename) - filesize($file2->filename);
  780. if ($compare_size) {
  781. // Sort by file size.
  782. return $compare_size;
  783. }
  784. else {
  785. // The files were the same size, so sort alphabetically.
  786. return strnatcmp($file1->name, $file2->name);
  787. }
  788. }
  789. /**
  790. * Create a user with a given set of permissions. The permissions correspond to the
  791. * names given on the privileges page.
  792. *
  793. * @param $permissions
  794. * Array of permission names to assign to user.
  795. * @return
  796. * A fully loaded user object with pass_raw property, or FALSE if account
  797. * creation fails.
  798. */
  799. protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'post comments without approval')) {
  800. // Create a role with the given permission set.
  801. if (!($rid = $this->drupalCreateRole($permissions))) {
  802. return FALSE;
  803. }
  804. // Create a user assigned to that role.
  805. $edit = array();
  806. $edit['name'] = $this->randomName();
  807. $edit['mail'] = $edit['name'] . '@example.com';
  808. $edit['roles'] = array($rid => $rid);
  809. $edit['pass'] = user_password();
  810. $edit['status'] = 1;
  811. $account = user_save('', $edit);
  812. $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
  813. if (empty($account->uid)) {
  814. return FALSE;
  815. }
  816. // Add the raw password so that we can log in as this user.
  817. $account->pass_raw = $edit['pass'];
  818. return $account;
  819. }
  820. /**
  821. * Internal helper function; Create a role with specified permissions.
  822. *
  823. * @param $permissions
  824. * Array of permission names to assign to role.
  825. * @param $name
  826. * (optional) String for the name of the role. Defaults to a random string.
  827. * @return
  828. * Role ID of newly created role, or FALSE if role creation failed.
  829. */
  830. protected function drupalCreateRole(array $permissions, $name = NULL) {
  831. // Generate random name if it was not passed.
  832. if (!$name) {
  833. $name = $this->randomName();
  834. }
  835. // Check the all the permissions strings are valid.
  836. if (!$this->checkPermissions($permissions)) {
  837. return FALSE;
  838. }
  839. // Create new role.
  840. // $role = new stdClass();
  841. // $role->name = $name;
  842. // user_role_save($role);
  843. // user_role_set_permissions($role->name, $permissions);
  844. db_query("INSERT INTO {role} (name) VALUES ('%s')", $name);
  845. $role = db_fetch_object(db_query("SELECT * FROM {role} WHERE name = '%s'", $name));
  846. $this->assertTrue(isset($role->rid), t('Created role of name: @name, id: @rid', array('@name' => $name, '@rid' => (isset($role->rid) ? $role->rid : t('-n/a-')))), t('Role'));
  847. if ($role && !empty($role->rid)) {
  848. // $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
  849. // $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
  850. // Assign permissions to role and mark it for clean-up.
  851. db_query("INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')", $role->rid, implode(', ', $permissions));
  852. $perm = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $role->rid));
  853. $this->assertTrue(count(explode(', ', $perm)) == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
  854. return $role->rid;
  855. }
  856. else {
  857. return FALSE;
  858. }
  859. }
  860. /**
  861. * Check to make sure that the array of permissions are valid.
  862. *
  863. * @param $permissions
  864. * Permissions to check.
  865. * @param $reset
  866. * Reset cached available permissions.
  867. * @return
  868. * TRUE or FALSE depending on whether the permissions are valid.
  869. */
  870. protected function checkPermissions(array $permissions, $reset = FALSE) {
  871. // $available = &drupal_static(__FUNCTION__);
  872. static $available;
  873. if (!isset($available) || $reset) {
  874. // $available = array_keys(module_invoke_all('permission'));
  875. $available = module_invoke_all('perm');
  876. }
  877. $valid = TRUE;
  878. foreach ($permissions as $permission) {
  879. if (!in_array($permission, $available)) {
  880. $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
  881. $valid = FALSE;
  882. }
  883. }
  884. return $valid;
  885. }
  886. /**
  887. * Log in a user with the internal browser.
  888. *
  889. * If a user is already logged in, then the current user is logged out before
  890. * logging in the specified user.
  891. *
  892. * Please note that neither the global $user nor the passed in user object is
  893. * populated with data of the logged in user. If you need full access to the
  894. * user object after logging in, it must be updated manually. If you also need
  895. * access to the plain-text password of the user (set by drupalCreateUser()),
  896. * e.g. to login the same user again, then it must be re-assigned manually.
  897. * For example:
  898. * @code
  899. * // Create a user.
  900. * $account = $this->drupalCreateUser(array());
  901. * $this->drupalLogin($account);
  902. * // Load real user object.
  903. * $pass_raw = $account->pass_raw;
  904. * $account = user_load($account->uid);
  905. * $account->pass_raw = $pass_raw;
  906. * @endcode
  907. *
  908. * @param $user
  909. * User object representing the user to login.
  910. *
  911. * @see drupalCreateUser()
  912. */
  913. protected function drupalLogin(stdClass $user) {
  914. if ($this->loggedInUser) {
  915. $this->drupalLogout();
  916. }
  917. $edit = array(
  918. 'name' => $user->name,
  919. 'pass' => $user->pass_raw
  920. );
  921. $this->drupalPost('user', $edit, t('Log in'));
  922. // If a "log out" link appears on the page, it is almost certainly because
  923. // the login was successful.
  924. $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
  925. if ($pass) {
  926. $this->loggedInUser = $user;
  927. }
  928. }
  929. /**
  930. * Generate a token for the currently logged in user.
  931. */
  932. protected function drupalGetToken($value = '') {
  933. $private_key = drupal_get_private_key();
  934. return md5($this->session_id . $value . $private_key);
  935. }
  936. /*
  937. * Logs a user out of the internal browser, then check the login page to confirm logout.
  938. */
  939. protected function drupalLogout() {
  940. // Make a request to the logout page, and redirect to the user page, the
  941. // idea being if you were properly logged out you should be seeing a login
  942. // screen.
  943. // $this->drupalGet('user/logout', array('query' => 'destination=user'));
  944. $this->drupalGet('logout', array('query' => 'destination=user'));
  945. $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
  946. $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
  947. if ($pass) {
  948. $this->loggedInUser = FALSE;
  949. }
  950. }
  951. /**
  952. * Generates a random database prefix, runs the install scripts on the
  953. * prefixed database and enable the specified modules. After installation
  954. * many caches are flushed and the internal browser is setup so that the
  955. * page requests will run on the new prefix. A temporary files directory
  956. * is created with the same name as the database prefix.
  957. *
  958. * @param ...
  959. * List of modules to enable for the duration of the test.
  960. */
  961. protected function setUp() {
  962. global $db_prefix, $user, $language;
  963. // Store necessary current values before switching to prefixed database.
  964. $this->originalLanguage = $language;
  965. // $this->originalLanguageDefault = variable_get('language_default');
  966. $this->originalPrefix = $db_prefix;
  967. $this->originalFileDirectory = file_directory_path();
  968. // $this->originalProfile = drupal_get_profile();
  969. $clean_url_original = variable_get('clean_url', 0);
  970. // Must reset locale here, since schema calls t(). (Drupal 6)
  971. if (module_exists('locale')) {
  972. $language = (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => '');
  973. locale(NULL, NULL, TRUE);
  974. }
  975. // Generate temporary prefixed database to ensure that tests have a clean starting point.
  976. // $db_prefix_new = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
  977. $db_prefix_new = $db_prefix . 'simpletest' . mt_rand(1000, 1000000);
  978. // Workaround to insure we init the theme layer before going into prefixed
  979. // environment. (Drupal 6)
  980. $this->pass(t('Starting run with db_prefix %prefix', array('%prefix' => $db_prefix_new)), 'System');
  981. // db_update('simpletest_test_id')
  982. // ->fields(array('last_prefix' => $db_prefix_new))
  983. // ->condition('test_id', $this->testId)
  984. // ->execute();
  985. db_query("UPDATE {simpletest_test_id}
  986. SET last_prefix = '%s'
  987. WHERE test_id = %d", $db_prefix_new, $this->testId);
  988. $db_prefix = $db_prefix_new;
  989. // Create test directory ahead of installation so fatal errors and debug
  990. // information can be logged during installation process.
  991. $directory = $this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10);
  992. // file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  993. file_check_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  994. // Log fatal errors.
  995. ini_set('log_errors', 1);
  996. ini_set('error_log', $directory . '/error.log');
  997. // include_once DRUPAL_ROOT . '/includes/install.inc';
  998. include_once './includes/install.inc';
  999. drupal_install_system();
  1000. // $this->preloadRegistry();
  1001. // // Include the default profile
  1002. // variable_set('install_profile', 'default');
  1003. // $profile_details = install_profile_info('default', 'en');
  1004. // Add the specified modules to the list of modules in the default profile.
  1005. // Install the modules specified by the default profile.
  1006. // drupal_install_modules($profile_details['dependencies'], TRUE);
  1007. drupal_install_modules(drupal_verify_profile('default', 'en'));
  1008. // node_type_clear();
  1009. // Install additional modules one at a time in order to make sure that the
  1010. // list of modules is updated between each module's installation.
  1011. $modules = func_get_args();
  1012. foreach ($modules as $module) {
  1013. // drupal_install_modules(array($module), TRUE);
  1014. drupal_install_modules(array($module));
  1015. }
  1016. // Because the schema is static cached, we need to flush
  1017. // it between each run. If we don't, then it will contain
  1018. // stale data for the previous run's database prefix and all
  1019. // calls to it will fail.
  1020. drupal_get_schema(NULL, TRUE);
  1021. // Run default profile tasks.
  1022. // $install_state = array();
  1023. // drupal_install_modules(array('default'), TRUE);
  1024. $task = 'profile';
  1025. default_profile_tasks($task, '');
  1026. // Rebuild caches.
  1027. // node_types_rebuild();
  1028. actions_synchronize();
  1029. _drupal_flush_css_js();
  1030. $this->refreshVariables();
  1031. $this->checkPermissions(array(), TRUE);
  1032. user_access(NULL, NULL, TRUE); // Drupal 6.
  1033. // Log in with a clean $user.
  1034. $this->originalUser = $user;
  1035. // drupal_save_session(FALSE);
  1036. // $user = user_load(1);
  1037. session_save_session(FALSE);
  1038. $user = user_load(array('uid' => 1));
  1039. // Restore necessary variables.
  1040. variable_set('install_profile', 'default');
  1041. // variable_set('install_task', 'done');
  1042. variable_set('install_task', 'profile-finished');
  1043. variable_set('clean_url', $clean_url_original);
  1044. variable_set('site_mail', 'simpletest@example.com');
  1045. // // Set up English language.
  1046. // unset($GLOBALS['conf']['language_default']);
  1047. // $language = language_default();
  1048. // Use the test mail class instead of the default mail handler class.
  1049. // variable_set('mail_sending_system', array('default-system' => 'TestingMailSystem'));
  1050. variable_set('smtp_library', drupal_get_path('module', 'simpletest') . '/simpletest.mail.inc');
  1051. // Use temporary files directory with the same prefix as the database.
  1052. // $public_files_directory = $this->originalFileDirectory . '/' . $db_prefix;
  1053. // $private_files_directory = $public_files_directory . '/private';
  1054. $directory = $this->originalFileDirectory . '/' . $db_prefix;
  1055. // Set path variables
  1056. // variable_set('file_public_path', $public_files_directory);
  1057. // variable_set('file_private_path', $private_files_directory);
  1058. variable_set('file_directory_path', $directory);
  1059. // Create the directories
  1060. // $directory = file_directory_path('public');
  1061. // file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1062. // file_prepare_directory($private_files_directory, FILE_CREATE_DIRECTORY);
  1063. file_check_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1064. // drupal_set_time_limit($this->timeLimit);
  1065. set_time_limit($this->timeLimit);
  1066. }
  1067. // /**
  1068. // * This method is called by DrupalWebTestCase::setUp, and preloads the
  1069. // * registry from the testing site to cut down on the time it takes to
  1070. // * setup a clean environment for the current test run.
  1071. // */
  1072. // protected function preloadRegistry() {
  1073. // db_query('INSERT INTO {registry} SELECT * FROM ' . $this->originalPrefix . 'registry');
  1074. // db_query('INSERT INTO {registry_file} SELECT * FROM ' . $this->originalPrefix . 'registry_file');
  1075. // }
  1076. /**
  1077. * Refresh the in-memory set of variables. Useful after a page request is made
  1078. * that changes a variable in a different thread.
  1079. *
  1080. * In other words calling a settings page with $this->drupalPost() with a changed
  1081. * value would update a variable to reflect that change, but in the thread that
  1082. * made the call (thread running the test) the changed variable would not be
  1083. * picked up.
  1084. *
  1085. * This method clears the variables cache and loads a fresh copy from the database
  1086. * to ensure that the most up-to-date set of variables is loaded.
  1087. */
  1088. protected function refreshVariables() {
  1089. global $conf;
  1090. cache_clear_all('variables', 'cache');
  1091. // $conf = variable_initialize();
  1092. $conf = variable_init();
  1093. }
  1094. /**
  1095. * Delete created files and temporary files directory, delete the tables created by setUp(),
  1096. * and reset the database prefix.
  1097. */
  1098. protected function tearDown() {
  1099. global $db_prefix, $user, $language;
  1100. // In case a fatal error occured that was not in the test process read the
  1101. // log to pick up any fatal errors.
  1102. $db_prefix_temp = $db_prefix;
  1103. $db_prefix = $this->originalPrefix;
  1104. simpletest_log_read($this->testId, $db_prefix, get_class($this), TRUE);
  1105. $db_prefix = $db_prefix_temp;
  1106. $emailCount = count(variable_get('drupal_test_email_collector', array()));
  1107. if ($emailCount) {
  1108. $message = format_plural($emailCount, t('!count e-mail was sent during this test.'), t('!count e-mails were sent during this test.'), array('!count' => $emailCount));
  1109. $this->pass($message, t('E-mail'));
  1110. }
  1111. if (preg_match('/simpletest\d+/', $db_prefix)) {
  1112. // Delete temporary files directory.
  1113. // file_unmanaged_delete_recursive(file_directory_path());
  1114. simpletest_clean_temporary_directory(file_directory_path());
  1115. // Remove all prefixed tables (all the tables in the schema).
  1116. $schema = drupal_get_schema(NULL, TRUE);
  1117. $ret = array();
  1118. foreach ($schema as $name => $table) {
  1119. db_drop_table($ret, $name);
  1120. }
  1121. // Return the database prefix to the original.
  1122. $db_prefix = $this->originalPrefix;
  1123. // Return the user to the original one.
  1124. $user = $this->originalUser;
  1125. // drupal_save_session(TRUE);
  1126. session_save_session(TRUE);
  1127. // Bring back default language. (Drupal 6)
  1128. if (module_exists('locale')) {
  1129. drupal_init_language();
  1130. locale(NULL, NULL, TRUE);
  1131. }
  1132. // Ensure that internal logged in variable and cURL options are reset.
  1133. $this->loggedInUser = FALSE;
  1134. $this->additionalCurlOptions = array();
  1135. // Reload module list and implementations to ensure that test module hooks
  1136. // aren't called after tests.
  1137. module_list(TRUE);
  1138. // module_implements('', FALSE, TRUE);
  1139. module_implements('', '', TRUE);
  1140. // Reset the Field API.
  1141. // field_cache_clear();
  1142. // Rebuild caches.
  1143. $this->refreshVariables();
  1144. // // Reset language.
  1145. // $language = $this->originalLanguage;
  1146. // if ($this->originalLanguageDefault) {
  1147. // $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
  1148. // }
  1149. // Close the CURL handler.
  1150. $this->curlClose();
  1151. }
  1152. }
  1153. /**
  1154. * Initializes the cURL connection.
  1155. *
  1156. * If the simpletest_httpauth_credentials variable is set, this function will
  1157. * add HTTP authentication headers. This is necessary for testing sites that
  1158. * are protected by login credentials from public access.
  1159. * See the description of $curl_options for other options.
  1160. */
  1161. protected function curlInitialize() {
  1162. global $base_url, $db_prefix;
  1163. if (!isset($this->curlHandle)) {
  1164. $this->curlHandle = curl_init();
  1165. $curl_options = $this->additionalCurlOptions + array(
  1166. CURLOPT_COOKIEJAR => $this->cookieFile,
  1167. CURLOPT_URL => $base_url,
  1168. CURLOPT_FOLLOWLOCATION => TRUE,
  1169. CURLOPT_MAXREDIRS => 5,
  1170. CURLOPT_RETURNTRANSFER => TRUE,
  1171. CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on https.
  1172. CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on https.
  1173. CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
  1174. );
  1175. if (isset($this->httpauth_credentials)) {
  1176. $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
  1177. }
  1178. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1179. // By default, the child session name should be the same as the parent.
  1180. $this->session_name = session_name();
  1181. }
  1182. // We set the user agent header on each request so as to use the current
  1183. // time and a new uniqid.
  1184. if (preg_match('/simpletest\d+/', $db_prefix, $matches)) {
  1185. curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
  1186. }
  1187. }
  1188. /**
  1189. * Performs a cURL exec with the specified options after calling curlConnect().
  1190. *
  1191. * @param $curl_options
  1192. * Custom cURL options.
  1193. * @return
  1194. * Content returned from the exec.
  1195. */
  1196. protected function curlExec($curl_options) {
  1197. $this->curlInitialize();
  1198. $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
  1199. if (!empty($curl_options[CURLOPT_POST])) {
  1200. // This is a fix for the Curl library to prevent Expect: 100-continue
  1201. // headers in POST requests, that may cause unexpected HTTP response
  1202. // codes from some webservers (like lighttpd that returns a 417 error
  1203. // code). It is done by setting an empty "Expect" header field that is
  1204. // not overwritten by Curl.
  1205. $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
  1206. }
  1207. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1208. // Reset headers and the session ID.
  1209. $this->session_id = NULL;
  1210. $this->headers = array();
  1211. $this->drupalSetContent(curl_exec($this->curlHandle), curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
  1212. $message_vars = array(
  1213. '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
  1214. '@url' => $url,
  1215. '@status' => curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE),
  1216. '!length' => format_size(strlen($this->content))
  1217. );
  1218. $message = t('!method @url returned @status (!length).', $message_vars);
  1219. $this->assertTrue($this->content !== FALSE, $message, t('Browser'));
  1220. return $this->drupalGetContent();
  1221. }
  1222. /**
  1223. * Reads headers and registers errors received from the tested site.
  1224. *
  1225. * @see _drupal_log_error().
  1226. *
  1227. * @param $curlHandler
  1228. * The cURL handler.
  1229. * @param $header
  1230. * An header.
  1231. */
  1232. protected function curlHeaderCallback($curlHandler, $header) {
  1233. $this->headers[] = $header;
  1234. // Errors are being sent via X-Drupal-Assertion-* headers,
  1235. // generated by _drupal_log_error() in the exact form required
  1236. // by DrupalWebTestCase::error().
  1237. if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
  1238. // Call DrupalWebTestCase::error() with the parameters from the header.
  1239. call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
  1240. }
  1241. // Save the session cookie, if set.
  1242. if (preg_match('/^Set-Cookie: ' . preg_quote($this->session_name) . '=([a-z90-9]+)/', $header, $matches)) {
  1243. if ($matches[1] != 'deleted') {
  1244. $this->session_id = $matches[1];
  1245. }
  1246. else {
  1247. $this->session_id = NULL;
  1248. }
  1249. }
  1250. // This is required by cURL.
  1251. return strlen($header);
  1252. }
  1253. /**
  1254. * Close the cURL handler and unset the handler.
  1255. */
  1256. protected function curlClose() {
  1257. if (isset($this->curlHandle)) {
  1258. curl_close($this->curlHandle);
  1259. unset($this->curlHandle);
  1260. }
  1261. }
  1262. /**
  1263. * Parse content returned from curlExec using DOM and SimpleXML.
  1264. *
  1265. * @return
  1266. * A SimpleXMLElement or FALSE on failure.
  1267. */
  1268. protected function parse() {
  1269. if (!$this->elements) {
  1270. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1271. // them.
  1272. @$htmlDom = DOMDocument::loadHTML($this->content);
  1273. if ($htmlDom) {
  1274. $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
  1275. // It's much easier to work with simplexml than DOM, luckily enough
  1276. // we can just simply import our DOM tree.
  1277. $this->elements = simplexml_import_dom($htmlDom);
  1278. }
  1279. }
  1280. if (!$this->elements) {
  1281. $this->fail(t('Parsed page successfully.'), t('Browser'));
  1282. }
  1283. return $this->elements;
  1284. }
  1285. /**
  1286. * Retrieves a Drupal path or an absolute path.
  1287. *
  1288. * @param $path
  1289. * Drupal path or URL to load into internal browser
  1290. * @param $options
  1291. * Options to be forwarded to url().
  1292. * @param $headers
  1293. * An array containing additional HTTP request headers, each formatted as
  1294. * "name: value".
  1295. * @return
  1296. * The retrieved HTML string, also available as $this->drupalGetContent()
  1297. */
  1298. protected function drupalGet($path, array $options = array(), array $headers = array()) {
  1299. $options['absolute'] = TRUE;
  1300. // We re-using a CURL connection here. If that connection still has certain
  1301. // options set, it might change the GET into a POST. Make sure we clear out
  1302. // previous options.
  1303. $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
  1304. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  1305. // Replace original page output with new output from redirected page(s).
  1306. if (($new = $this->checkForMetaRefresh())) {
  1307. $out = $new;
  1308. }
  1309. $this->verbose('GET request to: ' . $path .
  1310. '<hr />Ending URL: ' . $this->getUrl() .
  1311. '<hr />' . $out);
  1312. return $out;
  1313. }
  1314. /**
  1315. * Execute a POST request on a Drupal page.
  1316. * It will be done as usual POST request with SimpleBrowser.
  1317. *
  1318. * @param $path
  1319. * Location of the post form. Either a Drupal path or an absolute path or
  1320. * NULL to post to the current page. For multi-stage forms you can set the
  1321. * path to NULL and have it post to the last received page. Example:
  1322. *
  1323. * // First…

Large files files are truncated, but you can click here to view the full file