simpletest.test 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. <?php
  2. /**
  3. * @file
  4. * Tests for simpletest.module.
  5. */
  6. class SimpleTestFunctionalTest extends DrupalWebTestCase {
  7. /**
  8. * The results array that has been parsed by getTestResults().
  9. */
  10. protected $childTestResults;
  11. /**
  12. * Store the test ID from each test run for comparison, to ensure they are
  13. * incrementing.
  14. */
  15. protected $test_ids = array();
  16. public static function getInfo() {
  17. return array(
  18. 'name' => 'SimpleTest functionality',
  19. 'description' => "Test SimpleTest's web interface: check that the intended tests were run and ensure that test reports display the intended results. Also test SimpleTest's internal browser and API's both explicitly and implicitly.",
  20. 'group' => 'SimpleTest'
  21. );
  22. }
  23. function setUp() {
  24. if (!$this->inCURL()) {
  25. parent::setUp('simpletest');
  26. // Create and login user
  27. $admin_user = $this->drupalCreateUser(array('administer unit tests'));
  28. $this->drupalLogin($admin_user);
  29. }
  30. else {
  31. parent::setUp('non_existent_module');
  32. }
  33. }
  34. /**
  35. * Test the internal browsers functionality.
  36. */
  37. function testInternalBrowser() {
  38. global $conf;
  39. if (!$this->inCURL()) {
  40. $this->drupalGet('node');
  41. $this->assertTrue($this->drupalGetHeader('Date'), 'An HTTP header was received.');
  42. $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
  43. $this->assertNoTitle('Foo', 'Site title does not match.');
  44. // Make sure that we are locked out of the installer when prefixing
  45. // using the user-agent header. This is an important security check.
  46. global $base_url;
  47. $this->drupalGet($base_url . '/install.php', array('external' => TRUE));
  48. $this->assertResponse(403, 'Cannot access install.php with a "simpletest" user-agent header.');
  49. $user = $this->drupalCreateUser();
  50. $this->drupalLogin($user);
  51. $headers = $this->drupalGetHeaders(TRUE);
  52. $this->assertEqual(count($headers), 2, 'There was one intermediate request.');
  53. $this->assertTrue(strpos($headers[0][':status'], '302') !== FALSE, 'Intermediate response code was 302.');
  54. $this->assertFalse(empty($headers[0]['location']), 'Intermediate request contained a Location header.');
  55. $this->assertEqual($this->getUrl(), $headers[0]['location'], 'HTTP redirect was followed');
  56. $this->assertFalse($this->drupalGetHeader('Location'), 'Headers from intermediate request were reset.');
  57. $this->assertResponse(200, 'Response code from intermediate request was reset.');
  58. // Test the maximum redirection option.
  59. $this->drupalLogout();
  60. $edit = array(
  61. 'name' => $user->name,
  62. 'pass' => $user->pass_raw
  63. );
  64. variable_set('simpletest_maximum_redirects', 1);
  65. $this->drupalPost('user?destination=user/logout', $edit, t('Log in'));
  66. $headers = $this->drupalGetHeaders(TRUE);
  67. $this->assertEqual(count($headers), 2, 'Simpletest stopped following redirects after the first one.');
  68. }
  69. }
  70. /**
  71. * Test validation of the User-Agent header we use to perform test requests.
  72. */
  73. function testUserAgentValidation() {
  74. if (!$this->inCURL()) {
  75. global $base_url;
  76. $simpletest_path = $base_url . '/' . drupal_get_path('module', 'simpletest');
  77. $HTTP_path = $simpletest_path .'/tests/http.php?q=node';
  78. $https_path = $simpletest_path .'/tests/https.php?q=node';
  79. // Generate a valid simpletest User-Agent to pass validation.
  80. $this->assertTrue(preg_match('/simpletest\d+/', $this->databasePrefix, $matches), 'Database prefix contains simpletest prefix.');
  81. $test_ua = drupal_generate_test_ua($matches[0]);
  82. $this->additionalCurlOptions = array(CURLOPT_USERAGENT => $test_ua);
  83. // Test pages only available for testing.
  84. $this->drupalGet($HTTP_path);
  85. $this->assertResponse(200, 'Requesting http.php with a legitimate simpletest User-Agent returns OK.');
  86. $this->drupalGet($https_path);
  87. $this->assertResponse(200, 'Requesting https.php with a legitimate simpletest User-Agent returns OK.');
  88. // Now slightly modify the HMAC on the header, which should not validate.
  89. $this->additionalCurlOptions = array(CURLOPT_USERAGENT => $test_ua . 'X');
  90. $this->drupalGet($HTTP_path);
  91. $this->assertResponse(403, 'Requesting http.php with a bad simpletest User-Agent fails.');
  92. $this->drupalGet($https_path);
  93. $this->assertResponse(403, 'Requesting https.php with a bad simpletest User-Agent fails.');
  94. // Use a real User-Agent and verify that the special files http.php and
  95. // https.php can't be accessed.
  96. $this->additionalCurlOptions = array(CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12');
  97. $this->drupalGet($HTTP_path);
  98. $this->assertResponse(403, 'Requesting http.php with a normal User-Agent fails.');
  99. $this->drupalGet($https_path);
  100. $this->assertResponse(403, 'Requesting https.php with a normal User-Agent fails.');
  101. }
  102. }
  103. /**
  104. * Make sure that tests selected through the web interface are run and
  105. * that the results are displayed correctly.
  106. */
  107. function testWebTestRunner() {
  108. $this->pass = t('SimpleTest pass.');
  109. $this->fail = t('SimpleTest fail.');
  110. $this->valid_permission = 'access content';
  111. $this->invalid_permission = 'invalid permission';
  112. if ($this->inCURL()) {
  113. // Only run following code if this test is running itself through a CURL request.
  114. $this->stubTest();
  115. }
  116. else {
  117. // Run twice so test_ids can be accumulated.
  118. for ($i = 0; $i < 2; $i++) {
  119. // Run this test from web interface.
  120. $this->drupalGet('admin/config/development/testing');
  121. $edit = array();
  122. $edit['SimpleTestFunctionalTest'] = TRUE;
  123. $this->drupalPost(NULL, $edit, t('Run tests'));
  124. // Parse results and confirm that they are correct.
  125. $this->getTestResults();
  126. $this->confirmStubTestResults();
  127. }
  128. // Regression test for #290316.
  129. // Check that test_id is incrementing.
  130. $this->assertTrue($this->test_ids[0] != $this->test_ids[1], 'Test ID is incrementing.');
  131. }
  132. }
  133. /**
  134. * Test to be run and the results confirmed.
  135. */
  136. function stubTest() {
  137. $this->pass($this->pass);
  138. $this->fail($this->fail);
  139. $this->drupalCreateUser(array($this->valid_permission));
  140. $this->drupalCreateUser(array($this->invalid_permission));
  141. $this->pass(t('Test ID is @id.', array('@id' => $this->testId)));
  142. // Generates a warning.
  143. $a = '';
  144. foreach ($a as $b) {
  145. }
  146. // Call an assert function specific to that class.
  147. $this->assertNothing();
  148. // Generates 3 warnings inside a PHP function.
  149. simplexml_load_string('<fake>');
  150. debug('Foo', 'Debug');
  151. }
  152. /**
  153. * Assert nothing.
  154. */
  155. function assertNothing() {
  156. $this->pass("This is nothing.");
  157. }
  158. /**
  159. * Confirm that the stub test produced the desired results.
  160. */
  161. function confirmStubTestResults() {
  162. $this->assertAssertion(t('Enabled modules: %modules', array('%modules' => 'non_existent_module')), 'Other', 'Fail', 'simpletest.test', 'SimpleTestFunctionalTest->setUp()');
  163. $this->assertAssertion($this->pass, 'Other', 'Pass', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  164. $this->assertAssertion($this->fail, 'Other', 'Fail', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  165. $this->assertAssertion(t('Created permissions: @perms', array('@perms' => $this->valid_permission)), 'Role', 'Pass', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  166. $this->assertAssertion(t('Invalid permission %permission.', array('%permission' => $this->invalid_permission)), 'Role', 'Fail', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  167. // Check that a warning is caught by simpletest.
  168. // The exact error message differs between PHP versions so we check only
  169. // the presense of the 'foreach' statement.
  170. $this->assertAssertion('foreach()', 'Warning', 'Fail', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  171. // Check that the backtracing code works for specific assert function.
  172. $this->assertAssertion('This is nothing.', 'Other', 'Pass', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  173. // Check that errors that occur inside PHP internal functions are correctly reported.
  174. // The exact error message differs between PHP versions so we check only
  175. // the function name 'simplexml_load_string'.
  176. $this->assertAssertion('simplexml_load_string', 'Warning', 'Fail', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  177. $this->assertAssertion("Debug: 'Foo'", 'Debug', 'Fail', 'simpletest.test', 'SimpleTestFunctionalTest->stubTest()');
  178. $this->assertEqual('6 passes, 5 fails, 4 exceptions, and 1 debug message', $this->childTestResults['summary'], 'Stub test summary is correct');
  179. $this->test_ids[] = $test_id = $this->getTestIdFromResults();
  180. $this->assertTrue($test_id, 'Found test ID in results.');
  181. }
  182. /**
  183. * Fetch the test id from the test results.
  184. */
  185. function getTestIdFromResults() {
  186. foreach ($this->childTestResults['assertions'] as $assertion) {
  187. if (preg_match('@^Test ID is ([0-9]*)\.$@', $assertion['message'], $matches)) {
  188. return $matches[1];
  189. }
  190. }
  191. return NULL;
  192. }
  193. /**
  194. * Assert that an assertion with the specified values is displayed
  195. * in the test results.
  196. *
  197. * @param string $message Assertion message.
  198. * @param string $type Assertion type.
  199. * @param string $status Assertion status.
  200. * @param string $file File where the assertion originated.
  201. * @param string $functuion Function where the assertion originated.
  202. * @return Assertion result.
  203. */
  204. function assertAssertion($message, $type, $status, $file, $function) {
  205. $message = trim(strip_tags($message));
  206. $found = FALSE;
  207. foreach ($this->childTestResults['assertions'] as $assertion) {
  208. if ((strpos($assertion['message'], $message) !== FALSE) &&
  209. $assertion['type'] == $type &&
  210. $assertion['status'] == $status &&
  211. $assertion['file'] == $file &&
  212. $assertion['function'] == $function) {
  213. $found = TRUE;
  214. break;
  215. }
  216. }
  217. return $this->assertTrue($found, format_string('Found assertion {"@message", "@type", "@status", "@file", "@function"}.', array('@message' => $message, '@type' => $type, '@status' => $status, "@file" => $file, "@function" => $function)));
  218. }
  219. /**
  220. * Get the results from a test and store them in the class array $results.
  221. */
  222. function getTestResults() {
  223. $results = array();
  224. if ($this->parse()) {
  225. if ($fieldset = $this->getResultFieldSet()) {
  226. // Code assumes this is the only test in group.
  227. $results['summary'] = $this->asText($fieldset->div->div[1]);
  228. $results['name'] = $this->asText($fieldset->legend);
  229. $results['assertions'] = array();
  230. $tbody = $fieldset->div->table->tbody;
  231. foreach ($tbody->tr as $row) {
  232. $assertion = array();
  233. $assertion['message'] = $this->asText($row->td[0]);
  234. $assertion['type'] = $this->asText($row->td[1]);
  235. $assertion['file'] = $this->asText($row->td[2]);
  236. $assertion['line'] = $this->asText($row->td[3]);
  237. $assertion['function'] = $this->asText($row->td[4]);
  238. $ok_url = file_create_url('misc/watchdog-ok.png');
  239. $assertion['status'] = ($row->td[5]->img['src'] == $ok_url) ? 'Pass' : 'Fail';
  240. $results['assertions'][] = $assertion;
  241. }
  242. }
  243. }
  244. $this->childTestResults = $results;
  245. }
  246. /**
  247. * Get the fieldset containing the results for group this test is in.
  248. */
  249. function getResultFieldSet() {
  250. $fieldsets = $this->xpath('//fieldset');
  251. $info = $this->getInfo();
  252. foreach ($fieldsets as $fieldset) {
  253. if ($this->asText($fieldset->legend) == $info['name']) {
  254. return $fieldset;
  255. }
  256. }
  257. return FALSE;
  258. }
  259. /**
  260. * Extract the text contained by the element.
  261. *
  262. * @param $element
  263. * Element to extract text from.
  264. * @return
  265. * Extracted text.
  266. */
  267. function asText(SimpleXMLElement $element) {
  268. if (!is_object($element)) {
  269. return $this->fail('The element is not an element.');
  270. }
  271. return trim(html_entity_decode(strip_tags($element->asXML())));
  272. }
  273. /**
  274. * Check if the test is being run from inside a CURL request.
  275. */
  276. function inCURL() {
  277. return (bool) drupal_valid_test_ua();
  278. }
  279. }
  280. /**
  281. * Test internal testing framework browser.
  282. */
  283. class SimpleTestBrowserTestCase extends DrupalWebTestCase {
  284. /**
  285. * A flag indicating whether a cookie has been set in a test.
  286. *
  287. * @var bool
  288. */
  289. protected static $cookieSet = FALSE;
  290. public static function getInfo() {
  291. return array(
  292. 'name' => 'SimpleTest browser',
  293. 'description' => 'Test the internal browser of the testing framework.',
  294. 'group' => 'SimpleTest',
  295. );
  296. }
  297. function setUp() {
  298. parent::setUp();
  299. variable_set('user_register', USER_REGISTER_VISITORS);
  300. }
  301. /**
  302. * Test DrupalWebTestCase::getAbsoluteUrl().
  303. */
  304. function testGetAbsoluteUrl() {
  305. // Testbed runs with Clean URLs disabled, so disable it here.
  306. variable_set('clean_url', 0);
  307. $url = 'user/login';
  308. $this->drupalGet($url);
  309. $absolute = url($url, array('absolute' => TRUE));
  310. $this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
  311. $this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
  312. $this->drupalPost(NULL, array(), t('Log in'));
  313. $this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
  314. $this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
  315. $this->clickLink('Create new account');
  316. $url = 'user/register';
  317. $absolute = url($url, array('absolute' => TRUE));
  318. $this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
  319. $this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
  320. }
  321. /**
  322. * Tests XPath escaping.
  323. */
  324. function testXPathEscaping() {
  325. $testpage = <<< EOF
  326. <html>
  327. <body>
  328. <a href="link1">A "weird" link, just to bother the dumb "XPath 1.0"</a>
  329. <a href="link2">A second "even more weird" link, in memory of George O'Malley</a>
  330. </body>
  331. </html>
  332. EOF;
  333. $this->drupalSetContent($testpage);
  334. // Matches the first link.
  335. $urls = $this->xpath('//a[text()=:text]', array(':text' => 'A "weird" link, just to bother the dumb "XPath 1.0"'));
  336. $this->assertEqual($urls[0]['href'], 'link1', 'Match with quotes.');
  337. $urls = $this->xpath('//a[text()=:text]', array(':text' => 'A second "even more weird" link, in memory of George O\'Malley'));
  338. $this->assertEqual($urls[0]['href'], 'link2', 'Match with mixed single and double quotes.');
  339. }
  340. /**
  341. * Tests that cookies set during a request are available for testing.
  342. */
  343. public function testCookies() {
  344. // Check that the $this->cookies property is populated when a user logs in.
  345. $user = $this->drupalCreateUser();
  346. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  347. $this->drupalPost('<front>', $edit, t('Log in'));
  348. $this->assertEqual(count($this->cookies), 1, 'A cookie is set when the user logs in.');
  349. // Check that the name and value of the cookie match the request data.
  350. $cookie_header = $this->drupalGetHeader('set-cookie', TRUE);
  351. // The name and value are located at the start of the string, separated by
  352. // an equals sign and ending in a semicolon.
  353. preg_match('/^([^=]+)=([^;]+)/', $cookie_header, $matches);
  354. $name = $matches[1];
  355. $value = $matches[2];
  356. $this->assertTrue(array_key_exists($name, $this->cookies), 'The cookie name is correct.');
  357. $this->assertEqual($value, $this->cookies[$name]['value'], 'The cookie value is correct.');
  358. // Set a flag indicating that a cookie has been set in this test.
  359. // @see SimpleTestBrowserTestCase::testCookieDoesNotBleed().
  360. self::$cookieSet = TRUE;
  361. }
  362. /**
  363. * Tests that the cookies from a previous test do not bleed into a new test.
  364. *
  365. * @see SimpleTestBrowserTestCase::testCookies().
  366. */
  367. public function testCookieDoesNotBleed() {
  368. // In order for this test to be effective it should always run after the
  369. // testCookies() test.
  370. $this->assertTrue(self::$cookieSet, 'Tests have been executed in the expected order.');
  371. $this->assertEqual(count($this->cookies), 0, 'No cookies are present at the start of a new test.');
  372. }
  373. }
  374. class SimpleTestMailCaptureTestCase extends DrupalWebTestCase {
  375. /**
  376. * Implement getInfo().
  377. */
  378. public static function getInfo() {
  379. return array(
  380. 'name' => 'SimpleTest e-mail capturing',
  381. 'description' => 'Test the SimpleTest e-mail capturing logic, the assertMail assertion and the drupalGetMails function.',
  382. 'group' => 'SimpleTest',
  383. );
  384. }
  385. /**
  386. * Test to see if the wrapper function is executed correctly.
  387. */
  388. function testMailSend() {
  389. // Create an e-mail.
  390. $subject = $this->randomString(64);
  391. $body = $this->randomString(128);
  392. $message = array(
  393. 'id' => 'drupal_mail_test',
  394. 'headers' => array('Content-type'=> 'text/html'),
  395. 'subject' => $subject,
  396. 'to' => 'foobar@example.com',
  397. 'body' => $body,
  398. );
  399. // Before we send the e-mail, drupalGetMails should return an empty array.
  400. $captured_emails = $this->drupalGetMails();
  401. $this->assertEqual(count($captured_emails), 0, 'The captured e-mails queue is empty.', 'E-mail');
  402. // Send the e-mail.
  403. $response = drupal_mail_system('simpletest', 'drupal_mail_test')->mail($message);
  404. // Ensure that there is one e-mail in the captured e-mails array.
  405. $captured_emails = $this->drupalGetMails();
  406. $this->assertEqual(count($captured_emails), 1, 'One e-mail was captured.', 'E-mail');
  407. // Assert that the e-mail was sent by iterating over the message properties
  408. // and ensuring that they are captured intact.
  409. foreach ($message as $field => $value) {
  410. $this->assertMail($field, $value, format_string('The e-mail was sent and the value for property @field is intact.', array('@field' => $field)), 'E-mail');
  411. }
  412. // Send additional e-mails so more than one e-mail is captured.
  413. for ($index = 0; $index < 5; $index++) {
  414. $message = array(
  415. 'id' => 'drupal_mail_test_' . $index,
  416. 'headers' => array('Content-type'=> 'text/html'),
  417. 'subject' => $this->randomString(64),
  418. 'to' => $this->randomName(32) . '@example.com',
  419. 'body' => $this->randomString(512),
  420. );
  421. drupal_mail_system('drupal_mail_test', $index)->mail($message);
  422. }
  423. // There should now be 6 e-mails captured.
  424. $captured_emails = $this->drupalGetMails();
  425. $this->assertEqual(count($captured_emails), 6, 'All e-mails were captured.', 'E-mail');
  426. // Test different ways of getting filtered e-mails via drupalGetMails().
  427. $captured_emails = $this->drupalGetMails(array('id' => 'drupal_mail_test'));
  428. $this->assertEqual(count($captured_emails), 1, 'Only one e-mail is returned when filtering by id.', 'E-mail');
  429. $captured_emails = $this->drupalGetMails(array('id' => 'drupal_mail_test', 'subject' => $subject));
  430. $this->assertEqual(count($captured_emails), 1, 'Only one e-mail is returned when filtering by id and subject.', 'E-mail');
  431. $captured_emails = $this->drupalGetMails(array('id' => 'drupal_mail_test', 'subject' => $subject, 'from' => 'this_was_not_used@example.com'));
  432. $this->assertEqual(count($captured_emails), 0, 'No e-mails are returned when querying with an unused from address.', 'E-mail');
  433. // Send the last e-mail again, so we can confirm that the drupalGetMails-filter
  434. // correctly returns all e-mails with a given property/value.
  435. drupal_mail_system('drupal_mail_test', $index)->mail($message);
  436. $captured_emails = $this->drupalGetMails(array('id' => 'drupal_mail_test_4'));
  437. $this->assertEqual(count($captured_emails), 2, 'All e-mails with the same id are returned when filtering by id.', 'E-mail');
  438. }
  439. }
  440. /**
  441. * Test Folder creation
  442. */
  443. class SimpleTestFolderTestCase extends DrupalWebTestCase {
  444. public static function getInfo() {
  445. return array(
  446. 'name' => 'Testing SimpleTest setUp',
  447. 'description' => "This test will check SimpleTest's treatment of hook_install during setUp. Image module is used for test.",
  448. 'group' => 'SimpleTest',
  449. );
  450. }
  451. function setUp() {
  452. return parent::setUp('image');
  453. }
  454. function testFolderSetup() {
  455. $directory = file_default_scheme() . '://styles';
  456. $this->assertTrue(file_prepare_directory($directory, FALSE), 'Directory created.');
  457. }
  458. }
  459. /**
  460. * Test required modules for tests.
  461. */
  462. class SimpleTestMissingDependentModuleUnitTest extends DrupalUnitTestCase {
  463. public static function getInfo() {
  464. return array(
  465. 'name' => 'Testing dependent module test',
  466. 'description' => 'This test should not load since it requires a module that is not found.',
  467. 'group' => 'SimpleTest',
  468. 'dependencies' => array('simpletest_missing_module'),
  469. );
  470. }
  471. /**
  472. * Ensure that this test will not be loaded despite its dependency.
  473. */
  474. function testFail() {
  475. $this->fail(t('Running test with missing required module.'));
  476. }
  477. }
  478. /**
  479. * Tests a test case that does not run parent::setUp() in its setUp() method.
  480. *
  481. * If a test case does not call parent::setUp(), running
  482. * DrupalTestCase::tearDown() would destroy the main site's database tables.
  483. * Therefore, we ensure that tests which are not set up properly are skipped.
  484. *
  485. * @see DrupalTestCase
  486. */
  487. class SimpleTestBrokenSetUp extends DrupalWebTestCase {
  488. public static function getInfo() {
  489. return array(
  490. 'name' => 'Broken SimpleTest method',
  491. 'description' => 'Tests a test case that does not call parent::setUp().',
  492. 'group' => 'SimpleTest'
  493. );
  494. }
  495. function setUp() {
  496. // If the test is being run from the main site, set up normally.
  497. if (!drupal_valid_test_ua()) {
  498. parent::setUp('simpletest');
  499. // Create and log in user.
  500. $admin_user = $this->drupalCreateUser(array('administer unit tests'));
  501. $this->drupalLogin($admin_user);
  502. }
  503. // If the test is being run from within simpletest, set up the broken test.
  504. else {
  505. $this->pass(t('The test setUp() method has been run.'));
  506. // Don't call parent::setUp(). This should trigger an error message.
  507. }
  508. }
  509. function tearDown() {
  510. // If the test is being run from the main site, tear down normally.
  511. if (!drupal_valid_test_ua()) {
  512. parent::tearDown();
  513. }
  514. else {
  515. // If the test is being run from within simpletest, output a message.
  516. $this->pass(t('The tearDown() method has run.'));
  517. }
  518. }
  519. /**
  520. * Runs this test case from within the simpletest child site.
  521. */
  522. function testBreakSetUp() {
  523. // If the test is being run from the main site, run it again from the web
  524. // interface within the simpletest child site.
  525. if (!drupal_valid_test_ua()) {
  526. $edit['SimpleTestBrokenSetUp'] = TRUE;
  527. $this->drupalPost('admin/config/development/testing', $edit, t('Run tests'));
  528. // Verify that the broken test and its tearDown() method are skipped.
  529. $this->assertRaw(t('The test setUp() method has been run.'));
  530. $this->assertRaw(t('The test cannot be executed because it has not been set up properly.'));
  531. $this->assertNoRaw(t('The test method has run.'));
  532. $this->assertNoRaw(t('The tearDown() method has run.'));
  533. }
  534. // If the test is being run from within simpletest, output a message.
  535. else {
  536. $this->pass(t('The test method has run.'));
  537. }
  538. }
  539. }
  540. /**
  541. * Verifies that tests bundled with installation profile modules are found.
  542. */
  543. class SimpleTestInstallationProfileModuleTestsTestCase extends DrupalWebTestCase {
  544. /**
  545. * Use the Testing profile.
  546. *
  547. * The Testing profile contains drupal_system_listing_compatible_test.test,
  548. * which attempts to:
  549. * - run tests using the Minimal profile (which does not contain the
  550. * drupal_system_listing_compatible_test.module)
  551. * - but still install the drupal_system_listing_compatible_test.module
  552. * contained in the Testing profile.
  553. *
  554. * @see DrupalSystemListingCompatibleTestCase
  555. */
  556. protected $profile = 'testing';
  557. public static function getInfo() {
  558. return array(
  559. 'name' => 'Installation profile module tests',
  560. 'description' => 'Verifies that tests bundled with installation profile modules are found.',
  561. 'group' => 'SimpleTest',
  562. );
  563. }
  564. function setUp() {
  565. parent::setUp(array('simpletest'));
  566. $this->admin_user = $this->drupalCreateUser(array('administer unit tests'));
  567. $this->drupalLogin($this->admin_user);
  568. }
  569. /**
  570. * Tests existence of test case located in an installation profile module.
  571. */
  572. function testInstallationProfileTests() {
  573. $this->drupalGet('admin/config/development/testing');
  574. $this->assertText('Installation profile module tests helper');
  575. $edit = array(
  576. 'DrupalSystemListingCompatibleTestCase' => TRUE,
  577. );
  578. $this->drupalPost(NULL, $edit, t('Run tests'));
  579. $this->assertText('DrupalSystemListingCompatibleTestCase test executed.');
  580. }
  581. }
  582. /**
  583. * Verifies that tests in other installation profiles are not found.
  584. *
  585. * @see SimpleTestInstallationProfileModuleTestsTestCase
  586. */
  587. class SimpleTestOtherInstallationProfileModuleTestsTestCase extends DrupalWebTestCase {
  588. /**
  589. * Use the Minimal profile.
  590. *
  591. * The Testing profile contains drupal_system_listing_compatible_test.test,
  592. * which should not be found.
  593. *
  594. * @see SimpleTestInstallationProfileModuleTestsTestCase
  595. * @see DrupalSystemListingCompatibleTestCase
  596. */
  597. protected $profile = 'minimal';
  598. public static function getInfo() {
  599. return array(
  600. 'name' => 'Other Installation profiles',
  601. 'description' => 'Verifies that tests in other installation profiles are not found.',
  602. 'group' => 'SimpleTest',
  603. );
  604. }
  605. function setUp() {
  606. parent::setUp(array('simpletest'));
  607. $this->admin_user = $this->drupalCreateUser(array('administer unit tests'));
  608. $this->drupalLogin($this->admin_user);
  609. }
  610. /**
  611. * Tests that tests located in another installation profile do not appear.
  612. */
  613. function testOtherInstallationProfile() {
  614. $this->drupalGet('admin/config/development/testing');
  615. $this->assertNoText('Installation profile module tests helper');
  616. }
  617. }
  618. /**
  619. * Verifies that tests in other installation profiles are not found.
  620. *
  621. * @see SimpleTestInstallationProfileModuleTestsTestCase
  622. */
  623. class SimpleTestDiscoveryTestCase extends DrupalWebTestCase {
  624. /**
  625. * Use the Testing profile.
  626. *
  627. * The Testing profile contains drupal_system_listing_compatible_test.test,
  628. * which attempts to:
  629. * - run tests using the Minimal profile (which does not contain the
  630. * drupal_system_listing_compatible_test.module)
  631. * - but still install the drupal_system_listing_compatible_test.module
  632. * contained in the Testing profile.
  633. *
  634. * @see DrupalSystemListingCompatibleTestCase
  635. */
  636. protected $profile = 'testing';
  637. public static function getInfo() {
  638. return array(
  639. 'name' => 'Discovery of test classes',
  640. 'description' => 'Verifies that tests classes are discovered and can be autoloaded (class_exists).',
  641. 'group' => 'SimpleTest',
  642. );
  643. }
  644. function setUp() {
  645. parent::setUp(array('simpletest'));
  646. $this->admin_user = $this->drupalCreateUser(array('administer unit tests'));
  647. $this->drupalLogin($this->admin_user);
  648. }
  649. /**
  650. * Test discovery of PSR-0 test classes.
  651. */
  652. function testDiscoveryFunctions() {
  653. if (version_compare(PHP_VERSION, '5.3') < 0) {
  654. // Don't expect PSR-0 tests to be discovered on older PHP versions.
  655. return;
  656. }
  657. // TODO: What if we have cached values? Do we need to force a cache refresh?
  658. $classes_all = simpletest_test_get_all();
  659. foreach (array(
  660. 'Drupal\\simpletest\\Tests\\PSR0WebTest',
  661. 'Drupal\\simpletest\\Tests\\PSR4WebTest',
  662. 'Drupal\\psr_0_test\\Tests\\ExampleTest',
  663. 'Drupal\\psr_4_test\\Tests\\ExampleTest',
  664. ) as $class) {
  665. $this->assert(!empty($classes_all['SimpleTest'][$class]), t('Class @class must be discovered by simpletest_test_get_all().', array('@class' => $class)));
  666. }
  667. }
  668. /**
  669. * Tests existence of test cases.
  670. */
  671. function testDiscovery() {
  672. $this->drupalGet('admin/config/development/testing');
  673. // Tests within enabled modules.
  674. // (without these, this test wouldn't happen in the first place, so this is
  675. // a bit pointless. We still run it for proof-of-concept.)
  676. // This one is defined in system module.
  677. $this->assertText('Drupal error handlers');
  678. // This one is defined in simpletest module.
  679. $this->assertText('Discovery of test classes');
  680. // Tests within disabled modules.
  681. if (version_compare(PHP_VERSION, '5.3') < 0) {
  682. // Don't expect PSR-0 tests to be discovered on older PHP versions.
  683. return;
  684. }
  685. // These are provided by simpletest itself via PSR-0 and PSR-4.
  686. $this->assertText('PSR0 web test');
  687. $this->assertText('PSR4 web test');
  688. $this->assertText('PSR0 example test: PSR-0 in disabled modules.');
  689. $this->assertText('PSR4 example test: PSR-4 in disabled modules.');
  690. $this->assertText('PSR0 example test: PSR-0 in nested subfolders.');
  691. $this->assertText('PSR4 example test: PSR-4 in nested subfolders.');
  692. // Test each test individually.
  693. foreach (array(
  694. 'Drupal\\psr_0_test\\Tests\\ExampleTest',
  695. 'Drupal\\psr_0_test\\Tests\\Nested\\NestedExampleTest',
  696. 'Drupal\\psr_4_test\\Tests\\ExampleTest',
  697. 'Drupal\\psr_4_test\\Tests\\Nested\\NestedExampleTest',
  698. ) as $class) {
  699. $this->drupalGet('admin/config/development/testing');
  700. $edit = array($class => TRUE);
  701. $this->drupalPost(NULL, $edit, t('Run tests'));
  702. $this->assertText('The test run finished', t('Test @class must finish.', array('@class' => $class)));
  703. $this->assertText('1 pass, 0 fails, and 0 exceptions', t('Test @class must pass.', array('@class' => $class)));
  704. }
  705. }
  706. }