TestBase.php 48 KB

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