PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/web/core/tests/Drupal/KernelTests/Core/Command/DbDumpTest.php

https://gitlab.com/mohamed_hussein/prodt
PHP | 276 lines | 159 code | 34 blank | 83 comment | 7 complexity | 7c0653128bec93c9545eb83f71d43967 MD5 | raw file
  1. <?php
  2. namespace Drupal\KernelTests\Core\Command;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Core\Command\DbDumpApplication;
  5. use Drupal\Core\Config\DatabaseStorage;
  6. use Drupal\Core\Database\Database;
  7. use Drupal\Core\DependencyInjection\ContainerBuilder;
  8. use Drupal\KernelTests\KernelTestBase;
  9. use Drupal\Tests\Traits\Core\PathAliasTestTrait;
  10. use Drupal\user\Entity\User;
  11. use Symfony\Component\Console\Tester\CommandTester;
  12. use Symfony\Component\DependencyInjection\Reference;
  13. /**
  14. * Tests for the database dump commands.
  15. *
  16. * @group Update
  17. */
  18. class DbDumpTest extends KernelTestBase {
  19. use PathAliasTestTrait;
  20. /**
  21. * {@inheritdoc}
  22. */
  23. protected static $modules = [
  24. 'system',
  25. 'config',
  26. 'dblog',
  27. 'menu_link_content',
  28. 'link',
  29. 'block_content',
  30. 'file',
  31. 'path_alias',
  32. 'user',
  33. ];
  34. /**
  35. * Test data to write into config.
  36. *
  37. * @var array
  38. */
  39. protected $data;
  40. /**
  41. * An array of original table schemas.
  42. *
  43. * @var array
  44. */
  45. protected $originalTableSchemas = [];
  46. /**
  47. * An array of original table indexes (including primary and unique keys).
  48. *
  49. * @var array
  50. */
  51. protected $originalTableIndexes = [];
  52. /**
  53. * Tables that should be part of the exported script.
  54. *
  55. * @var array
  56. */
  57. protected $tables;
  58. /**
  59. * {@inheritdoc}
  60. *
  61. * Register a database cache backend rather than memory-based.
  62. */
  63. public function register(ContainerBuilder $container) {
  64. parent::register($container);
  65. $container->register('cache_factory', 'Drupal\Core\Cache\DatabaseBackendFactory')
  66. ->addArgument(new Reference('database'))
  67. ->addArgument(new Reference('cache_tags.invalidator.checksum'))
  68. ->addArgument(new Reference('settings'));
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. protected function setUp(): void {
  74. parent::setUp();
  75. if (Database::getConnection()->databaseType() !== 'mysql') {
  76. $this->markTestSkipped("Skipping test since the DbDumpCommand is currently only compatible with MySql");
  77. }
  78. // Create some schemas so our export contains tables.
  79. $this->installSchema('system', ['sessions']);
  80. $this->installSchema('dblog', ['watchdog']);
  81. $this->installEntitySchema('block_content');
  82. $this->installEntitySchema('user');
  83. $this->installEntitySchema('file');
  84. $this->installEntitySchema('menu_link_content');
  85. $this->installEntitySchema('path_alias');
  86. $this->installSchema('system', 'sequences');
  87. // Place some sample config to test for in the export.
  88. $this->data = [
  89. 'foo' => $this->randomMachineName(),
  90. 'bar' => $this->randomMachineName(),
  91. ];
  92. $storage = new DatabaseStorage(Database::getConnection(), 'config');
  93. $storage->write('test_config', $this->data);
  94. // Create user account with some potential syntax issues.
  95. // cspell:disable-next-line
  96. $account = User::create(['mail' => 'q\'uote$dollar@example.com', 'name' => '$dollar']);
  97. $account->save();
  98. // Create a path alias.
  99. $this->createPathAlias('/user/' . $account->id(), '/user/example');
  100. // Create a cache table (this will create 'cache_discovery').
  101. \Drupal::cache('discovery')->set('test', $this->data);
  102. // These are all the tables that should now be in place.
  103. $this->tables = [
  104. 'block_content',
  105. 'block_content_field_data',
  106. 'block_content_field_revision',
  107. 'block_content_revision',
  108. 'cachetags',
  109. 'config',
  110. 'cache_bootstrap',
  111. 'cache_config',
  112. 'cache_discovery',
  113. 'cache_entity',
  114. 'file_managed',
  115. 'menu_link_content',
  116. 'menu_link_content_data',
  117. 'menu_link_content_revision',
  118. 'menu_link_content_field_revision',
  119. 'sequences',
  120. 'sessions',
  121. 'path_alias',
  122. 'path_alias_revision',
  123. 'user__roles',
  124. 'users',
  125. 'users_field_data',
  126. 'watchdog',
  127. ];
  128. }
  129. /**
  130. * Tests the command directly.
  131. */
  132. public function testDbDumpCommand() {
  133. $application = new DbDumpApplication();
  134. $command = $application->find('dump-database-d8-mysql');
  135. $command_tester = new CommandTester($command);
  136. $command_tester->execute([]);
  137. // Tables that are schema-only should not have data exported.
  138. $pattern = preg_quote("\$connection->insert('sessions')");
  139. $this->assertDoesNotMatchRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'Tables defined as schema-only do not have data exported to the script.');
  140. // Table data is exported.
  141. $pattern = preg_quote("\$connection->insert('config')");
  142. $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'Table data is properly exported to the script.');
  143. // The test data are in the dump (serialized).
  144. $pattern = preg_quote(serialize($this->data));
  145. $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'Generated data is found in the exported script.');
  146. // Check that the user account name and email address was properly escaped.
  147. // cspell:disable-next-line
  148. $pattern = preg_quote('"q\'uote\$dollar@example.com"');
  149. $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'The user account email address was properly escaped in the exported script.');
  150. $pattern = preg_quote('\'$dollar\'');
  151. $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'The user account name was properly escaped in the exported script.');
  152. }
  153. /**
  154. * Tests loading the script back into the database.
  155. */
  156. public function testScriptLoad() {
  157. // Generate the script.
  158. $application = new DbDumpApplication();
  159. $command = $application->find('dump-database-d8-mysql');
  160. $command_tester = new CommandTester($command);
  161. $command_tester->execute([]);
  162. $script = $command_tester->getDisplay();
  163. // Store original schemas and drop tables to avoid errors.
  164. $connection = Database::getConnection();
  165. $schema = $connection->schema();
  166. foreach ($this->tables as $table) {
  167. $this->originalTableSchemas[$table] = $this->getTableSchema($table);
  168. $this->originalTableIndexes[$table] = $this->getTableIndexes($table);
  169. $schema->dropTable($table);
  170. }
  171. // This will load the data.
  172. $file = sys_get_temp_dir() . '/' . $this->randomMachineName();
  173. file_put_contents($file, $script);
  174. require_once $file;
  175. // The tables should now exist and the schemas should match the originals.
  176. foreach ($this->tables as $table) {
  177. $this->assertTrue($schema
  178. ->tableExists($table), new FormattableMarkup('Table @table created by the database script.', ['@table' => $table]));
  179. $this->assertSame($this->originalTableSchemas[$table], $this->getTableSchema($table), new FormattableMarkup('The schema for @table was properly restored.', ['@table' => $table]));
  180. $this->assertSame($this->originalTableIndexes[$table], $this->getTableIndexes($table), new FormattableMarkup('The indexes for @table were properly restored.', ['@table' => $table]));
  181. }
  182. // Ensure the test config has been replaced.
  183. $config = unserialize($connection->select('config', 'c')->fields('c', ['data'])->condition('name', 'test_config')->execute()->fetchField());
  184. $this->assertSame($this->data, $config, 'Script has properly restored the config table data.');
  185. // Ensure the cache data was not exported.
  186. $this->assertFalse(\Drupal::cache('discovery')
  187. ->get('test'), 'Cache data was not exported to the script.');
  188. }
  189. /**
  190. * Helper function to get a simplified schema for a given table.
  191. *
  192. * @param string $table
  193. * The table name.
  194. *
  195. * @return array
  196. * Array keyed by field name, with the values being the field type.
  197. */
  198. protected function getTableSchema($table) {
  199. // Verify the field type on the data column in the cache table.
  200. // @todo this is MySQL specific.
  201. $query = Database::getConnection()->query("SHOW COLUMNS FROM {" . $table . "}");
  202. $definition = [];
  203. while ($row = $query->fetchAssoc()) {
  204. $definition[$row['Field']] = $row['Type'];
  205. }
  206. return $definition;
  207. }
  208. /**
  209. * Returns indexes for a given table.
  210. *
  211. * @param string $table
  212. * The table to find indexes for.
  213. *
  214. * @return array
  215. * The 'primary key', 'unique keys', and 'indexes' portion of the Drupal
  216. * table schema.
  217. */
  218. protected function getTableIndexes($table) {
  219. $query = Database::getConnection()->query("SHOW INDEX FROM {" . $table . "}");
  220. $definition = [];
  221. while ($row = $query->fetchAssoc()) {
  222. $index_name = $row['Key_name'];
  223. $column = $row['Column_name'];
  224. // Key the arrays by the index sequence for proper ordering (start at 0).
  225. $order = $row['Seq_in_index'] - 1;
  226. // If specified, add length to the index.
  227. if ($row['Sub_part']) {
  228. $column = [$column, $row['Sub_part']];
  229. }
  230. if ($index_name === 'PRIMARY') {
  231. $definition['primary key'][$order] = $column;
  232. }
  233. elseif ($row['Non_unique'] == 0) {
  234. $definition['unique keys'][$index_name][$order] = $column;
  235. }
  236. else {
  237. $definition['indexes'][$index_name][$order] = $column;
  238. }
  239. }
  240. return $definition;
  241. }
  242. }