simpletest.module 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. * @return array
  393. * Array containing the last database prefix used and the last test class
  394. * that ran.
  395. *
  396. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  397. * \Drupal\Core\Test\TestDatabase::lastTestGet() instead.
  398. *
  399. * @see https://www.drupal.org/node/3075252
  400. */
  401. function simpletest_last_test_get($test_id) {
  402. @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);
  403. return array_values(TestDatabase::lastTestGet($test_id));
  404. }
  405. /**
  406. * Reads the error log and reports any errors as assertion failures.
  407. *
  408. * The errors in the log should only be fatal errors since any other errors
  409. * will have been recorded by the error handler.
  410. *
  411. * @param $test_id
  412. * The test ID to which the log relates.
  413. * @param $database_prefix
  414. * The database prefix to which the log relates.
  415. * @param $test_class
  416. * The test class to which the log relates.
  417. *
  418. * @return bool
  419. * Whether any fatal errors were found.
  420. *
  421. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  422. * \Drupal\Core\Test\TestDatabase::logRead() instead.
  423. *
  424. * @see https://www.drupal.org/node/3075252
  425. */
  426. function simpletest_log_read($test_id, $database_prefix, $test_class) {
  427. @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);
  428. $test_db = new TestDatabase($database_prefix);
  429. return $test_db->logRead($test_id, $test_class);
  430. }
  431. /**
  432. * Store an assertion from outside the testing context.
  433. *
  434. * This is useful for inserting assertions that can only be recorded after
  435. * the test case has been destroyed, such as PHP fatal errors. The caller
  436. * information is not automatically gathered since the caller is most likely
  437. * inserting the assertion on behalf of other code. In all other respects
  438. * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
  439. * of storing the assertion.
  440. *
  441. * @param string $test_id
  442. * The test ID to which the assertion relates.
  443. * @param string $test_class
  444. * The test class to store an assertion for.
  445. * @param bool|string $status
  446. * A boolean or a string of 'pass' or 'fail'. TRUE means 'pass'.
  447. * @param string $message
  448. * The assertion message.
  449. * @param string $group
  450. * The assertion message group.
  451. * @param array $caller
  452. * The an array containing the keys 'file' and 'line' that represent the file
  453. * and line number of that file that is responsible for the assertion.
  454. *
  455. * @return
  456. * Message ID of the stored assertion.
  457. *
  458. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  459. * \Drupal\Core\Test\TestDatabase::insertAssert() instead.
  460. *
  461. * @see https://www.drupal.org/node/3075252
  462. */
  463. function simpletest_insert_assert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
  464. @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);
  465. TestDatabase::insertAssert($test_id, $test_class, $status, $message, $group, $caller);
  466. }
  467. /**
  468. * Gets a list of all of the tests provided by the system.
  469. *
  470. * The list of test classes is loaded by searching the designated directory for
  471. * each module for files matching the PSR-4 standard. Once loaded the test list
  472. * is cached and stored in a static variable.
  473. *
  474. * @param string $extension
  475. * (optional) The name of an extension to limit discovery to; e.g., 'node'.
  476. * @param string[] $types
  477. * An array of included test types.
  478. *
  479. * @return array[]
  480. * An array of tests keyed with the groups, and then keyed by test classes.
  481. * For example:
  482. * @code
  483. * $groups['Block'] => array(
  484. * 'BlockTestCase' => array(
  485. * 'name' => 'Block functionality',
  486. * 'description' => 'Add, edit and delete custom block.',
  487. * 'group' => 'Block',
  488. * ),
  489. * );
  490. * @endcode
  491. *
  492. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use
  493. * \Drupal::service('test_discovery')->getTestClasses($extension, $types)
  494. * instead.
  495. */
  496. function simpletest_test_get_all($extension = NULL, array $types = []) {
  497. @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);
  498. return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
  499. }
  500. /**
  501. * Registers test namespaces of all extensions and core test classes.
  502. *
  503. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use
  504. * \Drupal::service('test_discovery')->registerTestNamespaces() instead.
  505. */
  506. function simpletest_classloader_register() {
  507. @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);
  508. \Drupal::service('test_discovery')->registerTestNamespaces();
  509. }
  510. /**
  511. * Generates a test file.
  512. *
  513. * @param string $filename
  514. * The name of the file, including the path. The suffix '.txt' is appended to
  515. * the supplied file name and the file is put into the public:// files
  516. * directory.
  517. * @param int $width
  518. * The number of characters on one line.
  519. * @param int $lines
  520. * The number of lines in the file.
  521. * @param string $type
  522. * (optional) The type, one of:
  523. * - text: The generated file contains random ASCII characters.
  524. * - binary: The generated file contains random characters whose codes are in
  525. * the range of 0 to 31.
  526. * - binary-text: The generated file contains random sequence of '0' and '1'
  527. * values.
  528. *
  529. * @return string
  530. * The name of the file, including the path.
  531. *
  532. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  533. * \Drupal\Tests\TestFileCreationTrait::generateFile() instead.
  534. *
  535. * @see https://www.drupal.org/node/3077768
  536. */
  537. function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  538. @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);
  539. $text = '';
  540. for ($i = 0; $i < $lines; $i++) {
  541. // Generate $width - 1 characters to leave space for the "\n" character.
  542. for ($j = 0; $j < $width - 1; $j++) {
  543. switch ($type) {
  544. case 'text':
  545. $text .= chr(rand(32, 126));
  546. break;
  547. case 'binary':
  548. $text .= chr(rand(0, 31));
  549. break;
  550. case 'binary-text':
  551. default:
  552. $text .= rand(0, 1);
  553. break;
  554. }
  555. }
  556. $text .= "\n";
  557. }
  558. // Create filename.
  559. file_put_contents('public://' . $filename . '.txt', $text);
  560. return $filename;
  561. }
  562. /**
  563. * Removes all temporary database tables and directories.
  564. *
  565. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  566. * environment_cleaner service and call its cleanEnvironment() method, or use
  567. * \Drupal\Core\Test\EnvironmentCleaner::cleanEnvironment() instead.
  568. *
  569. * @see https://www.drupal.org/node/3076634
  570. */
  571. function simpletest_clean_environment() {
  572. @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);
  573. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  574. $cleaner = \Drupal::service('environment_cleaner');
  575. $cleaner->cleanEnvironment();
  576. }
  577. /**
  578. * Removes prefixed tables from the database from crashed tests.
  579. *
  580. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  581. * environment_cleaner service and call its cleanDatabase() method, or use
  582. * \Drupal\Core\Test\EnvironmentCleaner::cleanDatabase() instead.
  583. *
  584. * @see https://www.drupal.org/node/3076634
  585. */
  586. function simpletest_clean_database() {
  587. @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);
  588. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  589. $cleaner = \Drupal::service('environment_cleaner');
  590. $cleaner->cleanDatabase();
  591. }
  592. /**
  593. * Finds all leftover temporary directories and removes them.
  594. *
  595. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  596. * environment_cleaner service and call its cleanTemporaryDirectories()
  597. * method, or use
  598. * \Drupal\Core\Test\EnvironmentCleaner::cleanTemporaryDirectories() instead.
  599. *
  600. * @see https://www.drupal.org/node/3076634
  601. */
  602. function simpletest_clean_temporary_directories() {
  603. @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);
  604. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  605. $cleaner = \Drupal::service('environment_cleaner');
  606. $cleaner->cleanTemporaryDirectories();
  607. }
  608. /**
  609. * Clears the test result tables.
  610. *
  611. * @param $test_id
  612. * Test ID to remove results for, or NULL to remove all results.
  613. *
  614. * @return int
  615. * The number of results that were removed.
  616. *
  617. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
  618. * environment_cleaner service and call its cleanResultsTable() method, or use
  619. * \Drupal\Core\Test\EnvironmentCleaner::cleanResultsTable() instead.
  620. *
  621. * @see https://www.drupal.org/node/3076634
  622. */
  623. function simpletest_clean_results_table($test_id = NULL) {
  624. @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);
  625. $count = 0;
  626. if (\Drupal::config('simpletest.settings')->get('clear_results')) {
  627. /* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
  628. $cleaner = \Drupal::service('environment_cleaner');
  629. $count = $cleaner->cleanResultsTable($test_id);
  630. }
  631. return $count;
  632. }
  633. /**
  634. * Converts PHPUnit's JUnit XML output to an array.
  635. *
  636. * @param $test_id
  637. * The current test ID.
  638. * @param $phpunit_xml_file
  639. * Path to the PHPUnit XML file.
  640. *
  641. * @return array[]|null
  642. * The results as array of rows in a format that can be inserted into
  643. * {simpletest}. If the phpunit_xml_file does not have any contents then the
  644. * function will return NULL.
  645. *
  646. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  647. * \Drupal\Core\Test\JUnitConverter::xmlToRows() instead.
  648. *
  649. * @see https://www.drupal.org/node/2948547
  650. */
  651. function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
  652. @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);
  653. return JUnitConverter::xmlToRows($test_id, $phpunit_xml_file) ?: NULL;
  654. }
  655. /**
  656. * Finds all test cases recursively from a test suite list.
  657. *
  658. * @param \SimpleXMLElement $element
  659. * The PHPUnit xml to search for test cases.
  660. * @param \SimpleXMLElement $parent
  661. * (Optional) The parent of the current element. Defaults to NULL.
  662. *
  663. * @return array
  664. * A list of all test cases.
  665. *
  666. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  667. * \Drupal\Core\Test\JUnitConverter::findTestCases() instead.
  668. *
  669. * @see https://www.drupal.org/node/2948547
  670. */
  671. function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
  672. @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);
  673. return JUnitConverter::findTestCases($element, $parent);
  674. }
  675. /**
  676. * Converts a PHPUnit test case result to a {simpletest} result row.
  677. *
  678. * @param int $test_id
  679. * The current test ID.
  680. * @param \SimpleXMLElement $test_case
  681. * The PHPUnit test case represented as XML element.
  682. *
  683. * @return array
  684. * An array containing the {simpletest} result row.
  685. *
  686. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  687. * \Drupal\Core\Test\JUnitConverter::convertTestCaseToSimpletestRow() instead.
  688. *
  689. * @see https://www.drupal.org/node/2948547
  690. */
  691. function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $test_case) {
  692. @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);
  693. return JUnitConverter::convertTestCaseToSimpletestRow($test_id, $test_case);
  694. }
  695. /**
  696. * Display test results from run-tests.sh in a browser.
  697. *
  698. * @internal
  699. * This function is only used by run-tests.sh
  700. *
  701. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. This function
  702. * supports the --browser option in this script. Use the --verbose option
  703. * instead.
  704. *
  705. * @see https://www.drupal.org/node/3083549
  706. */
  707. function _simpletest_run_tests_script_open_browser() {
  708. global $test_ids;
  709. try {
  710. $connection = Database::getConnection('default', 'test-runner');
  711. $results = $connection->select('simpletest')
  712. ->fields('simpletest')
  713. ->condition('test_id', $test_ids, 'IN')
  714. ->orderBy('test_class')
  715. ->orderBy('message_id')
  716. ->execute()
  717. ->fetchAll();
  718. }
  719. catch (Exception $e) {
  720. echo (string) $e;
  721. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  722. }
  723. // Get the results form.
  724. $form = [];
  725. SimpletestResultsForm::addResultForm($form, $results);
  726. // Get the assets to make the details element collapsible and theme the result
  727. // form.
  728. $assets = new AttachedAssets();
  729. $assets->setLibraries([
  730. 'core/drupal.collapse',
  731. 'system/admin',
  732. 'simpletest/drupal.simpletest',
  733. ]);
  734. $resolver = \Drupal::service('asset.resolver');
  735. list($js_assets_header, $js_assets_footer) = $resolver->getJsAssets($assets, FALSE);
  736. $js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
  737. $js_assets_header = $js_collection_renderer->render($js_assets_header);
  738. $js_assets_footer = $js_collection_renderer->render($js_assets_footer);
  739. $css_assets = \Drupal::service('asset.css.collection_renderer')->render($resolver->getCssAssets($assets, FALSE));
  740. // Make the html page to write to disk.
  741. $render_service = \Drupal::service('renderer');
  742. $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>';
  743. // Ensure we have assets verbose directory - tests with no verbose output will
  744. // not have created one.
  745. $directory = PublicStream::basePath() . '/simpletest/verbose';
  746. \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
  747. $php = new Php();
  748. $uuid = $php->generate();
  749. $filename = $directory . '/results-' . $uuid . '.html';
  750. $base_url = getenv('SIMPLETEST_BASE_URL');
  751. if (empty($base_url)) {
  752. simpletest_script_print_error("--browser needs argument --url.");
  753. }
  754. $url = $base_url . '/' . PublicStream::basePath() . '/simpletest/verbose/results-' . $uuid . '.html';
  755. file_put_contents($filename, $html);
  756. // See if we can find an OS helper to open URLs in default browser.
  757. $browser = FALSE;
  758. if (shell_exec('which xdg-open')) {
  759. $browser = 'xdg-open';
  760. }
  761. elseif (shell_exec('which open')) {
  762. $browser = 'open';
  763. }
  764. elseif (substr(PHP_OS, 0, 3) == 'WIN') {
  765. $browser = 'start';
  766. }
  767. if ($browser) {
  768. shell_exec($browser . ' ' . escapeshellarg($url));
  769. }
  770. else {
  771. // Can't find assets valid browser.
  772. print 'Open file://' . realpath($filename) . ' in your browser to see the verbose output.';
  773. }
  774. }