simpletest.test 30 KB

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