TestBase.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. <?php
  2. namespace Drupal\simpletest;
  3. use Drupal\Component\Assertion\Handle;
  4. use Drupal\Component\Render\MarkupInterface;
  5. use Drupal\Component\Utility\Crypt;
  6. use Drupal\Component\Utility\SafeMarkup;
  7. use Drupal\Core\Database\Database;
  8. use Drupal\Core\Site\Settings;
  9. use Drupal\Core\StreamWrapper\PublicStream;
  10. use Drupal\Core\Test\TestDatabase;
  11. use Drupal\Core\Test\TestSetupTrait;
  12. use Drupal\Core\Utility\Error;
  13. use Drupal\Tests\AssertHelperTrait as BaseAssertHelperTrait;
  14. use Drupal\Tests\ConfigTestTrait;
  15. use Drupal\Tests\RandomGeneratorTrait;
  16. use Drupal\Tests\SessionTestTrait;
  17. use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
  18. /**
  19. * Base class for Drupal tests.
  20. *
  21. * Do not extend this class directly; use \Drupal\simpletest\WebTestBase.
  22. */
  23. abstract class TestBase {
  24. use BaseAssertHelperTrait;
  25. use TestSetupTrait;
  26. use SessionTestTrait;
  27. use RandomGeneratorTrait;
  28. use GeneratePermutationsTrait;
  29. // For backwards compatibility switch the visbility of the methods to public.
  30. use ConfigTestTrait {
  31. configImporter as public;
  32. copyConfig as public;
  33. }
  34. /**
  35. * The database prefix of this test run.
  36. *
  37. * @var string
  38. */
  39. protected $databasePrefix = NULL;
  40. /**
  41. * Time limit for the test.
  42. *
  43. * @var int
  44. */
  45. protected $timeLimit = 500;
  46. /**
  47. * Current results of this test case.
  48. *
  49. * @var Array
  50. */
  51. public $results = [
  52. '#pass' => 0,
  53. '#fail' => 0,
  54. '#exception' => 0,
  55. '#debug' => 0,
  56. ];
  57. /**
  58. * Assertions thrown in that test case.
  59. *
  60. * @var Array
  61. */
  62. protected $assertions = [];
  63. /**
  64. * This class is skipped when looking for the source of an assertion.
  65. *
  66. * When displaying which function an assert comes from, it's not too useful
  67. * to see "WebTestBase->drupalLogin()', we would like to see the test
  68. * that called it. So we need to skip the classes defining these helper
  69. * methods.
  70. */
  71. protected $skipClasses = [__CLASS__ => TRUE];
  72. /**
  73. * TRUE if verbose debugging is enabled.
  74. *
  75. * @var bool
  76. */
  77. public $verbose;
  78. /**
  79. * Incrementing identifier for verbose output filenames.
  80. *
  81. * @var int
  82. */
  83. protected $verboseId = 0;
  84. /**
  85. * Safe class name for use in verbose output filenames.
  86. *
  87. * Namespaces separator (\) replaced with _.
  88. *
  89. * @var string
  90. */
  91. protected $verboseClassName;
  92. /**
  93. * Directory where verbose output files are put.
  94. *
  95. * @var string
  96. */
  97. protected $verboseDirectory;
  98. /**
  99. * URL to the verbose output file directory.
  100. *
  101. * @var string
  102. */
  103. protected $verboseDirectoryUrl;
  104. /**
  105. * The original configuration (variables), if available.
  106. *
  107. * @var string
  108. * @todo Remove all remnants of $GLOBALS['conf'].
  109. * @see https://www.drupal.org/node/2183323
  110. */
  111. protected $originalConf;
  112. /**
  113. * The original configuration (variables).
  114. *
  115. * @var string
  116. */
  117. protected $originalConfig;
  118. /**
  119. * The original configuration directories.
  120. *
  121. * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by
  122. * core/includes/bootstrap.inc.
  123. *
  124. * @var array
  125. */
  126. protected $originalConfigDirectories;
  127. /**
  128. * The original container.
  129. *
  130. * @var \Symfony\Component\DependencyInjection\ContainerInterface
  131. */
  132. protected $originalContainer;
  133. /**
  134. * The original file directory, before it was changed for testing purposes.
  135. *
  136. * @var string
  137. */
  138. protected $originalFileDirectory = NULL;
  139. /**
  140. * The original language.
  141. *
  142. * @var \Drupal\Core\Language\LanguageInterface
  143. */
  144. protected $originalLanguage;
  145. /**
  146. * The original database prefix when running inside Simpletest.
  147. *
  148. * @var string
  149. */
  150. protected $originalPrefix;
  151. /**
  152. * The name of the session cookie of the test-runner.
  153. *
  154. * @var string
  155. */
  156. protected $originalSessionName;
  157. /**
  158. * The settings array.
  159. *
  160. * @var array
  161. */
  162. protected $originalSettings;
  163. /**
  164. * The original array of shutdown function callbacks.
  165. *
  166. * @var array
  167. */
  168. protected $originalShutdownCallbacks;
  169. /**
  170. * The original user, before testing began.
  171. *
  172. * @var \Drupal\Core\Session\AccountProxyInterface
  173. */
  174. protected $originalUser;
  175. /**
  176. * The translation file directory for the test environment.
  177. *
  178. * This is set in TestBase::prepareEnvironment().
  179. *
  180. * @var string
  181. */
  182. protected $translationFilesDirectory;
  183. /**
  184. * Whether to die in case any test assertion fails.
  185. *
  186. * @var bool
  187. *
  188. * @see run-tests.sh
  189. */
  190. public $dieOnFail = FALSE;
  191. /**
  192. * The config importer that can used in a test.
  193. *
  194. * @var \Drupal\Core\Config\ConfigImporter
  195. */
  196. protected $configImporter;
  197. /**
  198. * HTTP authentication method (specified as a CURLAUTH_* constant).
  199. *
  200. * @var int
  201. * @see http://php.net/manual/function.curl-setopt.php
  202. */
  203. protected $httpAuthMethod = CURLAUTH_BASIC;
  204. /**
  205. * HTTP authentication credentials (<username>:<password>).
  206. *
  207. * @var string
  208. */
  209. protected $httpAuthCredentials = NULL;
  210. /**
  211. * Constructor for Test.
  212. *
  213. * @param $test_id
  214. * Tests with the same id are reported together.
  215. */
  216. public function __construct($test_id = NULL) {
  217. $this->testId = $test_id;
  218. }
  219. /**
  220. * Performs setup tasks before each individual test method is run.
  221. */
  222. abstract protected function setUp();
  223. /**
  224. * Checks the matching requirements for Test.
  225. *
  226. * @return
  227. * Array of errors containing a list of unmet requirements.
  228. */
  229. protected function checkRequirements() {
  230. return [];
  231. }
  232. /**
  233. * Helper method to store an assertion record in the configured database.
  234. *
  235. * This method decouples database access from assertion logic.
  236. *
  237. * @param array $assertion
  238. * Keyed array representing an assertion, as generated by assert().
  239. *
  240. * @see self::assert()
  241. *
  242. * @return \Drupal\Core\Database\StatementInterface|int|null
  243. * The message ID.
  244. */
  245. protected function storeAssertion(array $assertion) {
  246. return self::getDatabaseConnection()
  247. ->insert('simpletest', ['return' => Database::RETURN_INSERT_ID])
  248. ->fields($assertion)
  249. ->execute();
  250. }
  251. /**
  252. * Internal helper: stores the assert.
  253. *
  254. * @param $status
  255. * Can be 'pass', 'fail', 'exception', 'debug'.
  256. * TRUE is a synonym for 'pass', FALSE for 'fail'.
  257. * @param string|\Drupal\Component\Render\MarkupInterface $message
  258. * (optional) A message to display with the assertion. Do not translate
  259. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  260. * variables in the message text, not t(). If left blank, a default message
  261. * will be displayed.
  262. * @param $group
  263. * (optional) The group this message is in, which is displayed in a column
  264. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  265. * translate this string. Defaults to 'Other'; most tests do not override
  266. * this default.
  267. * @param $caller
  268. * By default, the assert comes from a function whose name starts with
  269. * 'test'. Instead, you can specify where this assert originates from
  270. * by passing in an associative array as $caller. Key 'file' is
  271. * the name of the source file, 'line' is the line number and 'function'
  272. * is the caller function itself.
  273. */
  274. protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
  275. if ($message instanceof MarkupInterface) {
  276. $message = (string) $message;
  277. }
  278. // Convert boolean status to string status.
  279. if (is_bool($status)) {
  280. $status = $status ? 'pass' : 'fail';
  281. }
  282. // Increment summary result counter.
  283. $this->results['#' . $status]++;
  284. // Get the function information about the call to the assertion method.
  285. if (!$caller) {
  286. $caller = $this->getAssertionCall();
  287. }
  288. // Creation assertion array that can be displayed while tests are running.
  289. $assertion = [
  290. 'test_id' => $this->testId,
  291. 'test_class' => get_class($this),
  292. 'status' => $status,
  293. 'message' => $message,
  294. 'message_group' => $group,
  295. 'function' => $caller['function'],
  296. 'line' => $caller['line'],
  297. 'file' => $caller['file'],
  298. ];
  299. // Store assertion for display after the test has completed.
  300. $message_id = $this->storeAssertion($assertion);
  301. $assertion['message_id'] = $message_id;
  302. $this->assertions[] = $assertion;
  303. // We do not use a ternary operator here to allow a breakpoint on
  304. // test failure.
  305. if ($status == 'pass') {
  306. return TRUE;
  307. }
  308. else {
  309. if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) {
  310. exit(1);
  311. }
  312. return FALSE;
  313. }
  314. }
  315. /**
  316. * Store an assertion from outside the testing context.
  317. *
  318. * This is useful for inserting assertions that can only be recorded after
  319. * the test case has been destroyed, such as PHP fatal errors. The caller
  320. * information is not automatically gathered since the caller is most likely
  321. * inserting the assertion on behalf of other code. In all other respects
  322. * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
  323. * of storing the assertion.
  324. *
  325. * @return
  326. * Message ID of the stored assertion.
  327. *
  328. * @see \Drupal\simpletest\TestBase::assert()
  329. * @see \Drupal\simpletest\TestBase::deleteAssert()
  330. */
  331. public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
  332. // Convert boolean status to string status.
  333. if (is_bool($status)) {
  334. $status = $status ? 'pass' : 'fail';
  335. }
  336. $caller += [
  337. 'function' => 'Unknown',
  338. 'line' => 0,
  339. 'file' => 'Unknown',
  340. ];
  341. $assertion = [
  342. 'test_id' => $test_id,
  343. 'test_class' => $test_class,
  344. 'status' => $status,
  345. 'message' => $message,
  346. 'message_group' => $group,
  347. 'function' => $caller['function'],
  348. 'line' => $caller['line'],
  349. 'file' => $caller['file'],
  350. ];
  351. // We can't use storeAssertion() because this method is static.
  352. return self::getDatabaseConnection()
  353. ->insert('simpletest')
  354. ->fields($assertion)
  355. ->execute();
  356. }
  357. /**
  358. * Delete an assertion record by message ID.
  359. *
  360. * @param $message_id
  361. * Message ID of the assertion to delete.
  362. *
  363. * @return
  364. * TRUE if the assertion was deleted, FALSE otherwise.
  365. *
  366. * @see \Drupal\simpletest\TestBase::insertAssert()
  367. */
  368. public static function deleteAssert($message_id) {
  369. // We can't use storeAssertion() because this method is static.
  370. return (bool) self::getDatabaseConnection()
  371. ->delete('simpletest')
  372. ->condition('message_id', $message_id)
  373. ->execute();
  374. }
  375. /**
  376. * Cycles through backtrace until the first non-assertion method is found.
  377. *
  378. * @return
  379. * Array representing the true caller.
  380. */
  381. protected function getAssertionCall() {
  382. $backtrace = debug_backtrace();
  383. // The first element is the call. The second element is the caller.
  384. // We skip calls that occurred in one of the methods of our base classes
  385. // or in an assertion function.
  386. while (($caller = $backtrace[1]) &&
  387. ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
  388. substr($caller['function'], 0, 6) == 'assert')) {
  389. // We remove that call.
  390. array_shift($backtrace);
  391. }
  392. return Error::getLastCaller($backtrace);
  393. }
  394. /**
  395. * Check to see if a value is not false.
  396. *
  397. * False values are: empty string, 0, NULL, and FALSE.
  398. *
  399. * @param $value
  400. * The value on which the assertion is to be done.
  401. * @param $message
  402. * (optional) A message to display with the assertion. Do not translate
  403. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  404. * variables in the message text, not t(). If left blank, a default message
  405. * will be displayed.
  406. * @param $group
  407. * (optional) The group this message is in, which is displayed in a column
  408. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  409. * translate this string. Defaults to 'Other'; most tests do not override
  410. * this default.
  411. *
  412. * @return
  413. * TRUE if the assertion succeeded, FALSE otherwise.
  414. */
  415. protected function assertTrue($value, $message = '', $group = 'Other') {
  416. return $this->assert((bool) $value, $message ? $message : SafeMarkup::format('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group);
  417. }
  418. /**
  419. * Check to see if a value is false.
  420. *
  421. * False values are: empty string, 0, NULL, and FALSE.
  422. *
  423. * @param $value
  424. * The value on which the assertion is to be done.
  425. * @param $message
  426. * (optional) A message to display with the assertion. Do not translate
  427. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  428. * variables in the message text, not t(). If left blank, a default message
  429. * will be displayed.
  430. * @param $group
  431. * (optional) The group this message is in, which is displayed in a column
  432. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  433. * translate this string. Defaults to 'Other'; most tests do not override
  434. * this default.
  435. *
  436. * @return
  437. * TRUE if the assertion succeeded, FALSE otherwise.
  438. */
  439. protected function assertFalse($value, $message = '', $group = 'Other') {
  440. return $this->assert(!$value, $message ? $message : SafeMarkup::format('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group);
  441. }
  442. /**
  443. * Check to see if a value is NULL.
  444. *
  445. * @param $value
  446. * The value on which the assertion is to be done.
  447. * @param $message
  448. * (optional) A message to display with the assertion. Do not translate
  449. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  450. * variables in the message text, not t(). If left blank, a default message
  451. * will be displayed.
  452. * @param $group
  453. * (optional) The group this message is in, which is displayed in a column
  454. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  455. * translate this string. Defaults to 'Other'; most tests do not override
  456. * this default.
  457. *
  458. * @return
  459. * TRUE if the assertion succeeded, FALSE otherwise.
  460. */
  461. protected function assertNull($value, $message = '', $group = 'Other') {
  462. return $this->assert(!isset($value), $message ? $message : SafeMarkup::format('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group);
  463. }
  464. /**
  465. * Check to see if a value is not NULL.
  466. *
  467. * @param $value
  468. * The value on which the assertion is to be done.
  469. * @param $message
  470. * (optional) A message to display with the assertion. Do not translate
  471. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  472. * variables in the message text, not t(). If left blank, a default message
  473. * will be displayed.
  474. * @param $group
  475. * (optional) The group this message is in, which is displayed in a column
  476. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  477. * translate this string. Defaults to 'Other'; most tests do not override
  478. * this default.
  479. *
  480. * @return
  481. * TRUE if the assertion succeeded, FALSE otherwise.
  482. */
  483. protected function assertNotNull($value, $message = '', $group = 'Other') {
  484. return $this->assert(isset($value), $message ? $message : SafeMarkup::format('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group);
  485. }
  486. /**
  487. * Check to see if two values are equal.
  488. *
  489. * @param $first
  490. * The first value to check.
  491. * @param $second
  492. * The second value to check.
  493. * @param $message
  494. * (optional) A message to display with the assertion. Do not translate
  495. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  496. * variables in the message text, not t(). If left blank, a default message
  497. * will be displayed.
  498. * @param $group
  499. * (optional) The group this message is in, which is displayed in a column
  500. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  501. * translate this string. Defaults to 'Other'; most tests do not override
  502. * this default.
  503. *
  504. * @return
  505. * TRUE if the assertion succeeded, FALSE otherwise.
  506. */
  507. protected function assertEqual($first, $second, $message = '', $group = 'Other') {
  508. // Cast objects implementing MarkupInterface to string instead of
  509. // relying on PHP casting them to string depending on what they are being
  510. // comparing with.
  511. $first = $this->castSafeStrings($first);
  512. $second = $this->castSafeStrings($second);
  513. $is_equal = $first == $second;
  514. if (!$is_equal || !$message) {
  515. $default_message = SafeMarkup::format('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
  516. $message = $message ? $message . PHP_EOL . $default_message : $default_message;
  517. }
  518. return $this->assert($is_equal, $message, $group);
  519. }
  520. /**
  521. * Check to see if two values are not equal.
  522. *
  523. * @param $first
  524. * The first value to check.
  525. * @param $second
  526. * The second value to check.
  527. * @param $message
  528. * (optional) A message to display with the assertion. Do not translate
  529. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  530. * variables in the message text, not t(). If left blank, a default message
  531. * will be displayed.
  532. * @param $group
  533. * (optional) The group this message is in, which is displayed in a column
  534. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  535. * translate this string. Defaults to 'Other'; most tests do not override
  536. * this default.
  537. *
  538. * @return
  539. * TRUE if the assertion succeeded, FALSE otherwise.
  540. */
  541. protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
  542. // Cast objects implementing MarkupInterface to string instead of
  543. // relying on PHP casting them to string depending on what they are being
  544. // comparing with.
  545. $first = $this->castSafeStrings($first);
  546. $second = $this->castSafeStrings($second);
  547. $not_equal = $first != $second;
  548. if (!$not_equal || !$message) {
  549. $default_message = SafeMarkup::format('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
  550. $message = $message ? $message . PHP_EOL . $default_message : $default_message;
  551. }
  552. return $this->assert($not_equal, $message, $group);
  553. }
  554. /**
  555. * Check to see if two values are identical.
  556. *
  557. * @param $first
  558. * The first value to check.
  559. * @param $second
  560. * The second value to check.
  561. * @param $message
  562. * (optional) A message to display with the assertion. Do not translate
  563. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  564. * variables in the message text, not t(). If left blank, a default message
  565. * will be displayed.
  566. * @param $group
  567. * (optional) The group this message is in, which is displayed in a column
  568. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  569. * translate this string. Defaults to 'Other'; most tests do not override
  570. * this default.
  571. *
  572. * @return
  573. * TRUE if the assertion succeeded, FALSE otherwise.
  574. */
  575. protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
  576. $is_identical = $first === $second;
  577. if (!$is_identical || !$message) {
  578. $default_message = SafeMarkup::format('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
  579. $message = $message ? $message . PHP_EOL . $default_message : $default_message;
  580. }
  581. return $this->assert($is_identical, $message, $group);
  582. }
  583. /**
  584. * Check to see if two values are not identical.
  585. *
  586. * @param $first
  587. * The first value to check.
  588. * @param $second
  589. * The second value to check.
  590. * @param $message
  591. * (optional) A message to display with the assertion. Do not translate
  592. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  593. * variables in the message text, not t(). If left blank, a default message
  594. * will be displayed.
  595. * @param $group
  596. * (optional) The group this message is in, which is displayed in a column
  597. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  598. * translate this string. Defaults to 'Other'; most tests do not override
  599. * this default.
  600. *
  601. * @return
  602. * TRUE if the assertion succeeded, FALSE otherwise.
  603. */
  604. protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
  605. $not_identical = $first !== $second;
  606. if (!$not_identical || !$message) {
  607. $default_message = SafeMarkup::format('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
  608. $message = $message ? $message . PHP_EOL . $default_message : $default_message;
  609. }
  610. return $this->assert($not_identical, $message, $group);
  611. }
  612. /**
  613. * Checks to see if two objects are identical.
  614. *
  615. * @param object $object1
  616. * The first object to check.
  617. * @param object $object2
  618. * The second object to check.
  619. * @param $message
  620. * (optional) A message to display with the assertion. Do not translate
  621. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  622. * variables in the message text, not t(). If left blank, a default message
  623. * will be displayed.
  624. * @param $group
  625. * (optional) The group this message is in, which is displayed in a column
  626. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  627. * translate this string. Defaults to 'Other'; most tests do not override
  628. * this default.
  629. *
  630. * @return
  631. * TRUE if the assertion succeeded, FALSE otherwise.
  632. */
  633. protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
  634. $message = $message ?: SafeMarkup::format('@object1 is identical to @object2', [
  635. '@object1' => var_export($object1, TRUE),
  636. '@object2' => var_export($object2, TRUE),
  637. ]);
  638. $identical = TRUE;
  639. foreach ($object1 as $key => $value) {
  640. $identical = $identical && isset($object2->$key) && $object2->$key === $value;
  641. }
  642. return $this->assertTrue($identical, $message, $group);
  643. }
  644. /**
  645. * Asserts that no errors have been logged to the PHP error.log thus far.
  646. *
  647. * @return bool
  648. * TRUE if the assertion succeeded, FALSE otherwise.
  649. *
  650. * @see \Drupal\simpletest\TestBase::prepareEnvironment()
  651. * @see \Drupal\Core\DrupalKernel::bootConfiguration()
  652. */
  653. protected function assertNoErrorsLogged() {
  654. // Since PHP only creates the error.log file when an actual error is
  655. // triggered, it is sufficient to check whether the file exists.
  656. return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.');
  657. }
  658. /**
  659. * Asserts that a specific error has been logged to the PHP error log.
  660. *
  661. * @param string $error_message
  662. * The expected error message.
  663. *
  664. * @return bool
  665. * TRUE if the assertion succeeded, FALSE otherwise.
  666. *
  667. * @see \Drupal\simpletest\TestBase::prepareEnvironment()
  668. * @see \Drupal\Core\DrupalKernel::bootConfiguration()
  669. */
  670. protected function assertErrorLogged($error_message) {
  671. $error_log_filename = DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log';
  672. if (!file_exists($error_log_filename)) {
  673. $this->error('No error logged yet.');
  674. }
  675. $content = file_get_contents($error_log_filename);
  676. $rows = explode(PHP_EOL, $content);
  677. // We iterate over the rows in order to be able to remove the logged error
  678. // afterwards.
  679. $found = FALSE;
  680. foreach ($rows as $row_index => $row) {
  681. if (strpos($content, $error_message) !== FALSE) {
  682. $found = TRUE;
  683. unset($rows[$row_index]);
  684. }
  685. }
  686. file_put_contents($error_log_filename, implode("\n", $rows));
  687. return $this->assertTrue($found, sprintf('The %s error message was logged.', $error_message));
  688. }
  689. /**
  690. * Fire an assertion that is always positive.
  691. *
  692. * @param $message
  693. * (optional) A message to display with the assertion. Do not translate
  694. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  695. * variables in the message text, not t(). If left blank, a default message
  696. * will be displayed.
  697. * @param $group
  698. * (optional) The group this message is in, which is displayed in a column
  699. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  700. * translate this string. Defaults to 'Other'; most tests do not override
  701. * this default.
  702. *
  703. * @return
  704. * TRUE.
  705. */
  706. protected function pass($message = NULL, $group = 'Other') {
  707. return $this->assert(TRUE, $message, $group);
  708. }
  709. /**
  710. * Fire an assertion that is always negative.
  711. *
  712. * @param $message
  713. * (optional) A message to display with the assertion. Do not translate
  714. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  715. * variables in the message text, not t(). If left blank, a default message
  716. * will be displayed.
  717. * @param $group
  718. * (optional) The group this message is in, which is displayed in a column
  719. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  720. * translate this string. Defaults to 'Other'; most tests do not override
  721. * this default.
  722. *
  723. * @return
  724. * FALSE.
  725. */
  726. protected function fail($message = NULL, $group = 'Other') {
  727. return $this->assert(FALSE, $message, $group);
  728. }
  729. /**
  730. * Fire an error assertion.
  731. *
  732. * @param $message
  733. * (optional) A message to display with the assertion. Do not translate
  734. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  735. * variables in the message text, not t(). If left blank, a default message
  736. * will be displayed.
  737. * @param $group
  738. * (optional) The group this message is in, which is displayed in a column
  739. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  740. * translate this string. Defaults to 'Other'; most tests do not override
  741. * this default.
  742. * @param $caller
  743. * The caller of the error.
  744. *
  745. * @return
  746. * FALSE.
  747. */
  748. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  749. if ($group == 'User notice') {
  750. // Since 'User notice' is set by trigger_error() which is used for debug
  751. // set the message to a status of 'debug'.
  752. return $this->assert('debug', $message, 'Debug', $caller);
  753. }
  754. return $this->assert('exception', $message, $group, $caller);
  755. }
  756. /**
  757. * Logs a verbose message in a text file.
  758. *
  759. * The link to the verbose message will be placed in the test results as a
  760. * passing assertion with the text '[verbose message]'.
  761. *
  762. * @param $message
  763. * The verbose message to be stored.
  764. *
  765. * @see simpletest_verbose()
  766. */
  767. protected function verbose($message) {
  768. // Do nothing if verbose debugging is disabled.
  769. if (!$this->verbose) {
  770. return;
  771. }
  772. $message = '<hr />ID #' . $this->verboseId . ' (<a href="' . $this->verboseClassName . '-' . ($this->verboseId - 1) . '-' . $this->testId . '.html">Previous</a> | <a href="' . $this->verboseClassName . '-' . ($this->verboseId + 1) . '-' . $this->testId . '.html">Next</a>)<hr />' . $message;
  773. $verbose_filename = $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html';
  774. if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) {
  775. $url = $this->verboseDirectoryUrl . '/' . $verbose_filename;
  776. // Not using \Drupal\Core\Utility\LinkGeneratorInterface::generate()
  777. // to avoid invoking the theme system, so that unit tests
  778. // can use verbose() as well.
  779. $url = '<a href="' . $url . '" target="_blank">Verbose message</a>';
  780. $this->error($url, 'User notice');
  781. }
  782. $this->verboseId++;
  783. }
  784. /**
  785. * Run all tests in this class.
  786. *
  787. * Regardless of whether $methods are passed or not, only method names
  788. * starting with "test" are executed.
  789. *
  790. * @param $methods
  791. * (optional) A list of method names in the test case class to run; e.g.,
  792. * array('testFoo', 'testBar'). By default, all methods of the class are
  793. * taken into account, but it can be useful to only run a few selected test
  794. * methods during debugging.
  795. */
  796. public function run(array $methods = []) {
  797. $class = get_class($this);
  798. if ($missing_requirements = $this->checkRequirements()) {
  799. $object_info = new \ReflectionObject($this);
  800. $caller = [
  801. 'file' => $object_info->getFileName(),
  802. ];
  803. foreach ($missing_requirements as $missing_requirement) {
  804. TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
  805. }
  806. return;
  807. }
  808. TestServiceProvider::$currentTest = $this;
  809. $simpletest_config = $this->config('simpletest.settings');
  810. // Unless preset from run-tests.sh, retrieve the current verbose setting.
  811. if (!isset($this->verbose)) {
  812. $this->verbose = $simpletest_config->get('verbose');
  813. }
  814. if ($this->verbose) {
  815. // Initialize verbose debugging.
  816. $this->verbose = TRUE;
  817. $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose';
  818. $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory);
  819. if (file_prepare_directory($this->verboseDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) {
  820. file_put_contents($this->verboseDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
  821. }
  822. $this->verboseClassName = str_replace("\\", "_", $class);
  823. }
  824. // HTTP auth settings (<username>:<password>) for the simpletest browser
  825. // when sending requests to the test site.
  826. $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method');
  827. $username = $simpletest_config->get('httpauth.username');
  828. $password = $simpletest_config->get('httpauth.password');
  829. if (!empty($username) && !empty($password)) {
  830. $this->httpAuthCredentials = $username . ':' . $password;
  831. }
  832. // Force assertion failures to be thrown as AssertionError for PHP 5 & 7
  833. // compatibility.
  834. Handle::register();
  835. set_error_handler([$this, 'errorHandler']);
  836. // Iterate through all the methods in this class, unless a specific list of
  837. // methods to run was passed.
  838. $test_methods = array_filter(get_class_methods($class), function ($method) {
  839. return strpos($method, 'test') === 0;
  840. });
  841. if (empty($test_methods)) {
  842. // Call $this->assert() here because we need to pass along custom caller
  843. // information, lest the wrong originating code file/line be identified.
  844. $this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]);
  845. }
  846. if ($methods) {
  847. $test_methods = array_intersect($test_methods, $methods);
  848. }
  849. foreach ($test_methods as $method) {
  850. // Insert a fail record. This will be deleted on completion to ensure
  851. // that testing completed.
  852. $method_info = new \ReflectionMethod($class, $method);
  853. $caller = [
  854. 'file' => $method_info->getFileName(),
  855. 'line' => $method_info->getStartLine(),
  856. 'function' => $class . '->' . $method . '()',
  857. ];
  858. $test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);
  859. try {
  860. $this->prepareEnvironment();
  861. }
  862. catch (\Exception $e) {
  863. $this->exceptionHandler($e);
  864. // The prepareEnvironment() method isolates the test from the parent
  865. // Drupal site by creating a random database prefix and test site
  866. // directory. If this fails, a test would possibly operate in the
  867. // parent site. Therefore, the entire test run for this test class
  868. // has to be aborted.
  869. // restoreEnvironment() cannot be called, because we do not know
  870. // where exactly the environment setup failed.
  871. break;
  872. }
  873. try {
  874. $this->setUp();
  875. }
  876. catch (\Exception $e) {
  877. $this->exceptionHandler($e);
  878. // Abort if setUp() fails, since all test methods will fail.
  879. // But ensure to clean up and restore the environment, since
  880. // prepareEnvironment() succeeded.
  881. $this->restoreEnvironment();
  882. break;
  883. }
  884. try {
  885. $this->$method();
  886. }
  887. catch (\Exception $e) {
  888. $this->exceptionHandler($e);
  889. }
  890. try {
  891. $this->tearDown();
  892. }
  893. catch (\Exception $e) {
  894. $this->exceptionHandler($e);
  895. // If a test fails to tear down, abort the entire test class, since
  896. // it is likely that all tests will fail in the same way and a
  897. // failure here only results in additional test artifacts that have
  898. // to be manually deleted.
  899. $this->restoreEnvironment();
  900. break;
  901. }
  902. $this->restoreEnvironment();
  903. // Remove the test method completion check record.
  904. TestBase::deleteAssert($test_completion_check_id);
  905. }
  906. TestServiceProvider::$currentTest = NULL;
  907. // Clear out the error messages and restore error handler.
  908. drupal_get_messages();
  909. restore_error_handler();
  910. }
  911. /**
  912. * Generates a database prefix for running tests.
  913. *
  914. * The database prefix is used by prepareEnvironment() to setup a public files
  915. * directory for the test to be run, which also contains the PHP error log,
  916. * which is written to in case of a fatal error. Since that directory is based
  917. * on the database prefix, all tests (even unit tests) need to have one, in
  918. * order to access and read the error log.
  919. *
  920. * @see TestBase::prepareEnvironment()
  921. *
  922. * The generated database table prefix is used for the Drupal installation
  923. * being performed for the test. It is also used as user agent HTTP header
  924. * value by the cURL-based browser of WebTestBase, which is sent to the Drupal
  925. * installation of the test. During early Drupal bootstrap, the user agent
  926. * HTTP header is parsed, and if it matches, all database queries use the
  927. * database table prefix that has been generated here.
  928. *
  929. * @see WebTestBase::curlInitialize()
  930. * @see drupal_valid_test_ua()
  931. */
  932. private function prepareDatabasePrefix() {
  933. $test_db = new TestDatabase();
  934. $this->siteDirectory = $test_db->getTestSitePath();
  935. $this->databasePrefix = $test_db->getDatabasePrefix();
  936. // As soon as the database prefix is set, the test might start to execute.
  937. // All assertions as well as the SimpleTest batch operations are associated
  938. // with the testId, so the database prefix has to be associated with it.
  939. $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
  940. ->fields(['last_prefix' => $this->databasePrefix])
  941. ->condition('test_id', $this->testId)
  942. ->execute();
  943. if (!$affected_rows) {
  944. throw new \RuntimeException('Failed to set up database prefix.');
  945. }
  946. }
  947. /**
  948. * Act on global state information before the environment is altered for a test.
  949. *
  950. * Allows e.g. KernelTestBase to prime system/extension info from the
  951. * parent site (and inject it into the test environment so as to improve
  952. * performance).
  953. */
  954. protected function beforePrepareEnvironment() {
  955. }
  956. /**
  957. * Prepares the current environment for running the test.
  958. *
  959. * Backups various current environment variables and resets them, so they do
  960. * not interfere with the Drupal site installation in which tests are executed
  961. * and can be restored in TestBase::restoreEnvironment().
  962. *
  963. * Also sets up new resources for the testing environment, such as the public
  964. * filesystem and configuration directories.
  965. *
  966. * This method is private as it must only be called once by TestBase::run()
  967. * (multiple invocations for the same test would have unpredictable
  968. * consequences) and it must not be callable or overridable by test classes.
  969. *
  970. * @see TestBase::beforePrepareEnvironment()
  971. */
  972. private function prepareEnvironment() {
  973. $user = \Drupal::currentUser();
  974. // Allow (base) test classes to backup global state information.
  975. $this->beforePrepareEnvironment();
  976. // Create the database prefix for this test.
  977. $this->prepareDatabasePrefix();
  978. $language_interface = \Drupal::languageManager()->getCurrentLanguage();
  979. // When running the test runner within a test, back up the original database
  980. // prefix.
  981. if (DRUPAL_TEST_IN_CHILD_SITE) {
  982. $this->originalPrefix = drupal_valid_test_ua();
  983. }
  984. // Backup current in-memory configuration.
  985. $site_path = \Drupal::service('site.path');
  986. $this->originalSite = $site_path;
  987. $this->originalSettings = Settings::getAll();
  988. $this->originalConfig = $GLOBALS['config'];
  989. // @todo Remove all remnants of $GLOBALS['conf'].
  990. // @see https://www.drupal.org/node/2183323
  991. $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL;
  992. // Backup statics and globals.
  993. $this->originalContainer = \Drupal::getContainer();
  994. $this->originalLanguage = $language_interface;
  995. $this->originalConfigDirectories = $GLOBALS['config_directories'];
  996. // Save further contextual information.
  997. // Use the original files directory to avoid nesting it within an existing
  998. // simpletest directory if a test is executed within a test.
  999. $this->originalFileDirectory = Settings::get('file_public_path', $site_path . '/files');
  1000. $this->originalProfile = drupal_get_profile();
  1001. $this->originalUser = isset($user) ? clone $user : NULL;
  1002. // Prevent that session data is leaked into the UI test runner by closing
  1003. // the session and then setting the session-name (i.e. the name of the
  1004. // session cookie) to a random value. If a test starts a new session, then
  1005. // it will be associated with a different session-name. After the test-run
  1006. // it can be safely destroyed.
  1007. // @see TestBase::restoreEnvironment()
  1008. if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
  1009. session_write_close();
  1010. }
  1011. $this->originalSessionName = session_name();
  1012. session_name('SIMPLETEST' . Crypt::randomBytesBase64());
  1013. // Save and clean the shutdown callbacks array because it is static cached
  1014. // and will be changed by the test run. Otherwise it will contain callbacks
  1015. // from both environments and the testing environment will try to call the
  1016. // handlers defined by the original one.
  1017. $callbacks = &drupal_register_shutdown_function();
  1018. $this->originalShutdownCallbacks = $callbacks;
  1019. $callbacks = [];
  1020. // Create test directory ahead of installation so fatal errors and debug
  1021. // information can be logged during installation process.
  1022. file_prepare_directory($this->siteDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1023. // Prepare filesystem directory paths.
  1024. $this->publicFilesDirectory = $this->siteDirectory . '/files';
  1025. $this->privateFilesDirectory = $this->siteDirectory . '/private';
  1026. $this->tempFilesDirectory = $this->siteDirectory . '/temp';
  1027. $this->translationFilesDirectory = $this->siteDirectory . '/translations';
  1028. $this->generatedTestFiles = FALSE;
  1029. // Ensure the configImporter is refreshed for each test.
  1030. $this->configImporter = NULL;
  1031. // Unregister all custom stream wrappers of the parent site.
  1032. // Availability of Drupal stream wrappers varies by test base class:
  1033. // - KernelTestBase supports and maintains stream wrappers in a custom
  1034. // way.
  1035. // - WebTestBase re-initializes Drupal stream wrappers after installation.
  1036. // The original stream wrappers are restored after the test run.
  1037. // @see TestBase::restoreEnvironment()
  1038. $this->originalContainer->get('stream_wrapper_manager')->unregister();
  1039. // Reset statics.
  1040. drupal_static_reset();
  1041. // Ensure there is no service container.
  1042. $this->container = NULL;
  1043. \Drupal::unsetContainer();
  1044. // Unset globals.
  1045. unset($GLOBALS['config_directories']);
  1046. unset($GLOBALS['config']);
  1047. unset($GLOBALS['conf']);
  1048. // Log fatal errors.
  1049. ini_set('log_errors', 1);
  1050. ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log');
  1051. // Change the database prefix.
  1052. $this->changeDatabasePrefix();
  1053. // After preparing the environment and changing the database prefix, we are
  1054. // in a valid test environment.
  1055. drupal_valid_test_ua($this->databasePrefix);
  1056. // Reset settings.
  1057. new Settings([
  1058. // For performance, simply use the database prefix as hash salt.
  1059. 'hash_salt' => $this->databasePrefix,
  1060. 'container_yamls' => [],
  1061. ]);
  1062. drupal_set_time_limit($this->timeLimit);
  1063. }
  1064. /**
  1065. * Performs cleanup tasks after each individual test method has been run.
  1066. */
  1067. protected function tearDown() {
  1068. }
  1069. /**
  1070. * Cleans up the test environment and restores the original environment.
  1071. *
  1072. * Deletes created files, database tables, and reverts environment changes.
  1073. *
  1074. * This method needs to be invoked for both unit and integration tests.
  1075. *
  1076. * @see TestBase::prepareDatabasePrefix()
  1077. * @see TestBase::changeDatabasePrefix()
  1078. * @see TestBase::prepareEnvironment()
  1079. */
  1080. private function restoreEnvironment() {
  1081. // Destroy the session if one was started during the test-run.
  1082. $_SESSION = [];
  1083. if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
  1084. session_destroy();
  1085. $params = session_get_cookie_params();
  1086. setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
  1087. }
  1088. session_name($this->originalSessionName);
  1089. // Reset all static variables.
  1090. // Unsetting static variables will potentially invoke destruct methods,
  1091. // which might call into functions that prime statics and caches again.
  1092. // In that case, all functions are still operating on the test environment,
  1093. // which means they may need to access its filesystem and database.
  1094. drupal_static_reset();
  1095. if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
  1096. $captured_emails = $state->get('system.test_mail_collector') ?: [];
  1097. $emailCount = count($captured_emails);
  1098. if ($emailCount) {
  1099. $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
  1100. $this->pass($message, 'Email');
  1101. }
  1102. }
  1103. // Sleep for 50ms to allow shutdown functions and terminate events to
  1104. // complete. Further information: https://www.drupal.org/node/2194357.
  1105. usleep(50000);
  1106. // Remove all prefixed tables.
  1107. $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
  1108. $original_prefix = $original_connection_info['default']['prefix']['default'];
  1109. $test_connection_info = Database::getConnectionInfo('default');
  1110. $test_prefix = $test_connection_info['default']['prefix']['default'];
  1111. if ($original_prefix != $test_prefix) {
  1112. $tables = Database::getConnection()->schema()->findTables('%');
  1113. foreach ($tables as $table) {
  1114. if (Database::getConnection()->schema()->dropTable($table)) {
  1115. unset($tables[$table]);
  1116. }
  1117. }
  1118. }
  1119. // In case a fatal error occurred that was not in the test process read the
  1120. // log to pick up any fatal errors.
  1121. simpletest_log_read($this->testId, $this->databasePrefix, get_class($this));
  1122. // Restore original dependency injection container.
  1123. $this->container = $this->originalContainer;
  1124. \Drupal::setContainer($this->originalContainer);
  1125. // Delete test site directory.
  1126. file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
  1127. // Restore original database connection.
  1128. Database::removeConnection('default');
  1129. Database::renameConnection('simpletest_original_default', 'default');
  1130. // Reset all static variables.
  1131. // All destructors of statically cached objects have been invoked above;
  1132. // this second reset is guaranteed to reset everything to nothing.
  1133. drupal_static_reset();
  1134. // Restore original in-memory configuration.
  1135. $GLOBALS['config'] = $this->originalConfig;
  1136. $GLOBALS['conf'] = $this->originalConf;
  1137. new Settings($this->originalSettings);
  1138. // Restore original statics and globals.
  1139. $GLOBALS['config_directories'] = $this->originalConfigDirectories;
  1140. // Re-initialize original stream wrappers of the parent site.
  1141. // This must happen after static variables have been reset and the original
  1142. // container and $config_directories are restored, as simpletest_log_read()
  1143. // uses the public stream wrapper to locate the error.log.
  1144. $this->originalContainer->get('stream_wrapper_manager')->register();
  1145. if (isset($this->originalPrefix)) {
  1146. drupal_valid_test_ua($this->originalPrefix);
  1147. }
  1148. else {
  1149. drupal_valid_test_ua(FALSE);
  1150. }
  1151. // Restore original shutdown callbacks.
  1152. $callbacks = &drupal_register_shutdown_function();
  1153. $callbacks = $this->originalShutdownCallbacks;
  1154. }
  1155. /**
  1156. * Handle errors during test runs.
  1157. *
  1158. * Because this is registered in set_error_handler(), it has to be public.
  1159. *
  1160. * @see set_error_handler
  1161. */
  1162. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  1163. if ($severity & error_reporting()) {
  1164. $error_map = [
  1165. E_STRICT => 'Run-time notice',
  1166. E_WARNING => 'Warning',
  1167. E_NOTICE => 'Notice',
  1168. E_CORE_ERROR => 'Core error',
  1169. E_CORE_WARNING => 'Core warning',
  1170. E_USER_ERROR => 'User error',
  1171. E_USER_WARNING => 'User warning',
  1172. E_USER_NOTICE => 'User notice',
  1173. E_RECOVERABLE_ERROR => 'Recoverable error',
  1174. E_DEPRECATED => 'Deprecated',
  1175. E_USER_DEPRECATED => 'User deprecated',
  1176. ];
  1177. $backtrace = debug_backtrace();
  1178. // Add verbose backtrace for errors, but not for debug() messages.
  1179. if ($severity !== E_USER_NOTICE) {
  1180. $verbose_backtrace = $backtrace;
  1181. array_shift($verbose_backtrace);
  1182. $message .= '<pre class="backtrace">' . Error::formatBacktrace($verbose_backtrace) . '</pre>';
  1183. }
  1184. $this->error($message, $error_map[$severity], Error::getLastCaller($backtrace));
  1185. }
  1186. return TRUE;
  1187. }
  1188. /**
  1189. * Handle exceptions.
  1190. *
  1191. * @see set_exception_handler
  1192. */
  1193. protected function exceptionHandler($exception) {
  1194. $backtrace = $exception->getTrace();
  1195. $verbose_backtrace = $backtrace;
  1196. // Push on top of the backtrace the call that generated the exception.
  1197. array_unshift($backtrace, [
  1198. 'line' => $exception->getLine(),
  1199. 'file' => $exception->getFile(),
  1200. ]);
  1201. $decoded_exception = Error::decodeException($exception);
  1202. unset($decoded_exception['backtrace']);
  1203. $message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + [
  1204. '@backtrace' => Error::formatBacktrace($verbose_backtrace),
  1205. ]);
  1206. $this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace));
  1207. }
  1208. /**
  1209. * Changes in memory settings.
  1210. *
  1211. * @param $name
  1212. * The name of the setting to return.
  1213. * @param $value
  1214. * The value of the setting.
  1215. *
  1216. * @see \Drupal\Core\Site\Settings::get()
  1217. */
  1218. protected function settingsSet($name, $value) {
  1219. $settings = Settings::getAll();
  1220. $settings[$name] = $value;
  1221. new Settings($settings);
  1222. }
  1223. /**
  1224. * Ensures test files are deletable within file_unmanaged_delete_recursive().
  1225. *
  1226. * Some tests chmod generated files to be read only. During
  1227. * TestBase::restoreEnvironment() and other cleanup operations, these files
  1228. * need to get deleted too.
  1229. */
  1230. public static function filePreDeleteCallback($path) {
  1231. // When the webserver runs with the same system user as the test runner, we
  1232. // can make read-only files writable again. If not, chmod will fail while
  1233. // the file deletion still works if file permissions have been configured
  1234. // correctly. Thus, we ignore any problems while running chmod.
  1235. @chmod($path, 0700);
  1236. }
  1237. /**
  1238. * Configuration accessor for tests. Returns non-overridden configuration.
  1239. *
  1240. * @param $name
  1241. * Configuration name.
  1242. *
  1243. * @return \Drupal\Core\Config\Config
  1244. * The configuration object with original configuration data.
  1245. */
  1246. protected function config($name) {
  1247. return \Drupal::configFactory()->getEditable($name);
  1248. }
  1249. /**
  1250. * Gets the database prefix.
  1251. *
  1252. * @return string
  1253. * The database prefix
  1254. */
  1255. public function getDatabasePrefix() {
  1256. return $this->databasePrefix;
  1257. }
  1258. /**
  1259. * Gets the temporary files directory.
  1260. *
  1261. * @return string
  1262. * The temporary files directory.
  1263. */
  1264. public function getTempFilesDirectory() {
  1265. return $this->tempFilesDirectory;
  1266. }
  1267. }