KernelTestBaseTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php
  2. namespace Drupal\KernelTests;
  3. use Drupal\Component\FileCache\FileCacheFactory;
  4. use Drupal\Core\Database\Database;
  5. use org\bovigo\vfs\vfsStream;
  6. use org\bovigo\vfs\visitor\vfsStreamStructureVisitor;
  7. use PHPUnit\Framework\SkippedTestError;
  8. /**
  9. * @coversDefaultClass \Drupal\KernelTests\KernelTestBase
  10. *
  11. * @group PHPUnit
  12. * @group Test
  13. * @group KernelTests
  14. */
  15. class KernelTestBaseTest extends KernelTestBase {
  16. /**
  17. * @covers ::setUpBeforeClass
  18. */
  19. public function testSetUpBeforeClass() {
  20. // Note: PHPUnit automatically restores the original working directory.
  21. $this->assertSame(realpath(__DIR__ . '/../../../../'), getcwd());
  22. }
  23. /**
  24. * @covers ::bootEnvironment
  25. */
  26. public function testBootEnvironment() {
  27. $this->assertRegExp('/^test\d{8}$/', $this->databasePrefix);
  28. $this->assertStringStartsWith('vfs://root/sites/simpletest/', $this->siteDirectory);
  29. $this->assertEquals([
  30. 'root' => [
  31. 'sites' => [
  32. 'simpletest' => [
  33. substr($this->databasePrefix, 4) => [
  34. 'files' => [
  35. 'config' => [
  36. 'sync' => [],
  37. ],
  38. ],
  39. ],
  40. ],
  41. ],
  42. ],
  43. ], vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure());
  44. }
  45. /**
  46. * @covers ::getDatabaseConnectionInfo
  47. */
  48. public function testGetDatabaseConnectionInfoWithOutManualSetDbUrl() {
  49. $options = $this->container->get('database')->getConnectionOptions();
  50. $this->assertSame($this->databasePrefix, $options['prefix']['default']);
  51. }
  52. /**
  53. * @covers ::setUp
  54. */
  55. public function testSetUp() {
  56. $this->assertTrue($this->container->has('request_stack'));
  57. $this->assertTrue($this->container->initialized('request_stack'));
  58. $request = $this->container->get('request_stack')->getCurrentRequest();
  59. $this->assertNotEmpty($request);
  60. $this->assertEquals('/', $request->getPathInfo());
  61. $this->assertSame($request, \Drupal::request());
  62. $this->assertEquals($this, $GLOBALS['conf']['container_service_providers']['test']);
  63. $GLOBALS['destroy-me'] = TRUE;
  64. $this->assertArrayHasKey('destroy-me', $GLOBALS);
  65. $database = $this->container->get('database');
  66. $database->schema()->createTable('foo', [
  67. 'fields' => [
  68. 'number' => [
  69. 'type' => 'int',
  70. 'unsigned' => TRUE,
  71. 'not null' => TRUE,
  72. ],
  73. ],
  74. ]);
  75. $this->assertTrue($database->schema()->tableExists('foo'));
  76. // Ensure that the database tasks have been run during set up. Neither MySQL
  77. // nor SQLite make changes that are testable.
  78. if ($database->driver() == 'pgsql') {
  79. $this->assertEquals('on', $database->query("SHOW standard_conforming_strings")->fetchField());
  80. $this->assertEquals('escape', $database->query("SHOW bytea_output")->fetchField());
  81. }
  82. $this->assertNotNull(FileCacheFactory::getPrefix());
  83. }
  84. /**
  85. * @covers ::setUp
  86. * @depends testSetUp
  87. */
  88. public function testSetUpDoesNotLeak() {
  89. $this->assertArrayNotHasKey('destroy-me', $GLOBALS);
  90. // Ensure that we have a different database prefix.
  91. $schema = $this->container->get('database')->schema();
  92. $this->assertFalse($schema->tableExists('foo'));
  93. }
  94. /**
  95. * @covers ::register
  96. */
  97. public function testRegister() {
  98. // Verify that this container is identical to the actual container.
  99. $this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $this->container);
  100. $this->assertSame($this->container, \Drupal::getContainer());
  101. // The request service should never exist.
  102. $this->assertFalse($this->container->has('request'));
  103. // Verify that there is a request stack.
  104. $request = $this->container->get('request_stack')->getCurrentRequest();
  105. $this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $request);
  106. $this->assertSame($request, \Drupal::request());
  107. // Trigger a container rebuild.
  108. $this->enableModules(['system']);
  109. // Verify that this container is identical to the actual container.
  110. $this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $this->container);
  111. $this->assertSame($this->container, \Drupal::getContainer());
  112. // The request service should never exist.
  113. $this->assertFalse($this->container->has('request'));
  114. // Verify that there is a request stack (and that it persisted).
  115. $new_request = $this->container->get('request_stack')->getCurrentRequest();
  116. $this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $new_request);
  117. $this->assertSame($new_request, \Drupal::request());
  118. $this->assertSame($request, $new_request);
  119. // Ensure getting the router.route_provider does not trigger a deprecation
  120. // message that errors.
  121. $this->container->get('router.route_provider');
  122. }
  123. /**
  124. * Tests whether the fixture allows us to install modules and configuration.
  125. *
  126. * @see ::testSubsequentContainerIsolation()
  127. */
  128. public function testContainerIsolation() {
  129. $this->enableModules(['system', 'user']);
  130. $this->assertNull($this->installConfig('user'));
  131. }
  132. /**
  133. * Tests whether the fixture can re-install modules and configuration.
  134. *
  135. * @depends testContainerIsolation
  136. */
  137. public function testSubsequentContainerIsolation() {
  138. $this->enableModules(['system', 'user']);
  139. $this->assertNull($this->installConfig('user'));
  140. }
  141. /**
  142. * @covers ::render
  143. */
  144. public function testRender() {
  145. $type = 'processed_text';
  146. $element_info = $this->container->get('element_info');
  147. $this->assertSame(['#defaults_loaded' => TRUE], $element_info->getInfo($type));
  148. $this->enableModules(['filter']);
  149. $this->assertNotSame($element_info, $this->container->get('element_info'));
  150. $this->assertNotEmpty($this->container->get('element_info')->getInfo($type));
  151. $build = [
  152. '#type' => 'html_tag',
  153. '#tag' => 'h3',
  154. '#value' => 'Inner',
  155. ];
  156. $expected = "<h3>Inner</h3>\n";
  157. $this->assertEquals('core', \Drupal::theme()->getActiveTheme()->getName());
  158. $output = \Drupal::service('renderer')->renderRoot($build);
  159. $this->assertEquals('core', \Drupal::theme()->getActiveTheme()->getName());
  160. $this->assertEquals($expected, $build['#markup']);
  161. $this->assertEquals($expected, $output);
  162. }
  163. /**
  164. * @covers ::render
  165. */
  166. public function testRenderWithTheme() {
  167. $this->enableModules(['system']);
  168. $build = [
  169. '#type' => 'textfield',
  170. '#name' => 'test',
  171. ];
  172. $expected = '/' . preg_quote('<input type="text" name="test"', '/') . '/';
  173. $this->assertArrayNotHasKey('theme', $GLOBALS);
  174. $output = \Drupal::service('renderer')->renderRoot($build);
  175. $this->assertEquals('core', \Drupal::theme()->getActiveTheme()->getName());
  176. $this->assertRegExp($expected, (string) $build['#children']);
  177. $this->assertRegExp($expected, (string) $output);
  178. }
  179. /**
  180. * @covers ::bootKernel
  181. */
  182. public function testBootKernel() {
  183. $this->assertNull($this->container->get('request_stack')->getParentRequest(), 'There should only be one request on the stack');
  184. $this->assertEquals('public', \Drupal::config('system.file')->get('default_scheme'));
  185. }
  186. /**
  187. * Tests the assumption that local time is in 'Australia/Sydney'.
  188. */
  189. public function testLocalTimeZone() {
  190. // The 'Australia/Sydney' time zone is set in core/tests/bootstrap.php
  191. $this->assertEquals('Australia/Sydney', date_default_timezone_get());
  192. }
  193. /**
  194. * Tests that a test method is skipped when it requires a module not present.
  195. *
  196. * In order to catch checkRequirements() regressions, we have to make a new
  197. * test object and run checkRequirements() here.
  198. *
  199. * @covers ::checkRequirements
  200. * @covers ::checkModuleRequirements
  201. */
  202. public function testMethodRequiresModule() {
  203. require __DIR__ . '/../../fixtures/KernelMissingDependentModuleMethodTest.php';
  204. $stub_test = new KernelMissingDependentModuleMethodTest();
  205. // We have to setName() to the method name we're concerned with.
  206. $stub_test->setName('testRequiresModule');
  207. // We cannot use $this->setExpectedException() because PHPUnit would skip
  208. // the test before comparing the exception type.
  209. try {
  210. $stub_test->publicCheckRequirements();
  211. $this->fail('Missing required module throws skipped test exception.');
  212. }
  213. catch (SkippedTestError $e) {
  214. $this->assertEqual('Required modules: module_does_not_exist', $e->getMessage());
  215. }
  216. }
  217. /**
  218. * Tests that a test case is skipped when it requires a module not present.
  219. *
  220. * In order to catch checkRequirements() regressions, we have to make a new
  221. * test object and run checkRequirements() here.
  222. *
  223. * @covers ::checkRequirements
  224. * @covers ::checkModuleRequirements
  225. */
  226. public function testRequiresModule() {
  227. require __DIR__ . '/../../fixtures/KernelMissingDependentModuleTest.php';
  228. $stub_test = new KernelMissingDependentModuleTest();
  229. // We have to setName() to the method name we're concerned with.
  230. $stub_test->setName('testRequiresModule');
  231. // We cannot use $this->setExpectedException() because PHPUnit would skip
  232. // the test before comparing the exception type.
  233. try {
  234. $stub_test->publicCheckRequirements();
  235. $this->fail('Missing required module throws skipped test exception.');
  236. }
  237. catch (SkippedTestError $e) {
  238. $this->assertEqual('Required modules: module_does_not_exist', $e->getMessage());
  239. }
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. protected function tearDown() {
  245. parent::tearDown();
  246. // Check that all tables of the test instance have been deleted. At this
  247. // point the original database connection is restored so we need to prefix
  248. // the tables.
  249. $connection = Database::getConnection();
  250. if ($connection->databaseType() != 'sqlite') {
  251. $tables = $connection->schema()->findTables($this->databasePrefix . '%');
  252. $this->assertTrue(empty($tables), 'All test tables have been removed.');
  253. }
  254. else {
  255. $result = $connection->query("SELECT name FROM " . $this->databasePrefix . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [
  256. ':type' => 'table',
  257. ':table_name' => '%',
  258. ':pattern' => 'sqlite_%',
  259. ])->fetchAllKeyed(0, 0);
  260. $this->assertTrue(empty($result), 'All test tables have been removed.');
  261. }
  262. }
  263. /**
  264. * Ensures KernelTestBase tests can access modules in profiles.
  265. */
  266. public function testProfileModules() {
  267. $this->assertFileExists('core/profiles/demo_umami/modules/demo_umami_content/demo_umami_content.info.yml');
  268. $this->assertSame(
  269. 'core/profiles/demo_umami/modules/demo_umami_content/demo_umami_content.info.yml',
  270. \Drupal::service('extension.list.module')->getPathname('demo_umami_content')
  271. );
  272. }
  273. }