PageRenderTime 71ms CodeModel.GetById 33ms RepoModel.GetById 0ms 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
  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 step in form.
  1324. * $edit = array(...);
  1325. * $this->drupalPost('some_url', $edit, t('Save'));
  1326. *
  1327. * // Second step in form.
  1328. * $edit = array(...);
  1329. * $this->drupalPost(NULL, $edit, t('Save'));
  1330. * @param $edit
  1331. * Field data in an associative array. Changes the current input fields
  1332. * (where possible) to the values indicated. A checkbox can be set to
  1333. * TRUE to be checked and FALSE to be unchecked. Note that when a form
  1334. * contains file upload fields, other fields cannot start with the '@'
  1335. * character.
  1336. *
  1337. * Multiple select fields can be set using name[] and setting each of the
  1338. * possible values. Example:
  1339. * $edit = array();
  1340. * $edit['name[]'] = array('value1', 'value2');
  1341. * @param $submit
  1342. * Value of the submit button.
  1343. * @param $options
  1344. * Options to be forwarded to url().
  1345. * @param $headers
  1346. * An array containing additional HTTP request headers, each formatted as
  1347. * "name: value".
  1348. */
  1349. protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array()) {
  1350. $submit_matches = FALSE;
  1351. if (isset($path)) {
  1352. $html = $this->drupalGet($path, $options);
  1353. }
  1354. if ($this->parse()) {
  1355. $edit_save = $edit;
  1356. // Let's iterate over all the forms.
  1357. $forms = $this->xpath('//form');
  1358. foreach ($forms as $form) {
  1359. // We try to set the fields of this form as specified in $edit.
  1360. $edit = $edit_save;
  1361. $post = array();
  1362. $upload = array();
  1363. $submit_matches = $this->handleForm($post, $edit, $upload, $submit, $form);
  1364. $action = isset($form['action']) ? $this->getAbsoluteUrl($form['action']) : $this->getUrl();
  1365. // We post only if we managed to handle every field in edit and the
  1366. // submit button matches.
  1367. if (!$edit && $submit_matches) {
  1368. $post_array = $post;
  1369. if ($upload) {
  1370. // TODO: cURL handles file uploads for us, but the implementation
  1371. // is broken. This is a less than elegant workaround. Alternatives
  1372. // are being explored at #253506.
  1373. foreach ($upload as $key => $file) {
  1374. // $file = drupal_realpath($file);
  1375. $file = realpath($file);
  1376. if ($file && is_file($file)) {
  1377. $post[$key] = '@' . $file;
  1378. }
  1379. }
  1380. }
  1381. else {
  1382. foreach ($post as $key => $value) {
  1383. // Encode according to application/x-www-form-urlencoded
  1384. // Both names and values needs to be urlencoded, according to
  1385. // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  1386. $post[$key] = urlencode($key) . '=' . urlencode($value);
  1387. }
  1388. $post = implode('&', $post);
  1389. }
  1390. $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
  1391. // Ensure that any changes to variables in the other thread are picked up.
  1392. $this->refreshVariables();
  1393. // Replace original page output with new output from redirected page(s).
  1394. if (($new = $this->checkForMetaRefresh())) {
  1395. $out = $new;
  1396. }
  1397. $this->verbose('POST request to: ' . $path .
  1398. '<hr />Ending URL: ' . $this->getUrl() .
  1399. '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
  1400. '<hr />' . $out);
  1401. return $out;
  1402. }
  1403. }
  1404. // We have not found a form which contained all fields of $edit.
  1405. foreach ($edit as $name => $value) {
  1406. $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
  1407. }
  1408. $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
  1409. $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
  1410. }
  1411. }
  1412. /**
  1413. * Check for meta refresh tag and if found call drupalGet() recursively. This
  1414. * function looks for the http-equiv attribute to be set to "Refresh"
  1415. * and is case-sensitive.
  1416. *
  1417. * @return
  1418. * Either the new page content or FALSE.
  1419. */
  1420. protected function checkForMetaRefresh() {
  1421. if ($this->drupalGetContent() != '' && $this->parse()) {
  1422. $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
  1423. if (!empty($refresh)) {
  1424. // Parse the content attribute of the meta tag for the format:
  1425. // "[delay]: URL=[page_to_redirect_to]".
  1426. if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
  1427. return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
  1428. }
  1429. }
  1430. }
  1431. return FALSE;
  1432. }
  1433. /**
  1434. * Retrieves only the headers for a Drupal path or an absolute path.
  1435. *
  1436. * @param $path
  1437. * Drupal path or URL to load into internal browser
  1438. * @param $options
  1439. * Options to be forwarded to url().
  1440. * @param $headers
  1441. * An array containing additional HTTP request headers, each formatted as
  1442. * "name: value".
  1443. * @return
  1444. * The retrieved headers, also available as $this->drupalGetContent()
  1445. */
  1446. protected function drupalHead($path, array $options = array(), array $headers = array()) {
  1447. $options['absolute'] = TRUE;
  1448. $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
  1449. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  1450. return $out;
  1451. }
  1452. /**
  1453. * Handle form input related to drupalPost(). Ensure that the specified fields
  1454. * exist and attempt to create POST data in the correct manner for the particular
  1455. * field type.
  1456. *
  1457. * @param $post
  1458. * Reference to array of post values.
  1459. * @param $edit
  1460. * Reference to array of edit values to be checked against the form.
  1461. * @param $submit
  1462. * Form submit button value.
  1463. * @param $form
  1464. * Array of form elements.
  1465. * @return
  1466. * Submit value matches a valid submit input in the form.
  1467. */
  1468. protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
  1469. // Retrieve the form elements.
  1470. $elements = $form->xpath('.//input|.//textarea|.//select');
  1471. $submit_matches = FALSE;
  1472. foreach ($elements as $element) {
  1473. // SimpleXML objects need string casting all the time.
  1474. $name = (string) $element['name'];
  1475. // This can either be the type of <input> or the name of the tag itself
  1476. // for <select> or <textarea>.
  1477. $type = isset($element['type']) ? (string)$element['type'] : $element->getName();
  1478. $value = isset($element['value']) ? (string)$element['value'] : '';
  1479. $done = FALSE;
  1480. if (isset($edit[$name])) {
  1481. switch ($type) {
  1482. case 'text':
  1483. case 'textarea':
  1484. case 'password':
  1485. $post[$name] = $edit[$name];
  1486. unset($edit[$name]);
  1487. break;
  1488. case 'radio':
  1489. if ($edit[$name] == $value) {
  1490. $post[$name] = $edit[$name];
  1491. unset($edit[$name]);
  1492. }
  1493. break;
  1494. case 'checkbox':
  1495. // To prevent checkbox from being checked.pass in a FALSE,
  1496. // otherwise the checkbox will be set to its value regardless
  1497. // of $edit.
  1498. if ($edit[$name] === FALSE) {
  1499. unset($edit[$name]);
  1500. continue 2;
  1501. }
  1502. else {
  1503. unset($edit[$name]);
  1504. $post[$name] = $value;
  1505. }
  1506. break;
  1507. case 'select':
  1508. $new_value = $edit[$name];
  1509. $index = 0;
  1510. $key = preg_replace('/\[\]$/', '', $name);
  1511. $options = $this->getAllOptions($element);
  1512. foreach ($options as $option) {
  1513. if (is_array($new_value)) {
  1514. $option_value= (string)$option['value'];
  1515. if (in_array($option_value, $new_value)) {
  1516. $post[$key . '[' . $index++ . ']'] = $option_value;
  1517. $done = TRUE;
  1518. unset($edit[$name]);
  1519. }
  1520. }
  1521. elseif ($new_value == $option['value']) {
  1522. $post[$name] = $new_value;
  1523. unset($edit[$name]);
  1524. $done = TRUE;
  1525. }
  1526. }
  1527. break;
  1528. case 'file':
  1529. $upload[$name] = $edit[$name];
  1530. unset($edit[$name]);
  1531. break;
  1532. }
  1533. }
  1534. if (!isset($post[$name]) && !$done) {
  1535. switch ($type) {
  1536. case 'textarea':
  1537. $post[$name] = (string)$element;
  1538. break;
  1539. case 'select':
  1540. $single = empty($element['multiple']);
  1541. $first = TRUE;
  1542. $index = 0;
  1543. $key = preg_replace('/\[\]$/', '', $name);
  1544. $options = $this->getAllOptions($element);
  1545. foreach ($options as $option) {
  1546. // For single select, we load the first option, if there is a
  1547. // selected option that will overwrite it later.
  1548. if ($option['selected'] || ($first && $single)) {
  1549. $first = FALSE;
  1550. if ($single) {
  1551. $post[$name] = (string)$option['value'];
  1552. }
  1553. else {
  1554. $post[$key . '[' . $index++ . ']'] = (string)$option['value'];
  1555. }
  1556. }
  1557. }
  1558. break;
  1559. case 'file':
  1560. break;
  1561. case 'submit':
  1562. case 'image':
  1563. if ($submit == $value) {
  1564. $post[$name] = $value;
  1565. $submit_matches = TRUE;
  1566. }
  1567. break;
  1568. case 'radio':
  1569. case 'checkbox':
  1570. if (!isset($element['checked'])) {
  1571. break;
  1572. }
  1573. // Deliberate no break.
  1574. default:
  1575. $post[$name] = $value;
  1576. }
  1577. }
  1578. }
  1579. return $submit_matches;
  1580. }
  1581. /**
  1582. * Perform an xpath search on the contents of the internal browser. The search
  1583. * is relative to the root element (HTML tag normally) of the page.
  1584. *
  1585. * @param $xpath
  1586. * The xpath string to use in the search.
  1587. * @return
  1588. * The return value of the xpath search. For details on the xpath string
  1589. * format and return values see the SimpleXML documentation,
  1590. * http://us.php.net/manual/function.simplexml-element-xpath.php.
  1591. */
  1592. protected function xpath($xpath) {
  1593. if ($this->parse()) {
  1594. return $this->elements->xpath($xpath);
  1595. }
  1596. return FALSE;
  1597. }
  1598. /**
  1599. * Get all option elements, including nested options, in a select.
  1600. *
  1601. * @param $element
  1602. * The element for which to get the options.
  1603. * @return
  1604. * Option elements in select.
  1605. */
  1606. protected function getAllOptions(SimpleXMLElement $element) {
  1607. $options = array();
  1608. // Add all options items.
  1609. foreach ($element->option as $option) {
  1610. $options[] = $option;
  1611. }
  1612. // Search option group children.
  1613. if (isset($element->optgroup)) {
  1614. foreach ($element->optgroup as $group) {
  1615. $options = array_merge($options, $this->getAllOptions($group));
  1616. }
  1617. }
  1618. return $options;
  1619. }
  1620. /**
  1621. * Pass if a link with the specified label is found, and optional with the
  1622. * specified index.
  1623. *
  1624. * @param $label
  1625. * Text between the anchor tags.
  1626. * @param $index
  1627. * Link position counting from zero.
  1628. * @param $message
  1629. * Message to display.
  1630. * @param $group
  1631. * The group this message belongs to, defaults to 'Other'.
  1632. * @return
  1633. * TRUE if the assertion succeeded, FALSE otherwise.
  1634. */
  1635. protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
  1636. $links = $this->xpath('//a[text()="' . $label . '"]');
  1637. $message = ($message ? $message : t('Link with label "!label" found.', array('!label' => $label)));
  1638. return $this->assert(isset($links[$index]), $message, $group);
  1639. }
  1640. /**
  1641. * Pass if a link with the specified label is not found.
  1642. *
  1643. * @param $label
  1644. * Text between the anchor tags.
  1645. * @param $index
  1646. * Link position counting from zero.
  1647. * @param $message
  1648. * Message to display.
  1649. * @param $group
  1650. * The group this message belongs to, defaults to 'Other'.
  1651. * @return
  1652. * TRUE if the assertion succeeded, FALSE otherwise.
  1653. */
  1654. protected function assertNoLink($label, $message = '', $group = 'Other') {
  1655. $links = $this->xpath('//a[text()="' . $label . '"]');
  1656. $message = ($message ? $message : t('Link with label "!label" not found.', array('!label' => $label)));
  1657. return $this->assert(empty($links), $message, $group);
  1658. }
  1659. /**
  1660. * Follows a link by name.
  1661. *
  1662. * Will click the first link found with this link text by default, or a
  1663. * later one if an index is given. Match is case insensitive with
  1664. * normalized space. The label is translated label. There is an assert
  1665. * for successful click.
  1666. *
  1667. * @param $label
  1668. * Text between the anchor tags.
  1669. * @param $index
  1670. * Link position counting from zero.
  1671. * @return
  1672. * Page on success, or FALSE on failure.
  1673. */
  1674. protected function clickLink($label, $index = 0) {
  1675. $url_before = $this->getUrl();
  1676. $urls = $this->xpath('//a[text()="' . $label . '"]');
  1677. if (isset($urls[$index])) {
  1678. $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
  1679. }
  1680. $this->assertTrue(isset($urls[$index]), t('Clicked link "!label" (!url_target) from !url_before', array('!label' => $label, '!url_target' => $url_target, '!url_before' => $url_before)), t('Browser'));
  1681. if (isset($urls[$index])) {
  1682. return $this->drupalGet($url_target);
  1683. }
  1684. return FALSE;
  1685. }
  1686. /**
  1687. * Takes a path and returns an absolute path.
  1688. *
  1689. * @param $path
  1690. * The path, can be a Drupal path or a site-relative path. It might have a
  1691. * query, too. Can even be an absolute path which is just passed through.
  1692. * @return
  1693. * An absolute path.
  1694. */
  1695. protected function getAbsoluteUrl($path) {
  1696. $options = array('absolute' => TRUE);
  1697. $parts = parse_url($path);
  1698. // This is more crude than the menu_is_external but enough here.
  1699. if (empty($parts['host'])) {
  1700. $path = $parts['path'];
  1701. $base_path = base_path();
  1702. $n = strlen($base_path);
  1703. if (substr($path, 0, $n) == $base_path) {
  1704. $path = substr($path, $n);
  1705. }
  1706. if (isset($parts['query'])) {
  1707. $options['query'] = $parts['query'];
  1708. }
  1709. $path = url($path, $options);
  1710. }
  1711. return $path;
  1712. }
  1713. /**
  1714. * Get the current url from the cURL handler.
  1715. *
  1716. * @return
  1717. * The current url.
  1718. */
  1719. protected function getUrl() {
  1720. return $this->url;
  1721. }
  1722. /**
  1723. * Gets the HTTP response headers of the requested page. Normally we are only
  1724. * interested in the headers returned by the last request. However, if a page
  1725. * is redirected or HTTP authentication is in use, multiple requests will be
  1726. * required to retrieve the page. Headers from all requests may be requested
  1727. * by passing TRUE to this function.
  1728. *
  1729. * @param $all_requests
  1730. * Boolean value specifying whether to return headers from all requests
  1731. * instead of just the last request. Defaults to FALSE.
  1732. * @return
  1733. * A name/value array if headers from only the last request are requested.
  1734. * If headers from all requests are requested, an array of name/value
  1735. * arrays, one for each request.
  1736. *
  1737. * The pseudonym ":status" is used for the HTTP status line.
  1738. *
  1739. * Values for duplicate headers are stored as a single comma-separated list.
  1740. */
  1741. protected function drupalGetHeaders($all_requests = FALSE) {
  1742. $request = 0;
  1743. $headers = array($request => array());
  1744. foreach ($this->headers as $header) {
  1745. $header = trim($header);
  1746. if ($header === '') {
  1747. $request++;
  1748. }
  1749. else {
  1750. if (strpos($header, 'HTTP/') === 0) {
  1751. $name = ':status';
  1752. $value = $header;
  1753. }
  1754. else {
  1755. list($name, $value) = explode(':', $header, 2);
  1756. $name = strtolower($name);
  1757. }
  1758. if (isset($headers[$request][$name])) {
  1759. $headers[$request][$name] .= ',' . trim($value);
  1760. }
  1761. else {
  1762. $headers[$request][$name] = trim($value);
  1763. }
  1764. }
  1765. }
  1766. if (!$all_requests) {
  1767. $headers = array_pop($headers);
  1768. }
  1769. return $headers;
  1770. }
  1771. /**
  1772. * Gets the value of an HTTP response header. If multiple requests were
  1773. * required to retrieve the page, only the headers from the last request will
  1774. * be checked by default. However, if TRUE is passed as the second argument,
  1775. * all requests will be processed from last to first until the header is
  1776. * found.
  1777. *
  1778. * @param $name
  1779. * The name of the header to retrieve. Names are case-insensitive (see RFC
  1780. * 2616 section 4.2).
  1781. * @param $all_requests
  1782. * Boolean value specifying whether to check all requests if the header is
  1783. * not found in the last request. Defaults to FALSE.
  1784. * @return
  1785. * The HTTP header value or FALSE if not found.
  1786. */
  1787. protected function drupalGetHeader($name, $all_requests = FALSE) {
  1788. $name = strtolower($name);
  1789. $header = FALSE;
  1790. if ($all_requests) {
  1791. foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
  1792. if (isset($headers[$name])) {
  1793. $header = $headers[$name];
  1794. break;
  1795. }
  1796. }
  1797. }
  1798. else {
  1799. $headers = $this->drupalGetHeaders();
  1800. if (isset($headers[$name])) {
  1801. $header = $headers[$name];
  1802. }
  1803. }
  1804. return $header;
  1805. }
  1806. /**
  1807. * Gets the current raw HTML of requested page.
  1808. */
  1809. protected function drupalGetContent() {
  1810. return $this->content;
  1811. }
  1812. /**
  1813. * Gets an array containing all e-mails sent during this test case.
  1814. *
  1815. * @param $filter
  1816. * An array containing key/value pairs used to filter the e-mails that are returned.
  1817. * @return
  1818. * An array containing e-mail messages captured during the current test.
  1819. */
  1820. protected function drupalGetMails($filter = array()) {
  1821. $captured_emails = variable_get('drupal_test_email_collector', array());
  1822. $filtered_emails = array();
  1823. foreach ($captured_emails as $message) {
  1824. foreach ($filter as $key => $value) {
  1825. // if (!isset($message[$key]) || $message[$key] != $value) {
  1826. if (!isset($message['params'][$key]) || $message['params'][$key] != $value) {
  1827. continue 2;
  1828. }
  1829. }
  1830. $filtered_emails[] = $message;
  1831. }
  1832. return $filtered_emails;
  1833. }
  1834. /**
  1835. * Sets the raw HTML content. This can be useful when a page has been fetched
  1836. * outside of the internal browser and assertions need to be made on the
  1837. * returned page.
  1838. *
  1839. * A good example would be when testing drupal_http_request(). After fetching
  1840. * the page the content can be set and page elements can be checked to ensure
  1841. * that the function worked properly.
  1842. */
  1843. protected function drupalSetContent($content, $url = 'internal:') {
  1844. $this->content = $content;
  1845. $this->url = $url;
  1846. $this->plainTextContent = FALSE;
  1847. $this->elements = FALSE;
  1848. }
  1849. /**
  1850. * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
  1851. * refers to the raw HTML that the page generated.
  1852. *
  1853. * @param $raw
  1854. * Raw (HTML) string to look for.
  1855. * @param $message
  1856. * Message to display.
  1857. * @param $group
  1858. * The group this message belongs to, defaults to 'Other'.
  1859. * @return
  1860. * TRUE on pass, FALSE on fail.
  1861. */
  1862. protected function assertRaw($raw, $message = '', $group = 'Other') {
  1863. if (!$message) {
  1864. $message = t('Raw "@raw" found', array('@raw' => check_plain($raw)));
  1865. }
  1866. return $this->assert(strpos($this->content, $raw) !== FALSE, $message, $group);
  1867. }
  1868. /**
  1869. * Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text
  1870. * refers to the raw HTML that the page generated.
  1871. *
  1872. * @param $raw
  1873. * Raw (HTML) string to look for.
  1874. * @param $message
  1875. * Message to display.
  1876. * @param $group
  1877. * The group this message belongs to, defaults to 'Other'.
  1878. * @return
  1879. * TRUE on pass, FALSE on fail.
  1880. */
  1881. protected function assertNoRaw($raw, $message = '', $group = 'Other') {
  1882. if (!$message) {
  1883. $message = t('Raw "@raw" not found', array('@raw' => check_plain($raw)));
  1884. }
  1885. return $this->assert(strpos($this->content, $raw) === FALSE, $message, $group);
  1886. }
  1887. /**
  1888. * Pass if the text IS found on the text version of the page. The text version
  1889. * is the equivalent of what a user would see when viewing through a web browser.
  1890. * In other words the HTML has been filtered out of the contents.
  1891. *
  1892. * @param $text
  1893. * Plain text to look for.
  1894. * @param $message
  1895. * Message to display.
  1896. * @param $group
  1897. * The group this message belongs to, defaults to 'Other'.
  1898. * @return
  1899. * TRUE on pass, FALSE on fail.
  1900. */
  1901. protected function assertText($text, $message = '', $group = 'Other') {
  1902. return $this->assertTextHelper($text, $message, $group, FALSE);
  1903. }
  1904. /**
  1905. * Pass if the text is NOT found on the text version of the page. The text version
  1906. * is the equivalent of what a user would see when viewing through a web browser.
  1907. * In other words the HTML has been filtered out of the contents.
  1908. *
  1909. * @param $text
  1910. * Plain text to look for.
  1911. * @param $message
  1912. * Message to display.
  1913. * @param $group
  1914. * The group this message belongs to, defaults to 'Other'.
  1915. * @return
  1916. * TRUE on pass, FALSE on fail.
  1917. */
  1918. protected function assertNoText($text, $message = '', $group = 'Other') {
  1919. return $this->assertTextHelper($text, $message, $group, TRUE);
  1920. }
  1921. /**
  1922. * Helper for assertText and assertNoText.
  1923. *
  1924. * It is not recommended to call this function directly.
  1925. *
  1926. * @param $text
  1927. * Plain text to look for.
  1928. * @param $message
  1929. * Message to display.
  1930. * @param $group
  1931. * The group this message belongs to.
  1932. * @param $not_exists
  1933. * TRUE if this text should not exist, FALSE if it should.
  1934. * @return
  1935. * TRUE on pass, FALSE on fail.
  1936. */
  1937. protected function assertTextHelper($text, $message, $group, $not_exists) {
  1938. if ($this->plainTextContent === FALSE) {
  1939. $this->plainTextContent = filter_xss($this->content, array());
  1940. }
  1941. if (!$message) {
  1942. $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
  1943. }
  1944. return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
  1945. }
  1946. /**
  1947. * Pass if the text is found ONLY ONCE on the text version of the page.
  1948. *
  1949. * The text version is the equivalent of what a user would see when viewing
  1950. * through a web browser. In other words the HTML has been filtered out of
  1951. * the contents.
  1952. *
  1953. * @param $text
  1954. * Plain text to look for.
  1955. * @param $message
  1956. * Message to display.
  1957. * @param $group
  1958. * The group this message belongs to, defaults to 'Other'.
  1959. * @return
  1960. * TRUE on pass, FALSE on fail.
  1961. */
  1962. protected function assertUniqueText($text, $message = '', $group = 'Other') {
  1963. return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
  1964. }
  1965. /**
  1966. * Pass if the text is found MORE THAN ONCE on the text version of the page.
  1967. *
  1968. * The text version is the equivalent of what a user would see when viewing
  1969. * through a web browser. In other words the HTML has been filtered out of
  1970. * the contents.
  1971. *
  1972. * @param $text
  1973. * Plain text to look for.
  1974. * @param $message
  1975. * Message to display.
  1976. * @param $group
  1977. * The group this message belongs to, defaults to 'Other'.
  1978. * @return
  1979. * TRUE on pass, FALSE on fail.
  1980. */
  1981. protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
  1982. return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
  1983. }
  1984. /**
  1985. * Helper for assertUniqueText and assertNoUniqueText.
  1986. *
  1987. * It is not recommended to call this function directly.
  1988. *
  1989. * @param $text
  1990. * Plain text to look for.
  1991. * @param $message
  1992. * Message to display.
  1993. * @param $group
  1994. * The group this message belongs to.
  1995. * @param $be_unique
  1996. * TRUE if this text should be found only once, FALSE if it should be found more than once.
  1997. * @return
  1998. * TRUE on pass, FALSE on fail.
  1999. */
  2000. protected function assertUniqueTextHelper($text, $message, $group, $be_unique) {
  2001. if ($this->plainTextContent === FALSE) {
  2002. $this->plainTextContent = filter_xss($this->content, array());
  2003. }
  2004. if (!$message) {
  2005. $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
  2006. }
  2007. $first_occurance = strpos($this->plainTextContent, $text);
  2008. if ($first_occurance === FALSE) {
  2009. return $this->assert(FALSE, $message, $group);
  2010. }
  2011. $offset = $first_occurance + strlen($text);
  2012. $second_occurance = strpos($this->plainTextContent, $text, $offset);
  2013. return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
  2014. }
  2015. /**
  2016. * Will trigger a pass if the Perl regex pattern is found in the raw content.
  2017. *
  2018. * @param $pattern
  2019. * Perl regex to look for including the regex delimiters.
  2020. * @param $message
  2021. * Message to display.
  2022. * @param $group
  2023. * The group this message belongs to.
  2024. * @return
  2025. * TRUE on pass, FALSE on fail.
  2026. */
  2027. protected function assertPattern($pattern, $message = '', $group = 'Other') {
  2028. if (!$message) {
  2029. $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
  2030. }
  2031. return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2032. }
  2033. /**
  2034. * Will trigger a pass if the perl regex pattern is not present in raw content.
  2035. *
  2036. * @param $pattern
  2037. * Perl regex to look for including the regex delimiters.
  2038. * @param $message
  2039. * Message to display.
  2040. * @param $group
  2041. * The group this message belongs to.
  2042. * @return
  2043. * TRUE on pass, FALSE on fail.
  2044. */
  2045. protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
  2046. if (!$message) {
  2047. $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
  2048. }
  2049. return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2050. }
  2051. /**
  2052. * Pass if the page title is the given string.
  2053. *
  2054. * @param $title
  2055. * The string the title should be.
  2056. * @param $message
  2057. * Message to display.
  2058. * @param $group
  2059. * The group this message belongs to.
  2060. * @return
  2061. * TRUE on pass, FALSE on fail.
  2062. */
  2063. protected function assertTitle($title, $message, $group = 'Other') {
  2064. return $this->assertEqual(current($this->xpath('//title')), $title, $message, $group);
  2065. }
  2066. /**
  2067. * Pass if the page title is not the given string.
  2068. *
  2069. * @param $title
  2070. * The string the title should not be.
  2071. * @param $message
  2072. * Message to display.
  2073. * @param $group
  2074. * The group this message belongs to.
  2075. * @return
  2076. * TRUE on pass, FALSE on fail.
  2077. */
  2078. protected function assertNoTitle($title, $message, $group = 'Other') {
  2079. return $this->assertNotEqual(current($this->xpath('//title')), $title, $message, $group);
  2080. }
  2081. /**
  2082. * Assert that a field exists in the current page by the given XPath.
  2083. *
  2084. * @param $xpath
  2085. * XPath used to find the field.
  2086. * @param $value
  2087. * Value of the field to assert.
  2088. * @param $message
  2089. * Message to display.
  2090. * @param $group
  2091. * The group this message belongs to.
  2092. * @return
  2093. * TRUE on pass, FALSE on fail.
  2094. */
  2095. protected function assertFieldByXPath($xpath, $value, $message, $group = 'Other') {
  2096. $fields = $this->xpath($xpath);
  2097. // If value specified then check array for match.
  2098. $found = TRUE;
  2099. if ($value) {
  2100. $found = FALSE;
  2101. if ($fields) {
  2102. foreach ($fields as $field) {
  2103. if (isset($field['value']) && $field['value'] == $value) {
  2104. // Input element with correct value.
  2105. $found = TRUE;
  2106. }
  2107. elseif (isset($field->option)) {
  2108. // Select element found.
  2109. if ($this->getSelectedItem($field) == $value) {
  2110. $found = TRUE;
  2111. }
  2112. else {
  2113. // No item selected so use first item.
  2114. $items = $this->getAllOptions($field);
  2115. if (!empty($items) && $items[0]['value'] == $value) {
  2116. $found = TRUE;
  2117. }
  2118. }
  2119. }
  2120. elseif ((string) $field == $value) {
  2121. // Text area with correct text.
  2122. $found = TRUE;
  2123. }
  2124. }
  2125. }
  2126. }
  2127. return $this->assertTrue($fields && $found, $message, $group);
  2128. }
  2129. /**
  2130. * Get the selected value from a select field.
  2131. *
  2132. * @param $element
  2133. * SimpleXMLElement select element.
  2134. * @return
  2135. * The selected value or FALSE.
  2136. */
  2137. protected function getSelectedItem(SimpleXMLElement $element) {
  2138. foreach ($element->children() as $item) {
  2139. if (isset($item['selected'])) {
  2140. return $item['value'];
  2141. }
  2142. elseif ($item->getName() == 'optgroup') {
  2143. if ($value = $this->getSelectedItem($item)) {
  2144. return $value;
  2145. }
  2146. }
  2147. }
  2148. return FALSE;
  2149. }
  2150. /**
  2151. * Assert that a field does not exist in the current page by the given XPath.
  2152. *
  2153. * @param $xpath
  2154. * XPath used to find the field.
  2155. * @param $value
  2156. * Value of the field to assert.
  2157. * @param $message
  2158. * Message to display.
  2159. * @param $group
  2160. * The group this message belongs to.
  2161. * @return
  2162. * TRUE on pass, FALSE on fail.
  2163. */
  2164. protected function assertNoFieldByXPath($xpath, $value, $message, $group = 'Other') {
  2165. $fields = $this->xpath($xpath);
  2166. // If value specified then check array for match.
  2167. $found = TRUE;
  2168. if ($value) {
  2169. $found = FALSE;
  2170. if ($fields) {
  2171. foreach ($fields as $field) {
  2172. if ($field['value'] == $value) {
  2173. $found = TRUE;
  2174. }
  2175. }
  2176. }
  2177. }
  2178. return $this->assertFalse($fields && $found, $message, $group);
  2179. }
  2180. /**
  2181. * Assert that a field exists in the current page with the given name and value.
  2182. *
  2183. * @param $name
  2184. * Name of field to assert.
  2185. * @param $value
  2186. * Value of the field to assert.
  2187. * @param $message
  2188. * Message to display.
  2189. * @param $group
  2190. * The group this message belongs to.
  2191. * @return
  2192. * TRUE on pass, FALSE on fail.
  2193. */
  2194. protected function assertFieldByName($name, $value = '', $message = '') {
  2195. return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Found field by name @name', array('@name' => $name)), t('Browser'));
  2196. }
  2197. /**
  2198. * Assert that a field does not exist with the given name and value.
  2199. *
  2200. * @param $name
  2201. * Name of field to assert.
  2202. * @param $value
  2203. * Value of the field to assert.
  2204. * @param $message
  2205. * Message to display.
  2206. * @param $group
  2207. * The group this message belongs to.
  2208. * @return
  2209. * TRUE on pass, FALSE on fail.
  2210. */
  2211. protected function assertNoFieldByName($name, $value = '', $message = '') {
  2212. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
  2213. }
  2214. /**
  2215. * Assert that a field exists in the current page with the given id and value.
  2216. *
  2217. * @param $id
  2218. * Id of field to assert.
  2219. * @param $value
  2220. * Value of the field to assert.
  2221. * @param $message
  2222. * Message to display.
  2223. * @param $group
  2224. * The group this message belongs to.
  2225. * @return
  2226. * TRUE on pass, FALSE on fail.
  2227. */
  2228. protected function assertFieldById($id, $value = '', $message = '') {
  2229. return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
  2230. }
  2231. /**
  2232. * Assert that a field does not exist with the given id and value.
  2233. *
  2234. * @param $id
  2235. * Id of field to assert.
  2236. * @param $value
  2237. * Value of the field to assert.
  2238. * @param $message
  2239. * Message to display.
  2240. * @param $group
  2241. * The group this message belongs to.
  2242. * @return
  2243. * TRUE on pass, FALSE on fail.
  2244. */
  2245. protected function assertNoFieldById($id, $value = '', $message = '') {
  2246. return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
  2247. }
  2248. /**
  2249. * Assert that a checkbox field in the current page is checked.
  2250. *
  2251. * @param $id
  2252. * Id of field to assert.
  2253. * @param $message
  2254. * Message to display.
  2255. * @return
  2256. * TRUE on pass, FALSE on fail.
  2257. */
  2258. protected function assertFieldChecked($id, $message = '') {
  2259. $elements = $this->xpath('//input[@id="' . $id . '"]');
  2260. return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
  2261. }
  2262. /**
  2263. * Assert that a checkbox field in the current page is not checked.
  2264. *
  2265. * @param $id
  2266. * Id of field to assert.
  2267. * @param $message
  2268. * Message to display.
  2269. * @return
  2270. * TRUE on pass, FALSE on fail.
  2271. */
  2272. protected function assertNoFieldChecked($id, $message = '') {
  2273. $elements = $this->xpath('//input[@id="' . $id . '"]');
  2274. return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
  2275. }
  2276. /**
  2277. * Assert that a field exists with the given name or id.
  2278. *
  2279. * @param $field
  2280. * Name or id of field to assert.
  2281. * @param $message
  2282. * Message to display.
  2283. * @param $group
  2284. * The group this message belongs to.
  2285. * @return
  2286. * TRUE on pass, FALSE on fail.
  2287. */
  2288. protected function assertField($field, $message = '', $group = 'Other') {
  2289. return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), '', $message, $group);
  2290. }
  2291. /**
  2292. * Assert that a field does not exist with the given name or id.
  2293. *
  2294. * @param $field
  2295. * Name or id of field to assert.
  2296. * @param $message
  2297. * Message to display.
  2298. * @param $group
  2299. * The group this message belongs to.
  2300. * @return
  2301. * TRUE on pass, FALSE on fail.
  2302. */
  2303. protected function assertNoField($field, $message = '', $group = 'Other') {
  2304. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), '', $message, $group);
  2305. }
  2306. /**
  2307. * Helper function: construct an XPath for the given set of attributes and value.
  2308. *
  2309. * @param $attribute
  2310. * Field attributes.
  2311. * @param $value
  2312. * Value of field.
  2313. * @return
  2314. * XPath for specified values.
  2315. */
  2316. protected function constructFieldXpath($attribute, $value) {
  2317. return '//textarea[@' . $attribute . '="' . $value . '"]|//input[@' . $attribute . '="' . $value . '"]|//select[@' . $attribute . '="' . $value . '"]';
  2318. }
  2319. /**
  2320. * Assert the page responds with the specified response code.
  2321. *
  2322. * @param $code
  2323. * Response code. For example 200 is a successful page request. For a list
  2324. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  2325. * @param $message
  2326. * Message to display.
  2327. * @return
  2328. * Assertion result.
  2329. */
  2330. protected function assertResponse($code, $message = '') {
  2331. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  2332. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  2333. return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  2334. }
  2335. /**
  2336. * Assert that the most recently sent e-mail message has a field with the given value.
  2337. *
  2338. * @param $name
  2339. * Name of field or message property to assert. Examples: subject, body, id, ...
  2340. * @param $value
  2341. * Value of the field to assert.
  2342. * @param $message
  2343. * Message to display.
  2344. * @return
  2345. * TRUE on pass, FALSE on fail.
  2346. */
  2347. protected function assertMail($name, $value = '', $message = '') {
  2348. $captured_emails = variable_get('drupal_test_email_collector', array());
  2349. $email = end($captured_emails);
  2350. // return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
  2351. return $this->assertTrue(
  2352. ($email && isset($email[$name]) && $email[$name] == $value) ||
  2353. ($email && isset($email['params'][$name]) && $email['params'][$name] == $value),
  2354. $message,
  2355. t('E-mail'));
  2356. }
  2357. /**
  2358. * Log verbose message in a text file.
  2359. *
  2360. * The a link to the vebose message will be placed in the test results via
  2361. * as a passing assertion with the text '[verbose message]'.
  2362. *
  2363. * @param $message
  2364. * The verbose message to be stored.
  2365. * @see simpletest_verbose()
  2366. */
  2367. protected function verbose($message) {
  2368. if ($id = simpletest_verbose($message)) {
  2369. $this->pass(l(t('Verbose message'), $this->originalFileDirectory . '/simpletest/verbose/' . get_class($this) . '-' . $id . '.html', array('attributes' => array('target' => '_blank'))), 'Debug');
  2370. }
  2371. }
  2372. }
  2373. /**
  2374. * Log verbose message in a text file.
  2375. *
  2376. * If verbose mode is enabled then page requests will be dumped to a file and
  2377. * presented on the test result screen. The messages will be placed in a file
  2378. * located in the simpletest directory in the original file system.
  2379. *
  2380. * @param $message
  2381. * The verbose message to be stored.
  2382. * @param $original_file_directory
  2383. * The original file directory, before it was changed for testing purposes.
  2384. * @param $test_class
  2385. * The active test case class.
  2386. * @return
  2387. * The ID of the message to be placed in related assertion messages.
  2388. * @see DrupalTestCase->originalFileDirectory
  2389. * @see DrupalWebTestCase->verbose()
  2390. */
  2391. function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
  2392. static $file_directory = NULL, $class = NULL, $id = 1;
  2393. // $verbose = &drupal_static(__FUNCTION__);
  2394. static $verbose;
  2395. // Will pass first time during setup phase, and when verbose is TRUE.
  2396. if (!isset($original_file_directory) && !$verbose) {
  2397. return FALSE;
  2398. }
  2399. if ($message && $file_directory) {
  2400. $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
  2401. file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
  2402. return $id++;
  2403. }
  2404. if ($original_file_directory) {
  2405. $file_directory = $original_file_directory;
  2406. $class = $test_class;
  2407. $verbose = variable_get('simpletest_verbose', FALSE);
  2408. $directory = $file_directory . '/simpletest/verbose';
  2409. // return file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  2410. return file_check_directory($directory, FILE_CREATE_DIRECTORY);
  2411. }
  2412. return FALSE;
  2413. }