simpletest.module 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. <?php
  2. /**
  3. * @file
  4. * Provides testing functionality.
  5. */
  6. use Drupal\Component\Uuid\Php;
  7. use Drupal\Core\Asset\AttachedAssets;
  8. use Drupal\Core\Asset\AttachedAssetsInterface;
  9. use Drupal\Core\Database\Database;
  10. use Drupal\Core\File\Exception\FileException;
  11. use Drupal\Core\File\FileSystemInterface;
  12. use Drupal\Core\Render\Element;
  13. use Drupal\Core\Routing\RouteMatchInterface;
  14. use Drupal\Core\StreamWrapper\PublicStream;
  15. use Drupal\Core\Test\JUnitConverter;
  16. use Drupal\Core\Test\PhpUnitTestRunner;
  17. use Drupal\Core\Test\TestDatabase;
  18. use Drupal\Core\Url;
  19. use Drupal\simpletest\Form\SimpletestResultsForm;
  20. use Drupal\simpletest\TestDiscovery;
  21. use PHPUnit\Framework\TestCase;
  22. /**
  23. * Implements hook_help().
  24. */
  25. function simpletest_help($route_name, RouteMatchInterface $route_match) {
  26. switch ($route_name) {
  27. case 'help.page.simpletest':
  28. $output = '';
  29. $output .= '<h3>' . t('About') . '</h3>';
  30. $output .= '<p>' . t('The Testing module provides a framework for running automated tests. It can be used to verify a working state of Drupal before and after any code changes, or as a means for developers to write and execute tests for their modules. For more information, see the <a href=":simpletest">online documentation for the Testing module</a>.', [':simpletest' => 'https://www.drupal.org/documentation/modules/simpletest']) . '</p>';
  31. $output .= '<h3>' . t('Uses') . '</h3>';
  32. $output .= '<dl>';
  33. $output .= '<dt>' . t('Running tests') . '</dt>';
  34. $output .= '<dd><p>' . t('Visit the <a href=":admin-simpletest">Testing page</a> to display a list of available tests. For comprehensive testing, select <em>all</em> tests, or individually select tests for more targeted testing. Note that it might take several minutes for all tests to complete.', [':admin-simpletest' => Url::fromRoute('simpletest.test_form')->toString()]) . '</p>';
  35. $output .= '<p>' . t('After the tests run, a message will be displayed next to each test group indicating whether tests within it passed, failed, or had exceptions. A pass means that the test returned the expected results, while fail means that it did not. An exception normally indicates an error outside of the test, such as a PHP warning or notice. If there were failures or exceptions, the results will be expanded to show details, and the tests that had failures or exceptions will be indicated in red or pink rows. You can then use these results to refine your code and tests, until all tests pass.') . '</p></dd>';
  36. $output .= '</dl>';
  37. return $output;
  38. case 'simpletest.test_form':
  39. $output = t('Select the test(s) or test group(s) you would like to run, and click <em>Run tests</em>.');
  40. return $output;
  41. }
  42. }
  43. /**
  44. * Implements hook_theme().
  45. */
  46. function simpletest_theme() {
  47. return [
  48. 'simpletest_result_summary' => [
  49. 'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0],
  50. ],
  51. ];
  52. }
  53. /**
  54. * Implements hook_js_alter().
  55. */
  56. function simpletest_js_alter(&$javascript, AttachedAssetsInterface $assets) {
  57. // Since SimpleTest is a special use case for the table select, stick the
  58. // SimpleTest JavaScript above the table select.
  59. $simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js';
  60. if (array_key_exists($simpletest, $javascript) && array_key_exists('core/misc/tableselect.js', $javascript)) {
  61. $javascript[$simpletest]['weight'] = $javascript['core/misc/tableselect.js']['weight'] - 1;
  62. }
  63. }
  64. /**
  65. * Prepares variables for simpletest result summary templates.
  66. *
  67. * Default template: simpletest-result-summary.html.twig.
  68. *
  69. * @param array $variables
  70. * An associative array containing:
  71. * - label: An optional label to be rendered before the results.
  72. * - ok: The overall group result pass or fail.
  73. * - pass: The number of passes.
  74. * - fail: The number of fails.
  75. * - exception: The number of exceptions.
  76. * - debug: The number of debug messages.
  77. */
  78. function template_preprocess_simpletest_result_summary(&$variables) {
  79. $variables['items'] = _simpletest_build_summary_line($variables);
  80. }
  81. /**
  82. * Formats each test result type pluralized summary.
  83. *
  84. * @param array $summary
  85. * A summary of the test results.
  86. *
  87. * @return array
  88. * The pluralized test summary items.
  89. */
  90. function _simpletest_build_summary_line($summary) {
  91. $translation = \Drupal::translation();
  92. $items['pass'] = $translation->formatPlural($summary['pass'], '1 pass', '@count passes');
  93. $items['fail'] = $translation->formatPlural($summary['fail'], '1 fail', '@count fails');
  94. $items['exception'] = $translation->formatPlural($summary['exception'], '1 exception', '@count exceptions');
  95. if ($summary['debug']) {
  96. $items['debug'] = $translation->formatPlural($summary['debug'], '1 debug message', '@count debug messages');
  97. }
  98. return $items;
  99. }
  100. /**
  101. * Formats test result summaries into a comma separated string for run-tests.sh.
  102. *
  103. * @param array $summary
  104. * A summary of the test results.
  105. *
  106. * @return string
  107. * A concatenated string of the formatted test results.
  108. */
  109. function _simpletest_format_summary_line($summary) {
  110. $parts = _simpletest_build_summary_line($summary);
  111. return implode(', ', $parts);
  112. }
  113. /**
  114. * Runs tests.
  115. *
  116. * @param array[] $test_list
  117. * List of tests to run. The top level is keyed by type of test, either
  118. * 'simpletest' or 'phpunit'. Under that is an array of class names to run.
  119. *
  120. * @return string
  121. * The test ID.
  122. */
  123. function simpletest_run_tests($test_list) {
  124. // We used to separate PHPUnit and Simpletest tests for a performance
  125. // optimization. In order to support backwards compatibility check if these
  126. // keys are set and create a single test list.
  127. // @todo https://www.drupal.org/node/2748967 Remove BC support in Drupal 9.
  128. if (isset($test_list['simpletest'])) {
  129. $test_list = array_merge($test_list, $test_list['simpletest']);
  130. unset($test_list['simpletest']);
  131. }
  132. if (isset($test_list['phpunit'])) {
  133. $test_list = array_merge($test_list, $test_list['phpunit']);
  134. unset($test_list['phpunit']);
  135. }
  136. $test_id = \Drupal::database()->insert('simpletest_test_id')
  137. ->useDefaults(['test_id'])
  138. ->execute();
  139. // Clear out the previous verbose files.
  140. try {
  141. \Drupal::service('file_system')->deleteRecursive('public://simpletest/verbose');
  142. }
  143. catch (FileException $e) {
  144. // Ignore failed deletes.
  145. }
  146. // Get the info for the first test being run.
  147. $first_test = reset($test_list);
  148. $info = TestDiscovery::getTestInfo($first_test);
  149. $batch = [
  150. 'title' => t('Running tests'),
  151. 'operations' => [
  152. ['_simpletest_batch_operation', [$test_list, $test_id]],
  153. ],
  154. 'finished' => '_simpletest_batch_finished',
  155. 'progress_message' => '',
  156. 'library' => ['simpletest/drupal.simpletest'],
  157. 'init_message' => t('Processing test @num of @max - %test.', ['%test' => $info['name'], '@num' => '1', '@max' => count($test_list)]),
  158. ];
  159. batch_set($batch);
  160. \Drupal::moduleHandler()->invokeAllDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242', 'test_group_started');
  161. return $test_id;
  162. }
  163. /**
  164. * Executes PHPUnit tests and returns the results of the run.
  165. *
  166. * @param $test_id
  167. * The current test ID.
  168. * @param $unescaped_test_classnames
  169. * An array of test class names, including full namespaces, to be passed as
  170. * a regular expression to PHPUnit's --filter option.
  171. * @param int $status
  172. * (optional) The exit status code of the PHPUnit process will be assigned to
  173. * this variable.
  174. *
  175. * @return array
  176. * The parsed results of PHPUnit's JUnit XML output, in the format of
  177. * {simpletest}'s schema.
  178. *
  179. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  180. * \Drupal\Core\Test\PhpUnitTestRunner::runTests() instead.
  181. *
  182. * @see https://www.drupal.org/node/2948547
  183. */
  184. function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames, &$status = NULL) {
  185. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  186. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::runTests() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  187. return $runner->runTests($test_id, $unescaped_test_classnames, $status);
  188. }
  189. /**
  190. * Inserts the parsed PHPUnit results into {simpletest}.
  191. *
  192. * @param array[] $phpunit_results
  193. * An array of test results returned from simpletest_phpunit_xml_to_rows().
  194. *
  195. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  196. * \Drupal\Core\Test\TestDatabase::processPhpUnitResults() instead.
  197. *
  198. * @see https://www.drupal.org/node/3075252
  199. */
  200. function simpletest_process_phpunit_results($phpunit_results) {
  201. @trigger_error(__FUNCTION__ . '() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::processPhpUnitResults() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
  202. TestDatabase::processPhpUnitResults($phpunit_results);
  203. }
  204. /**
  205. * Maps phpunit results to a data structure for batch messages and run-tests.sh.
  206. *
  207. * @param array $results
  208. * The output from simpletest_run_phpunit_tests().
  209. *
  210. * @return array
  211. * The test result summary. A row per test class.
  212. *
  213. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  214. * \Drupal\Core\Test\PhpUnitTestRunner::summarizeResults() instead.
  215. *
  216. * @see https://www.drupal.org/node/2948547
  217. */
  218. function simpletest_summarize_phpunit_result($results) {
  219. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  220. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::summarizeResults() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  221. return $runner->summarizeResults($results);
  222. }
  223. /**
  224. * Returns the path to use for PHPUnit's --log-junit option.
  225. *
  226. * @param $test_id
  227. * The current test ID.
  228. *
  229. * @return string
  230. * Path to the PHPUnit XML file to use for the current $test_id.
  231. *
  232. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  233. * \Drupal\Core\Test\PhpUnitTestRunner::xmlLogFilepath() instead.
  234. *
  235. * @see https://www.drupal.org/node/2948547
  236. */
  237. function simpletest_phpunit_xml_filepath($test_id) {
  238. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  239. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::xmlLogFilepath() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  240. return $runner->xmlLogFilePath($test_id);
  241. }
  242. /**
  243. * Returns the path to core's phpunit.xml.dist configuration file.
  244. *
  245. * @return string
  246. * The path to core's phpunit.xml.dist configuration file.
  247. *
  248. * @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. PHPUnit test
  249. * runners should change directory into core/ and then run the phpunit tool.
  250. * See simpletest_phpunit_run_command() for an example.
  251. *
  252. * @see simpletest_phpunit_run_command()
  253. */
  254. function simpletest_phpunit_configuration_filepath() {
  255. @trigger_error('The ' . __FUNCTION__ . ' function is deprecated since version 8.4.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
  256. return \Drupal::root() . '/core/phpunit.xml.dist';
  257. }
  258. /**
  259. * Executes the PHPUnit command.
  260. *
  261. * @param array $unescaped_test_classnames
  262. * An array of test class names, including full namespaces, to be passed as
  263. * a regular expression to PHPUnit's --filter option.
  264. * @param string $phpunit_file
  265. * A filepath to use for PHPUnit's --log-junit option.
  266. * @param int $status
  267. * (optional) The exit status code of the PHPUnit process will be assigned to
  268. * this variable.
  269. * @param string $output
  270. * (optional) The output by running the phpunit command.
  271. *
  272. * @return string
  273. * The results as returned by exec().
  274. *
  275. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  276. * \Drupal\Core\Test\PhpUnitTestRunner::runCommand() instead.
  277. *
  278. * @see https://www.drupal.org/node/2948547
  279. */
  280. function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) {
  281. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  282. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::runCommand() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  283. return $runner->runCommand($unescaped_test_classnames, $phpunit_file, $status, $output);
  284. }
  285. /**
  286. * Returns the command to run PHPUnit.
  287. *
  288. * @return string
  289. * The command that can be run through exec().
  290. *
  291. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  292. * \Drupal\Core\Test\PhpUnitTestRunner::phpUnitCommand() instead.
  293. *
  294. * @see https://www.drupal.org/node/2948547
  295. */
  296. function simpletest_phpunit_command() {
  297. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  298. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::phpUnitCommand() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  299. return $runner->phpUnitCommand();
  300. }
  301. /**
  302. * Implements callback_batch_operation().
  303. */
  304. function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
  305. \Drupal::service('test_discovery')->registerTestNamespaces();
  306. // Get working values.
  307. if (!isset($context['sandbox']['max'])) {
  308. // First iteration: initialize working values.
  309. $test_list = $test_list_init;
  310. $context['sandbox']['max'] = count($test_list);
  311. $test_results = ['#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0];
  312. }
  313. else {
  314. // Nth iteration: get the current values where we last stored them.
  315. $test_list = $context['sandbox']['tests'];
  316. $test_results = $context['sandbox']['test_results'];
  317. }
  318. $max = $context['sandbox']['max'];
  319. // Perform the next test.
  320. $test_class = array_shift($test_list);
  321. if (is_subclass_of($test_class, TestCase::class)) {
  322. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  323. $phpunit_results = $runner->runTests($test_id, [$test_class]);
  324. TestDatabase::processPhpUnitResults($phpunit_results);
  325. $test_results[$test_class] = simpletest_summarize_phpunit_result($phpunit_results)[$test_class];
  326. }
  327. else {
  328. $test = new $test_class($test_id);
  329. $test->run();
  330. \Drupal::moduleHandler()->invokeAllDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242', 'test_finished', [$test->results]);
  331. $test_results[$test_class] = $test->results;
  332. }
  333. $size = count($test_list);
  334. $info = TestDiscovery::getTestInfo($test_class);
  335. // Gather results and compose the report.
  336. foreach ($test_results[$test_class] as $key => $value) {
  337. $test_results[$key] += $value;
  338. }
  339. $test_results[$test_class]['#name'] = $info['name'];
  340. $items = [];
  341. foreach (Element::children($test_results) as $class) {
  342. $class_test_result = $test_results[$class] + [
  343. '#theme' => 'simpletest_result_summary',
  344. '#label' => t($test_results[$class]['#name'] . ':'),
  345. ];
  346. array_unshift($items, \Drupal::service('renderer')->render($class_test_result));
  347. }
  348. $context['message'] = t('Processed test @num of @max - %test.', ['%test' => $info['name'], '@num' => $max - $size, '@max' => $max]);
  349. $overall_results = $test_results + [
  350. '#theme' => 'simpletest_result_summary',
  351. '#label' => t('Overall results:'),
  352. ];
  353. $context['message'] .= \Drupal::service('renderer')->render($overall_results);
  354. $item_list = [
  355. '#theme' => 'item_list',
  356. '#items' => $items,
  357. ];
  358. $context['message'] .= \Drupal::service('renderer')->render($item_list);
  359. // Save working values for the next iteration.
  360. $context['sandbox']['tests'] = $test_list;
  361. $context['sandbox']['test_results'] = $test_results;
  362. // The test_id is the only thing we need to save for the report page.
  363. $context['results']['test_id'] = $test_id;
  364. // Multistep processing: report progress.
  365. $context['finished'] = 1 - $size / $max;
  366. }
  367. /**
  368. * Implements callback_batch_finished().
  369. */
  370. function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
  371. if ($success) {
  372. \Drupal::messenger()->addStatus(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
  373. }
  374. else {
  375. // Use the test_id passed as a parameter to _simpletest_batch_operation().
  376. $test_id = $operations[0][1][1];
  377. // Retrieve the last database prefix used for testing and the last test
  378. // class that was run from. Use the information to read the lgo file
  379. // in case any fatal errors caused the test to crash.
  380. $last_test = TestDatabase::lastTestGet($test_id);
  381. (new TestDatabase($last_test['last_prefix']))->logRead($test_id, $last_test['test_class']);
  382. \Drupal::messenger()->addError(t('The test run did not successfully finish.'));
  383. \Drupal::messenger()->addWarning(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'));
  384. }
  385. \Drupal::moduleHandler()->invokeAllDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242', 'test_group_finished');
  386. }
  387. /**
  388. * Get information about the last test that ran given a test ID.
  389. *
  390. * @param $test_id
  391. * The test ID to get the last test from.
  392. *
  393. * @return array
  394. * Array containing the last database prefix used and the last test class
  395. * that ran.
  396. *
  397. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  398. * \Drupal\Core\Test\TestDatabase::lastTestGet() instead.
  399. *
  400. * @see https://www.drupal.org/node/3075252
  401. */
  402. function simpletest_last_test_get($test_id) {
  403. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::lastTestGet() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
  404. return array_values(TestDatabase::lastTestGet($test_id));
  405. }
  406. /**
  407. * Reads the error log and reports any errors as assertion failures.
  408. *
  409. * The errors in the log should only be fatal errors since any other errors
  410. * will have been recorded by the error handler.
  411. *
  412. * @param $test_id
  413. * The test ID to which the log relates.
  414. * @param $database_prefix
  415. * The database prefix to which the log relates.
  416. * @param $test_class
  417. * The test class to which the log relates.
  418. *
  419. * @return bool
  420. * Whether any fatal errors were found.
  421. *
  422. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  423. * \Drupal\Core\Test\TestDatabase::logRead() instead.
  424. *
  425. * @see https://www.drupal.org/node/3075252
  426. */
  427. function simpletest_log_read($test_id, $database_prefix, $test_class) {
  428. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::logRead() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
  429. $test_db = new TestDatabase($database_prefix);
  430. return $test_db->logRead($test_id, $test_class);
  431. }
  432. /**
  433. * Store an assertion from outside the testing context.
  434. *
  435. * This is useful for inserting assertions that can only be recorded after
  436. * the test case has been destroyed, such as PHP fatal errors. The caller
  437. * information is not automatically gathered since the caller is most likely
  438. * inserting the assertion on behalf of other code. In all other respects
  439. * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
  440. * of storing the assertion.
  441. *
  442. * @param string $test_id
  443. * The test ID to which the assertion relates.
  444. * @param string $test_class
  445. * The test class to store an assertion for.
  446. * @param bool|string $status
  447. * A boolean or a string of 'pass' or 'fail'. TRUE means 'pass'.
  448. * @param string $message
  449. * The assertion message.
  450. * @param string $group
  451. * The assertion message group.
  452. * @param array $caller
  453. * The an array containing the keys 'file' and 'line' that represent the file
  454. * and line number of that file that is responsible for the assertion.
  455. *
  456. * @return
  457. * Message ID of the stored assertion.
  458. *
  459. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  460. * \Drupal\Core\Test\TestDatabase::insertAssert() instead.
  461. *
  462. * @see https://www.drupal.org/node/3075252
  463. */
  464. function simpletest_insert_assert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
  465. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::insertAssert() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
  466. TestDatabase::insertAssert($test_id, $test_class, $status, $message, $group, $caller);
  467. }
  468. /**
  469. * Gets a list of all of the tests provided by the system.
  470. *
  471. * The list of test classes is loaded by searching the designated directory for
  472. * each module for files matching the PSR-4 standard. Once loaded the test list
  473. * is cached and stored in a static variable.
  474. *
  475. * @param string $extension
  476. * (optional) The name of an extension to limit discovery to; e.g., 'node'.
  477. * @param string[] $types
  478. * An array of included test types.
  479. *
  480. * @return array[]
  481. * An array of tests keyed with the groups, and then keyed by test classes.
  482. * For example:
  483. * @code
  484. * $groups['Block'] => array(
  485. * 'BlockTestCase' => array(
  486. * 'name' => 'Block functionality',
  487. * 'description' => 'Add, edit and delete custom block.',
  488. * 'group' => 'Block',
  489. * ),
  490. * );
  491. * @endcode
  492. *
  493. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use
  494. * \Drupal::service('test_discovery')->getTestClasses($extension, $types)
  495. * instead.
  496. */
  497. function simpletest_test_get_all($extension = NULL, array $types = []) {
  498. @trigger_error('The ' . __FUNCTION__ . ' function is deprecated in version 8.3.x and will be removed in 9.0.0. Use \Drupal::service(\'test_discovery\')->getTestClasses($extension, $types) instead.', E_USER_DEPRECATED);
  499. return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
  500. }
  501. /**
  502. * Registers test namespaces of all extensions and core test classes.
  503. *
  504. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use
  505. * \Drupal::service('test_discovery')->registerTestNamespaces() instead.
  506. */
  507. function simpletest_classloader_register() {
  508. @trigger_error('The ' . __FUNCTION__ . ' function is deprecated in version 8.3.x and will be removed in 9.0.0. Use \Drupal::service(\'test_discovery\')->registerTestNamespaces() instead.', E_USER_DEPRECATED);
  509. \Drupal::service('test_discovery')->registerTestNamespaces();
  510. }
  511. /**
  512. * Generates a test file.
  513. *
  514. * @param string $filename
  515. * The name of the file, including the path. The suffix '.txt' is appended to
  516. * the supplied file name and the file is put into the public:// files
  517. * directory.
  518. * @param int $width
  519. * The number of characters on one line.
  520. * @param int $lines
  521. * The number of lines in the file.
  522. * @param string $type
  523. * (optional) The type, one of:
  524. * - text: The generated file contains random ASCII characters.
  525. * - binary: The generated file contains random characters whose codes are in
  526. * the range of 0 to 31.
  527. * - binary-text: The generated file contains random sequence of '0' and '1'
  528. * values.
  529. *
  530. * @return string
  531. * The name of the file, including the path.
  532. *
  533. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  534. * \Drupal\Tests\TestFileCreationTrait::generateFile() instead.
  535. *
  536. * @see https://www.drupal.org/node/3077768
  537. */
  538. function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  539. @trigger_error(__FUNCTION__ . '() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Tests\TestFileCreationTrait::generateFile() instead. See https://www.drupal.org/node/3077768', E_USER_DEPRECATED);
  540. $text = '';
  541. for ($i = 0; $i < $lines; $i++) {
  542. // Generate $width - 1 characters to leave space for the "\n" character.
  543. for ($j = 0; $j < $width - 1; $j++) {
  544. switch ($type) {
  545. case 'text':
  546. $text .= chr(rand(32, 126));
  547. break;
  548. case 'binary':
  549. $text .= chr(rand(0, 31));
  550. break;
  551. case 'binary-text':
  552. default:
  553. $text .= rand(0, 1);
  554. break;
  555. }
  556. }
  557. $text .= "\n";
  558. }
  559. // Create filename.
  560. file_put_contents('public://' . $filename . '.txt', $text);
  561. return $filename;
  562. }
  563. /**
  564. * Removes all temporary database tables and directories.
  565. *
  566. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  567. * environment_cleaner service and call its cleanEnvironment() method, or use
  568. * \Drupal\Core\Test\EnvironmentCleaner::cleanEnvironment() instead.
  569. *
  570. * @see https://www.drupal.org/node/3076634
  571. */
  572. function simpletest_clean_environment() {
  573. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanEnvironment() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanEnvironment() instead.. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
  574. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  575. $cleaner = \Drupal::service('environment_cleaner');
  576. $cleaner->cleanEnvironment();
  577. }
  578. /**
  579. * Removes prefixed tables from the database from crashed tests.
  580. *
  581. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  582. * environment_cleaner service and call its cleanDatabase() method, or use
  583. * \Drupal\Core\Test\EnvironmentCleaner::cleanDatabase() instead.
  584. *
  585. * @see https://www.drupal.org/node/3076634
  586. */
  587. function simpletest_clean_database() {
  588. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanDatabase() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanDatabase() instead. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
  589. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  590. $cleaner = \Drupal::service('environment_cleaner');
  591. $cleaner->cleanDatabase();
  592. }
  593. /**
  594. * Finds all leftover temporary directories and removes them.
  595. *
  596. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  597. * environment_cleaner service and call its cleanTemporaryDirectories()
  598. * method, or use
  599. * \Drupal\Core\Test\EnvironmentCleaner::cleanTemporaryDirectories() instead.
  600. *
  601. * @see https://www.drupal.org/node/3076634
  602. */
  603. function simpletest_clean_temporary_directories() {
  604. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanTemporaryDirectories() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanTemporaryDirectories() instead. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
  605. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  606. $cleaner = \Drupal::service('environment_cleaner');
  607. $cleaner->cleanTemporaryDirectories();
  608. }
  609. /**
  610. * Clears the test result tables.
  611. *
  612. * @param $test_id
  613. * Test ID to remove results for, or NULL to remove all results.
  614. *
  615. * @return int
  616. * The number of results that were removed.
  617. *
  618. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  619. * environment_cleaner service and call its cleanResultsTable() method, or use
  620. * \Drupal\Core\Test\EnvironmentCleaner::cleanResultsTable() instead.
  621. *
  622. * @see https://www.drupal.org/node/3076634
  623. */
  624. function simpletest_clean_results_table($test_id = NULL) {
  625. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanResultsTable() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanResultsTable() instead. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
  626. $count = 0;
  627. if (\Drupal::config('simpletest.settings')->get('clear_results')) {
  628. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  629. $cleaner = \Drupal::service('environment_cleaner');
  630. $count = $cleaner->cleanResultsTable($test_id);
  631. }
  632. return $count;
  633. }
  634. /**
  635. * Converts PHPUnit's JUnit XML output to an array.
  636. *
  637. * @param $test_id
  638. * The current test ID.
  639. * @param $phpunit_xml_file
  640. * Path to the PHPUnit XML file.
  641. *
  642. * @return array[]|null
  643. * The results as array of rows in a format that can be inserted into
  644. * {simpletest}. If the phpunit_xml_file does not have any contents then the
  645. * function will return NULL.
  646. *
  647. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  648. * \Drupal\Core\Test\JUnitConverter::xmlToRows() instead.
  649. *
  650. * @see https://www.drupal.org/node/2948547
  651. */
  652. function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
  653. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::xmlToRows() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  654. return JUnitConverter::xmlToRows($test_id, $phpunit_xml_file) ?: NULL;
  655. }
  656. /**
  657. * Finds all test cases recursively from a test suite list.
  658. *
  659. * @param \SimpleXMLElement $element
  660. * The PHPUnit xml to search for test cases.
  661. * @param \SimpleXMLElement $parent
  662. * (Optional) The parent of the current element. Defaults to NULL.
  663. *
  664. * @return array
  665. * A list of all test cases.
  666. *
  667. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  668. * \Drupal\Core\Test\JUnitConverter::findTestCases() instead.
  669. *
  670. * @see https://www.drupal.org/node/2948547
  671. */
  672. function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
  673. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::findTestCases() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  674. return JUnitConverter::findTestCases($element, $parent);
  675. }
  676. /**
  677. * Converts a PHPUnit test case result to a {simpletest} result row.
  678. *
  679. * @param int $test_id
  680. * The current test ID.
  681. * @param \SimpleXMLElement $test_case
  682. * The PHPUnit test case represented as XML element.
  683. *
  684. * @return array
  685. * An array containing the {simpletest} result row.
  686. *
  687. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  688. * \Drupal\Core\Test\JUnitConverter::convertTestCaseToSimpletestRow() instead.
  689. *
  690. * @see https://www.drupal.org/node/2948547
  691. */
  692. function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $test_case) {
  693. @trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::convertTestCaseToSimpletestRow() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
  694. return JUnitConverter::convertTestCaseToSimpletestRow($test_id, $test_case);
  695. }
  696. /**
  697. * Display test results from run-tests.sh in a browser.
  698. *
  699. * @internal
  700. * This function is only used by run-tests.sh
  701. *
  702. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. This function
  703. * supports the --browser option in this script. Use the --verbose option
  704. * instead.
  705. *
  706. * @see https://www.drupal.org/node/3083549
  707. */
  708. function _simpletest_run_tests_script_open_browser() {
  709. global $test_ids;
  710. try {
  711. $connection = Database::getConnection('default', 'test-runner');
  712. $results = $connection->select('simpletest')
  713. ->fields('simpletest')
  714. ->condition('test_id', $test_ids, 'IN')
  715. ->orderBy('test_class')
  716. ->orderBy('message_id')
  717. ->execute()
  718. ->fetchAll();
  719. }
  720. catch (Exception $e) {
  721. echo (string) $e;
  722. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  723. }
  724. // Get the results form.
  725. $form = [];
  726. SimpletestResultsForm::addResultForm($form, $results);
  727. // Get the assets to make the details element collapsible and theme the result
  728. // form.
  729. $assets = new AttachedAssets();
  730. $assets->setLibraries([
  731. 'core/drupal.collapse',
  732. 'system/admin',
  733. 'simpletest/drupal.simpletest',
  734. ]);
  735. $resolver = \Drupal::service('asset.resolver');
  736. list($js_assets_header, $js_assets_footer) = $resolver->getJsAssets($assets, FALSE);
  737. $js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
  738. $js_assets_header = $js_collection_renderer->render($js_assets_header);
  739. $js_assets_footer = $js_collection_renderer->render($js_assets_footer);
  740. $css_assets = \Drupal::service('asset.css.collection_renderer')->render($resolver->getCssAssets($assets, FALSE));
  741. // Make the html page to write to disk.
  742. $render_service = \Drupal::service('renderer');
  743. $html = '<head>' . $render_service->renderPlain($js_assets_header) . $render_service->renderPlain($css_assets) . '</head><body>' . $render_service->renderPlain($form) . $render_service->renderPlain($js_assets_footer) . '</body>';
  744. // Ensure we have assets verbose directory - tests with no verbose output will
  745. // not have created one.
  746. $directory = PublicStream::basePath() . '/simpletest/verbose';
  747. \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
  748. $php = new Php();
  749. $uuid = $php->generate();
  750. $filename = $directory . '/results-' . $uuid . '.html';
  751. $base_url = getenv('SIMPLETEST_BASE_URL');
  752. if (empty($base_url)) {
  753. simpletest_script_print_error("--browser needs argument --url.");
  754. }
  755. $url = $base_url . '/' . PublicStream::basePath() . '/simpletest/verbose/results-' . $uuid . '.html';
  756. file_put_contents($filename, $html);
  757. // See if we can find an OS helper to open URLs in default browser.
  758. $browser = FALSE;
  759. if (shell_exec('which xdg-open')) {
  760. $browser = 'xdg-open';
  761. }
  762. elseif (shell_exec('which open')) {
  763. $browser = 'open';
  764. }
  765. elseif (substr(PHP_OS, 0, 3) == 'WIN') {
  766. $browser = 'start';
  767. }
  768. if ($browser) {
  769. shell_exec($browser . ' ' . escapeshellarg($url));
  770. }
  771. else {
  772. // Can't find assets valid browser.
  773. print 'Open file://' . realpath($filename) . ' in your browser to see the verbose output.';
  774. }
  775. }