simpletest.test 30 KB

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