From 28a9703ec7cf018d260a8ffc0b039082ea913b48 Mon Sep 17 00:00:00 2001 From: Alexis Lefebvre Date: Mon, 11 Mar 2024 00:22:41 +0100 Subject: [PATCH] chore: remove backup --- .github/workflows/tests.yml | 13 +- doc/configuration.md | 5 - doc/database.md | 34 ---- doc/events.md | 12 +- src/Event/FixtureEvent.php | 12 +- src/Event/PostFixtureBackupRestoreEvent.php | 29 ---- src/Event/PreFixtureBackupRestoreEvent.php | 49 ------ src/Event/ReferenceSaveEvent.php | 49 ------ src/LiipTestFixturesEvents.php | 15 -- .../DatabaseBackup/AbstractDatabaseBackup.php | 105 ------------ .../DatabaseBackupInterface.php | 32 ---- .../DatabaseBackup/MongodbDatabaseBackup.php | 119 ------------- .../DatabaseBackup/MysqlDatabaseBackup.php | 160 ------------------ .../DatabaseBackup/SqliteDatabaseBackup.php | 78 --------- .../DatabaseTools/AbstractDatabaseTool.php | 44 ----- .../DatabaseTools/MongoDBDatabaseTool.php | 35 ---- .../DatabaseTools/ORMDatabaseTool.php | 44 +---- .../DatabaseTools/ORMSqliteDatabaseTool.php | 43 +---- .../EventListener/FixturesSubscriber.php | 43 +---- .../AppConfigMysqlKernelCacheDb.php | 35 ---- tests/AppConfigMysqlCacheDb/config.yml | 5 - tests/Test/ConfigEventsTest.php | 51 +----- tests/Test/ConfigMysqlCacheDbTest.php | 129 -------------- tests/Test/ConfigMysqlTest.php | 2 + tests/Test/ConfigTest.php | 123 -------------- 25 files changed, 17 insertions(+), 1249 deletions(-) delete mode 100644 src/Event/PostFixtureBackupRestoreEvent.php delete mode 100644 src/Event/PreFixtureBackupRestoreEvent.php delete mode 100644 src/Event/ReferenceSaveEvent.php delete mode 100644 src/Services/DatabaseBackup/AbstractDatabaseBackup.php delete mode 100644 src/Services/DatabaseBackup/DatabaseBackupInterface.php delete mode 100644 src/Services/DatabaseBackup/MongodbDatabaseBackup.php delete mode 100644 src/Services/DatabaseBackup/MysqlDatabaseBackup.php delete mode 100644 src/Services/DatabaseBackup/SqliteDatabaseBackup.php delete mode 100644 tests/AppConfigMysqlCacheDb/AppConfigMysqlKernelCacheDb.php delete mode 100644 tests/AppConfigMysqlCacheDb/config.yml delete mode 100644 tests/Test/ConfigMysqlCacheDbTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 168552b1..fee6fc1c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,7 +4,7 @@ on: [push, pull_request] jobs: tests: - name: Symfony ${{ matrix.symfony-version }} - PHP ${{ matrix.php-version }} - flags ${{ matrix.composer-flags }} - mysqldump ${{ matrix.mysql-client }} + name: Symfony ${{ matrix.symfony-version }} - PHP ${{ matrix.php-version }} - flags ${{ matrix.composer-flags }} runs-on: ubuntu-latest strategy: @@ -13,7 +13,6 @@ jobs: php-version: [''] composer-flags: [''] symfony-version: [''] - mysql-client: [ "default-mysql-client" ] include: - php-version: 8.1 # Use "update" instead of "install" since it allows using the "--prefer-lowest" option @@ -21,10 +20,6 @@ jobs: - php-version: 8.1 # add a specific job to test ^5.4 for all Symfony packages symfony-version: "^5.4" - - php-version: 8.1 - symfony-version: "^5.4" - # add a specific job to test mysqldump from MariaDB - mysql-client: "mariadb-client" - php-version: 8.2 # add a specific job to test ^6.4 for all Symfony packages symfony-version: "^6.4" @@ -61,12 +56,6 @@ jobs: - 27017:27017 steps: - - name: Install mysqldump - run: | - sudo apt update - sudo apt install -y -q ${{ matrix.mysql-client }} - mysqldump --version - - name: Install mongodb database tools run: | wget https://fastdl.mongodb.org/tools/db/mongodb-database-tools-debian92-x86_64-100.3.1.deb diff --git a/doc/configuration.md b/doc/configuration.md index f40f823d..76a0a140 100644 --- a/doc/configuration.md +++ b/doc/configuration.md @@ -7,16 +7,11 @@ Here is the full configuration with default values: liip_test_fixtures: keep_database_and_schema: false cache_metadata: true - cache_db: ~ ``` - `keep_database_and_schema`: pass it to `true` to avoid deleting and creating the database and schema before each test, you'll have to create the database schema before running your tests: 1. create database with `bin/console --env=test doctrine:database:create`: 2. create schema with `bin/console --env=test doctrine:schema:update --force` or `bin/console --env=test doctrine:migrations:migrate --no-interaction` - `cache_metadata`: using the cache slightly improve the performance -- `cache_db`: an array with a storage as key and a service as value, examples : - - `sqlite: 'Liip\TestFixturesBundle\Services\DatabaseBackup\SqliteDatabaseBackup'` - - `mysql: 'Liip\TestFixturesBundle\Services\DatabaseBackup\MysqlDatabaseBackup'` - - `mongodb: 'Liip\TestFixturesBundle\Services\DatabaseBackup\MongodbDatabaseBackup'` « [Installation](./installation.md) • [Database](./database.md) » diff --git a/doc/database.md b/doc/database.md index af4a2174..31c3b54b 100644 --- a/doc/database.md +++ b/doc/database.md @@ -109,40 +109,6 @@ Tips for Fixture Loading Tests NB: If you have an existing Doctrine configuration which uses slaves be sure to separate out the configuration for the slaves. Further detail is provided at the bottom of this README. - 2. In order to run your tests even faster, use LiipFunctionalBundle cached database. - This will create backups of the initial databases (with all fixtures loaded) - and re-load them when required. - - **Attention: you need Doctrine >= 2.2 to use this feature.** - - ```yaml - # sf4: config/packages/test/framework.yaml - liip_test_fixtures: - cache_db: - sqlite: 'Liip\TestFixturesBundle\Services\DatabaseBackup\SqliteDatabaseBackup' - ``` - -### Custom database cache services ([↑](#methods)) - - To create custom database cache service: - -Create cache class, implement `\Liip\TestFixturesBundle\Services\DatabaseBackup\DatabaseBackupInterface` and add it to config - -For example: -```yaml -# app/config/config_test.yml -liip_test_fixtures: - cache_db: - mysql: 'Liip\TestFixturesBundle\Services\DatabaseBackup\MysqlDatabaseBackup' - mongodb: 'Liip\TestFixturesBundle\Services\DatabaseBackup\MongodbDatabaseBackup' - db2: ... - [Other \Doctrine\DBAL\Platforms\AbstractPlatform name]: ... -``` - -**Attention: `Liip\TestFixturesBundle\Services\DatabaseBackup\MysqlDatabaseBackup` requires `mysql-client` installed on server.** - -**Attention: `Liip\TestFixturesBundle\Services\DatabaseBackup\MongodbDatabaseBackup` requires `mongodb-clients` installed on server.** - ### Load fixtures ([↑](#methods)) Load your Doctrine fixtures in your tests: diff --git a/doc/events.md b/doc/events.md index 1a6fa2b4..c66e7d31 100644 --- a/doc/events.md +++ b/doc/events.md @@ -2,11 +2,7 @@ Available events: -- `LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE`: triggered before restoring the backup -- `LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE`: triggered after the backup has been restored - `LiipTestFixturesEvents::POST_FIXTURE_SETUP`: triggered before purging the database -- `LiipTestFixturesEvents::PRE_REFERENCE_SAVE`: triggered before saving the backup of fixtures -- `LiipTestFixturesEvents::POST_REFERENCE_SAVE`: triggered before the backup of fixtures has been saved ## Registering events @@ -28,16 +24,12 @@ class FixturesSubscriber implements EventSubscriberInterface public static function getSubscribedEvents(): array { return [ - LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE => 'preFixtureBackupRestore', + LiipTestFixturesEvents::POST_FIXTURE_SETUP => 'postFixtureSetup', ]; } - public function preFixtureBackupRestore(PreFixtureBackupRestoreEvent $preFixtureBackupRestoreEvent): void + public function postFixtureSetup(FixtureEvent $fixtureEvent): void { - $manager = $preFixtureBackupRestoreEvent->getManager(); - $repository = $preFixtureBackupRestoreEvent->getRepository(); - $backupFilePath = $preFixtureBackupRestoreEvent->getBackupFilePath(); - // your code } } diff --git a/src/Event/FixtureEvent.php b/src/Event/FixtureEvent.php index eb4e7d79..b6e29101 100644 --- a/src/Event/FixtureEvent.php +++ b/src/Event/FixtureEvent.php @@ -13,16 +13,8 @@ namespace Liip\TestFixturesBundle\Event; -// Compatibility layer to use Contract if Symfony\Contracts\EventDispatcher\Event is not available use Symfony\Contracts\EventDispatcher\Event; -if (class_exists('\Symfony\Component\EventDispatcher\Event')) { - // Symfony < 5.0 - class FixtureEvent extends \Symfony\Component\EventDispatcher\Event - { - } -} else { - class FixtureEvent extends Event - { - } +class FixtureEvent extends Event +{ } diff --git a/src/Event/PostFixtureBackupRestoreEvent.php b/src/Event/PostFixtureBackupRestoreEvent.php deleted file mode 100644 index b8ff4241..00000000 --- a/src/Event/PostFixtureBackupRestoreEvent.php +++ /dev/null @@ -1,29 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Event; - -class PostFixtureBackupRestoreEvent extends FixtureEvent -{ - private $backupFilePath; - - public function __construct(string $backupFilePath) - { - $this->backupFilePath = $backupFilePath; - } - - public function getBackupFilePath(): string - { - return $this->backupFilePath; - } -} diff --git a/src/Event/PreFixtureBackupRestoreEvent.php b/src/Event/PreFixtureBackupRestoreEvent.php deleted file mode 100644 index 3eddc939..00000000 --- a/src/Event/PreFixtureBackupRestoreEvent.php +++ /dev/null @@ -1,49 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Event; - -use Doctrine\Common\DataFixtures\ReferenceRepository; -use Doctrine\Persistence\ObjectManager; - -class PreFixtureBackupRestoreEvent extends FixtureEvent -{ - private $manager; - private $repository; - private $backupFilePath; - - public function __construct( - ObjectManager $manager, - ReferenceRepository $executor, - string $backupFilePath - ) { - $this->manager = $manager; - $this->repository = $executor; - $this->backupFilePath = $backupFilePath; - } - - public function getManager(): ObjectManager - { - return $this->manager; - } - - public function getRepository(): ReferenceRepository - { - return $this->repository; - } - - public function getBackupFilePath(): string - { - return $this->backupFilePath; - } -} diff --git a/src/Event/ReferenceSaveEvent.php b/src/Event/ReferenceSaveEvent.php deleted file mode 100644 index c956f3d7..00000000 --- a/src/Event/ReferenceSaveEvent.php +++ /dev/null @@ -1,49 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Event; - -use Doctrine\Common\DataFixtures\Executor\AbstractExecutor; -use Doctrine\Persistence\ObjectManager; - -class ReferenceSaveEvent extends FixtureEvent -{ - private $manager; - private $executor; - private $backupFilePath; - - public function __construct( - ObjectManager $manager, - AbstractExecutor $executor, - string $backupFilePath - ) { - $this->manager = $manager; - $this->executor = $executor; - $this->backupFilePath = $backupFilePath; - } - - public function getManager(): ObjectManager - { - return $this->manager; - } - - public function getExecutor(): AbstractExecutor - { - return $this->executor; - } - - public function getBackupFilePath(): string - { - return $this->backupFilePath; - } -} diff --git a/src/LiipTestFixturesEvents.php b/src/LiipTestFixturesEvents.php index 51ded442..cc3cfee1 100644 --- a/src/LiipTestFixturesEvents.php +++ b/src/LiipTestFixturesEvents.php @@ -14,24 +14,9 @@ namespace Liip\TestFixturesBundle; use Liip\TestFixturesBundle\Event\FixtureEvent; -use Liip\TestFixturesBundle\Event\PostFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\PreFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\ReferenceSaveEvent; final class LiipTestFixturesEvents { - /** @see PreFixtureBackupRestoreEvent */ - public const PRE_FIXTURE_BACKUP_RESTORE = 'liip_test_fixtures.pre_fixture_backup_restore'; - /** @see FixtureEvent */ public const POST_FIXTURE_SETUP = 'liip_test_fixtures.post_fixture_setup'; - - /** @see PostFixtureBackupRestoreEvent */ - public const POST_FIXTURE_BACKUP_RESTORE = 'liip_test_fixtures.post_fixture_backup_restore'; - - /** @see ReferenceSaveEvent */ - public const PRE_REFERENCE_SAVE = 'liip_test_fixtures.pre_reference_save'; - - /** @see ReferenceSaveEvent */ - public const POST_REFERENCE_SAVE = 'liip_test_fixtures.post_reference_save'; } diff --git a/src/Services/DatabaseBackup/AbstractDatabaseBackup.php b/src/Services/DatabaseBackup/AbstractDatabaseBackup.php deleted file mode 100644 index 7eb096ec..00000000 --- a/src/Services/DatabaseBackup/AbstractDatabaseBackup.php +++ /dev/null @@ -1,105 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Services\DatabaseBackup; - -use Liip\TestFixturesBundle\FixturesLoaderFactoryInterface; -use Symfony\Component\DependencyInjection\ContainerInterface; - -/** - * @author Aleksey Tupichenkov - */ -abstract class AbstractDatabaseBackup implements DatabaseBackupInterface -{ - protected $container; - - protected $fixturesLoaderFactory; - - /** - * @var array - */ - protected $metadatas; - - /** - * The fixture classnames. - * - * @var array - */ - protected $classNames = []; - - public function __construct(ContainerInterface $container, FixturesLoaderFactoryInterface $fixturesLoaderFactory) - { - $this->container = $container; - $this->fixturesLoaderFactory = $fixturesLoaderFactory; - } - - public function init(array $metadatas, array $classNames, bool $append = false): void - { - $this->metadatas = $metadatas; - - if ($append) { - $this->classNames = array_merge($this->classNames, $classNames); - } else { - $this->classNames = $classNames; - } - } - - /** - * Determine if the Fixtures that define a database backup have been - * modified since the backup was made. - * - * @param string $backup The fixture backup database file path - * - * @return bool TRUE if the backup was made since the modifications to the - * fixtures; FALSE otherwise - */ - protected function isBackupUpToDate(string $backup): bool - { - $backupLastModifiedDateTime = \DateTime::createFromFormat('U', (string) filemtime($backup)); - - $loader = $this->fixturesLoaderFactory->getFixtureLoader($this->classNames); - - // Use loader in order to fetch all the dependencies fixtures. - foreach ($loader->getFixtures() as $className) { - $fixtureLastModifiedDateTime = $this->getFixtureLastModified($className); - if ($backupLastModifiedDateTime < $fixtureLastModifiedDateTime) { - return false; - } - } - - return true; - } - - /** - * This function finds the time when the data blocks of a class definition - * file were being written to, that is, the time when the content of the - * file was changed. - * - * @param string $class The fully qualified class name of the fixture class to - * check modification date on - */ - protected function getFixtureLastModified($class): ?\DateTime - { - $lastModifiedDateTime = null; - - $reflClass = new \ReflectionClass($class); - $classFileName = $reflClass->getFileName(); - - if (file_exists($classFileName)) { - $lastModifiedDateTime = new \DateTime(); - $lastModifiedDateTime->setTimestamp(filemtime($classFileName)); - } - - return $lastModifiedDateTime; - } -} diff --git a/src/Services/DatabaseBackup/DatabaseBackupInterface.php b/src/Services/DatabaseBackup/DatabaseBackupInterface.php deleted file mode 100644 index abf7f08a..00000000 --- a/src/Services/DatabaseBackup/DatabaseBackupInterface.php +++ /dev/null @@ -1,32 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Services\DatabaseBackup; - -use Doctrine\Common\DataFixtures\Executor\AbstractExecutor; - -/** - * @author Aleksey Tupichenkov - */ -interface DatabaseBackupInterface -{ - public function init(array $metadatas, array $classNames, bool $append = false): void; - - public function getBackupFilePath(): string; - - public function isBackupActual(): bool; - - public function backup(AbstractExecutor $executor): void; - - public function restore(AbstractExecutor $executor, array $excludedTables = []): void; -} diff --git a/src/Services/DatabaseBackup/MongodbDatabaseBackup.php b/src/Services/DatabaseBackup/MongodbDatabaseBackup.php deleted file mode 100644 index 49934b5e..00000000 --- a/src/Services/DatabaseBackup/MongodbDatabaseBackup.php +++ /dev/null @@ -1,119 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Services\DatabaseBackup; - -use Doctrine\Common\DataFixtures\Executor\AbstractExecutor; -use Doctrine\ODM\MongoDB\DocumentManager; -use MongoDB\Driver\Server; - -/** - * @author Aleksey Tupichenkov - */ -final class MongodbDatabaseBackup extends AbstractDatabaseBackup -{ - protected static $referenceData; - - protected static $metadata; - - protected static $databases; - - public function getBackupFilePath(): string - { - return $this->container->getParameter('kernel.cache_dir').'/test_mongodb_'.md5(serialize($this->metadatas).serialize($this->classNames)); - } - - public function getReferenceBackupFilePath(): string - { - return $this->getBackupFilePath().'.ser'; - } - - public function isBackupActual(): bool - { - return - file_exists($this->getBackupFilePath()) - && file_exists($this->getReferenceBackupFilePath()) - && $this->isBackupUpToDate($this->getBackupFilePath()); - } - - public function backup(AbstractExecutor $executor): void - { - /** @var DocumentManager $dm */ - $dm = $executor->getReferenceRepository()->getManager(); - - foreach ($this->getDatabases($dm) as $dbName => $server) { - /** - * @var Server $server - */ - $dbHost = $server->getHost(); - $dbPort = $server->getPort(); - - exec("mongodump --quiet --forceTableScan --db {$dbName} --host {$dbHost} --port {$dbPort} --out {$this->getBackupFilePath()}"); - } - - $executor->getReferenceRepository()->save($this->getBackupFilePath()); - self::$metadata = $dm->getMetadataFactory()->getLoadedMetadata(); - } - - public function restore(AbstractExecutor $executor, array $excludedTables = []): void - { - /** @var DocumentManager $dm */ - $dm = $executor->getReferenceRepository()->getManager(); - - foreach ($this->getDatabases($dm) as $dbName => $server) { - /** - * @var Server $server - */ - $dbHost = $server->getHost(); - $dbPort = $server->getPort(); - - exec("mongorestore --quiet --drop --db {$dbName} --host {$dbHost} --port {$dbPort} {$this->getBackupFilePath()}/{$dbName}", $output); - } - - if (self::$metadata) { - // it need for better performance - foreach (self::$metadata as $class => $data) { - $dm->getMetadataFactory()->setMetadataFor($class, $data); - } - $executor->getReferenceRepository()->unserialize($this->getReferenceBackup()); - } else { - $executor->getReferenceRepository()->unserialize($this->getReferenceBackup()); - self::$metadata = $dm->getMetadataFactory()->getLoadedMetadata(); - } - } - - protected function getReferenceBackup(): string - { - if (empty(self::$referenceData)) { - self::$referenceData = file_get_contents($this->getReferenceBackupFilePath()); - } - - return self::$referenceData; - } - - protected function getDatabases(DocumentManager $dm): array - { - if (!self::$databases) { - self::$databases = []; - foreach ($dm->getDocumentDatabases() as $db) { - $hosts = $db->getManager()->getServers(); - - foreach ($hosts as $host) { - self::$databases[$db->getDatabaseName()] = $host; - } - } - } - - return self::$databases; - } -} diff --git a/src/Services/DatabaseBackup/MysqlDatabaseBackup.php b/src/Services/DatabaseBackup/MysqlDatabaseBackup.php deleted file mode 100644 index 6d074746..00000000 --- a/src/Services/DatabaseBackup/MysqlDatabaseBackup.php +++ /dev/null @@ -1,160 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Services\DatabaseBackup; - -use Doctrine\Common\DataFixtures\Executor\AbstractExecutor; -use Doctrine\ORM\EntityManager; -use Doctrine\ORM\Tools\SchemaTool; - -/** - * @author Aleksey Tupichenkov - */ -final class MysqlDatabaseBackup extends AbstractDatabaseBackup -{ - protected static $metadata; - - protected static $schemaUpdatedFlag = false; - - public function getBackupFilePath(): string - { - return $this->container->getParameter('kernel.cache_dir').'/test_mysql_'.md5(serialize($this->metadatas).serialize($this->classNames)).'.sql'; - } - - public function getReferenceBackupFilePath(): string - { - return $this->getBackupFilePath().'.ser'; - } - - public function isBackupActual(): bool - { - return - file_exists($this->getBackupFilePath()) - && file_exists($this->getReferenceBackupFilePath()) - && $this->isBackupUpToDate($this->getBackupFilePath()); - } - - public function backup(AbstractExecutor $executor): void - { - /** @var EntityManager $em */ - $em = $executor->getReferenceRepository()->getManager(); - $connection = $em->getConnection(); - - $params = $connection->getParams(); - - // doctrine-bundle >= 2.2 - if (isset($params['primary'])) { - $params = $params['primary']; - } - // doctrine-bundle < 2.2 - elseif (isset($params['master'])) { - $params = $params['master']; - } - - $dbName = $params['dbname'] ?? ''; - $dbHost = $params['host'] ?? ''; - - // Define parameter only if there's a value, to avoid warning from mysqldump: - // mysqldump: [Warning] mysqldump: Empty value for 'port' specified. Will throw an error in future versions - $port = isset($params['port']) && $params['port'] ? '--port='.$params['port'] : ''; - - $dbUser = $params['user'] ?? ''; - // Set password through environment variable to remove warning - $dbPass = isset($params['password']) && $params['password'] ? 'MYSQL_PWD='.$params['password'].' ' : ''; - - $executor->getReferenceRepository()->save($this->getBackupFilePath()); - self::$metadata = $em->getMetadataFactory()->getLoadedMetadata(); - - $mysqldumpOptions = '--no-create-info --skip-triggers --no-create-db --no-tablespaces --compact'; - $mysqldumpCommand = 'mysqldump --host '.$dbHost.' '.$port.' --user '.$dbUser.' '.$dbName.' '.$mysqldumpOptions; - - exec( - 'mysqldump --version', - $output, - ); - - if (false === stripos(implode('', $output), 'MariaDB')) { - // when mysqldump is provided by MySQL (and not MariaDB), “--column-statistics=0” is a valid option, add it - $mysqldumpCommand .= ' --column-statistics=0'; - } - - exec( - $dbPass.' '.$mysqldumpCommand.' > '.$this->getBackupFilePath() - ); - } - - public function restore(AbstractExecutor $executor, array $excludedTables = []): void - { - /** @var EntityManager $em */ - $em = $executor->getReferenceRepository()->getManager(); - $connection = $em->getConnection(); - - $connection->executeQuery('SET FOREIGN_KEY_CHECKS = 0;'); - - $this->updateSchemaIfNeed($em); - $truncateSql = []; - foreach ($this->metadatas as $classMetadata) { - $tableName = $classMetadata->table['name']; - - if (!\in_array($tableName, $excludedTables, true)) { - $truncateSql[] = 'DELETE FROM '.$tableName; // in small tables it's really faster than truncate - } - } - if (!empty($truncateSql)) { - $connection->executeQuery(implode(';', $truncateSql)); - } - - // Only run query if it exists, to avoid the following exception: - // SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty - $backup = $this->getBackup(); - if (!empty($backup)) { - $connection->executeQuery($backup); - } - - $connection->executeQuery('SET FOREIGN_KEY_CHECKS = 1;'); - - if (self::$metadata) { - // it need for better performance - foreach (self::$metadata as $class => $data) { - $em->getMetadataFactory()->setMetadataFor($class, $data); - } - $executor->getReferenceRepository()->unserialize($this->getReferenceBackup()); - } else { - $executor->getReferenceRepository()->unserialize($this->getReferenceBackup()); - self::$metadata = $em->getMetadataFactory()->getLoadedMetadata(); - } - } - - protected function getBackup() - { - return file_get_contents($this->getBackupFilePath()); - } - - protected function getReferenceBackup(): string - { - return file_get_contents($this->getReferenceBackupFilePath()); - } - - protected function updateSchemaIfNeed(EntityManager $em): void - { - if (!self::$schemaUpdatedFlag) { - $schemaTool = new SchemaTool($em); - $schemaTool->dropDatabase(); - if (!empty($this->metadatas)) { - $schemaTool->createSchema($this->metadatas); - } - - self::$schemaUpdatedFlag = true; - } - } -} diff --git a/src/Services/DatabaseBackup/SqliteDatabaseBackup.php b/src/Services/DatabaseBackup/SqliteDatabaseBackup.php deleted file mode 100644 index ce8cb77a..00000000 --- a/src/Services/DatabaseBackup/SqliteDatabaseBackup.php +++ /dev/null @@ -1,78 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\TestFixturesBundle\Services\DatabaseBackup; - -use Doctrine\Common\DataFixtures\Executor\AbstractExecutor; -use Doctrine\DBAL\Connection; -use Doctrine\ORM\EntityManager; - -/** - * @author Aleksey Tupichenkov - */ -final class SqliteDatabaseBackup extends AbstractDatabaseBackup -{ - public function getBackupFilePath(): string - { - return $this->container->getParameter('kernel.cache_dir').'/test_sqlite_'.md5(serialize($this->metadatas).serialize($this->classNames)).'.db'; - } - - public function isBackupActual(): bool - { - $backupDBFileName = $this->getBackupFilePath(); - $backupReferenceFileName = $backupDBFileName.'.ser'; - - return file_exists($backupDBFileName) && file_exists($backupReferenceFileName) && $this->isBackupUpToDate($backupDBFileName); - } - - public function backup(AbstractExecutor $executor): void - { - /** @var EntityManager $em */ - $em = $executor->getReferenceRepository()->getManager(); - $connection = $em->getConnection(); - - $executor->getReferenceRepository()->save($this->getBackupFilePath()); - copy($this->getDatabaseName($connection), $this->getBackupFilePath()); - } - - public function restore(AbstractExecutor $executor, array $excludedTables = []): void - { - /** @var EntityManager $em */ - $em = $executor->getReferenceRepository()->getManager(); - $connection = $em->getConnection(); - - copy($this->getBackupFilePath(), $this->getDatabaseName($connection)); - $executor->getReferenceRepository()->load($this->getBackupFilePath()); - } - - private function getDatabaseName(Connection $connection): string - { - $params = $connection->getParams(); - - // doctrine-bundle >= 2.2 - if (isset($params['primary'])) { - $params = $params['primary']; - } - // doctrine-bundle < 2.2 - elseif (isset($params['master'])) { - $params = $params['master']; - } - - $name = $params['path'] ?? ($params['dbname'] ?? false); - if (!$name) { - throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped."); - } - - return $name; - } -} diff --git a/src/Services/DatabaseTools/AbstractDatabaseTool.php b/src/Services/DatabaseTools/AbstractDatabaseTool.php index 495d36a5..c929a1fb 100644 --- a/src/Services/DatabaseTools/AbstractDatabaseTool.php +++ b/src/Services/DatabaseTools/AbstractDatabaseTool.php @@ -18,7 +18,6 @@ use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ObjectManager; use Liip\TestFixturesBundle\FixturesLoaderFactoryInterface; -use Liip\TestFixturesBundle\Services\DatabaseBackup\DatabaseBackupInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -62,11 +61,6 @@ abstract class AbstractDatabaseTool */ protected $purgeMode; - /** - * @var bool - */ - protected $databaseCacheEnabled = true; - protected $excludedDoctrineTables = []; /** @@ -86,16 +80,6 @@ public function setRegistry(ManagerRegistry $registry): void $this->registry = $registry; } - public function setDatabaseCacheEnabled(bool $databaseCacheEnabled): void - { - $this->databaseCacheEnabled = $databaseCacheEnabled; - } - - public function isDatabaseCacheEnabled(): bool - { - return $this->databaseCacheEnabled; - } - public function setObjectManagerName(?string $omName = null): void { $this->omName = $omName; @@ -127,14 +111,6 @@ public function withPurgeMode(int $purgeMode): self return $newTool; } - public function withDatabaseCacheEnabled(bool $databaseCacheEnabled): self - { - $newTool = clone $this; - $newTool->setDatabaseCacheEnabled($databaseCacheEnabled); - - return $newTool; - } - abstract public function loadFixtures(array $classNames = [], bool $append = false): AbstractExecutor; /** @@ -182,26 +158,6 @@ public function setExcludedDoctrineTables(array $excludedDoctrineTables): void $this->excludedDoctrineTables = $excludedDoctrineTables; } - protected function getBackupService(): ?DatabaseBackupInterface - { - $backupServiceParamName = strtolower('liip_test_fixtures.cache_db.'.( - ('ORM' === $this->getType()) - ? $this->getPlatformName() - : $this->getType() - )); - - if ($this->container->hasParameter($backupServiceParamName)) { - $backupServiceName = $this->container->getParameter($backupServiceParamName); - if (\is_string($backupServiceName) && $this->container->has($backupServiceName)) { - $backupService = $this->container->get($backupServiceName); - } else { - @trigger_error("Could not find {$backupServiceName} in container. Possible misconfiguration."); - } - } - - return (isset($backupService) && $backupService instanceof DatabaseBackupInterface) ? $backupService : null; - } - protected function cleanDatabase(): void { $this->loadFixtures([]); diff --git a/src/Services/DatabaseTools/MongoDBDatabaseTool.php b/src/Services/DatabaseTools/MongoDBDatabaseTool.php index d091e012..e713ee6d 100644 --- a/src/Services/DatabaseTools/MongoDBDatabaseTool.php +++ b/src/Services/DatabaseTools/MongoDBDatabaseTool.php @@ -18,10 +18,6 @@ use Doctrine\Common\DataFixtures\ProxyReferenceRepository; use Doctrine\Common\DataFixtures\Purger\MongoDBPurger; use Doctrine\ODM\MongoDB\Configuration; -use Liip\TestFixturesBundle\Event\PostFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\PreFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\ReferenceSaveEvent; -use Liip\TestFixturesBundle\LiipTestFixturesEvents; /** * @author Aleksey Tupichenkov @@ -50,28 +46,6 @@ public function loadFixtures(array $classNames = [], bool $append = false): Abst $this->createDatabaseOnce(); - $backupService = $this->getBackupService(); - if ($backupService) { - $backupService->init($this->getMetadatas(), $classNames); - - if ($backupService->isBackupActual()) { - $this->om->flush(); - $this->om->clear(); - - $event = new PreFixtureBackupRestoreEvent($this->om, $referenceRepository, $backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE); - - $executor = $this->getExecutor($this->getPurger()); - $executor->setReferenceRepository($referenceRepository); - $backupService->restore($executor); - - $event = new PostFixtureBackupRestoreEvent($backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE); - - return $executor; - } - } - $executor = $this->getExecutor($this->getPurger()); $executor->setReferenceRepository($referenceRepository); if (false === $append) { @@ -81,15 +55,6 @@ public function loadFixtures(array $classNames = [], bool $append = false): Abst $loader = $this->fixturesLoaderFactory->getFixtureLoader($classNames); $executor->execute($loader->getFixtures(), true); - if ($backupService) { - $event = new ReferenceSaveEvent($this->om, $executor, $backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::PRE_REFERENCE_SAVE); - - $backupService->backup($executor); - - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::POST_REFERENCE_SAVE); - } - return $executor; } diff --git a/src/Services/DatabaseTools/ORMDatabaseTool.php b/src/Services/DatabaseTools/ORMDatabaseTool.php index 6240be5e..7d351356 100644 --- a/src/Services/DatabaseTools/ORMDatabaseTool.php +++ b/src/Services/DatabaseTools/ORMDatabaseTool.php @@ -23,9 +23,6 @@ use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; use Liip\TestFixturesBundle\Event\FixtureEvent; -use Liip\TestFixturesBundle\Event\PostFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\PreFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\ReferenceSaveEvent; use Liip\TestFixturesBundle\LiipTestFixturesEvents; /** @@ -38,10 +35,7 @@ class ORMDatabaseTool extends AbstractDbalDatabaseTool */ protected $om; - /** - * @var bool - */ - private $shouldEnableForeignKeyChecks = false; + private bool $shouldEnableForeignKeyChecks = false; public function getType(): string { @@ -65,33 +59,6 @@ public function loadFixtures(array $classNames = [], bool $append = false): Abst $this->createDatabaseIfNotExists(); } - $backupService = $this->getBackupService(); - - if ($backupService && $this->databaseCacheEnabled) { - $backupService->init($this->getMetadatas(), $classNames, $append); - - if ($backupService->isBackupActual()) { - if (null !== $this->connection) { - $this->connection->close(); - } - - $this->om->flush(); - $this->om->clear(); - - $event = new PreFixtureBackupRestoreEvent($this->om, $referenceRepository, $backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE); - - $executor = $this->getExecutor($this->getPurger()); - $executor->setReferenceRepository($referenceRepository); - $backupService->restore($executor, $this->excludedDoctrineTables); - - $event = new PostFixtureBackupRestoreEvent($backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE); - - return $executor; - } - } - // TODO: handle case when using persistent connections. Fail loudly? if (false === $this->getKeepDatabaseAndSchemaParameter()) { $schemaTool = new SchemaTool($this->om); @@ -121,15 +88,6 @@ public function loadFixtures(array $classNames = [], bool $append = false): Abst $loader = $this->fixturesLoaderFactory->getFixtureLoader($classNames); $executor->execute($loader->getFixtures(), true); - if ($backupService) { - $event = new ReferenceSaveEvent($this->om, $executor, $backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::PRE_REFERENCE_SAVE); - - $backupService->backup($executor); - - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::POST_REFERENCE_SAVE); - } - return $executor; } diff --git a/src/Services/DatabaseTools/ORMSqliteDatabaseTool.php b/src/Services/DatabaseTools/ORMSqliteDatabaseTool.php index 9cfb2af2..42ab541b 100644 --- a/src/Services/DatabaseTools/ORMSqliteDatabaseTool.php +++ b/src/Services/DatabaseTools/ORMSqliteDatabaseTool.php @@ -19,9 +19,6 @@ use Doctrine\ORM\Configuration; use Doctrine\ORM\Tools\SchemaTool; use Liip\TestFixturesBundle\Event\FixtureEvent; -use Liip\TestFixturesBundle\Event\PostFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\PreFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\ReferenceSaveEvent; use Liip\TestFixturesBundle\LiipTestFixturesEvents; /** @@ -29,10 +26,7 @@ */ class ORMSqliteDatabaseTool extends ORMDatabaseTool { - /** - * @var bool - */ - private $shouldEnableForeignKeyChecks = false; + private bool $shouldEnableForeignKeyChecks = false; public function getDriverName(): string { @@ -52,32 +46,6 @@ public function loadFixtures(array $classNames = [], bool $append = false): Abst $cacheDriver->clear(); } - $backupService = $this->getBackupService(); - if ($backupService && $this->databaseCacheEnabled) { - $backupService->init($this->getMetadatas(), $classNames); - - if ($backupService->isBackupActual()) { - if (null !== $this->connection) { - $this->connection->close(); - } - - $this->om->flush(); - $this->om->clear(); - - $event = new PreFixtureBackupRestoreEvent($this->om, $referenceRepository, $backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE); - - $executor = $this->getExecutor($this->getPurger()); - $executor->setReferenceRepository($referenceRepository); - $backupService->restore($executor); - - $event = new PostFixtureBackupRestoreEvent($backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE); - - return $executor; - } - } - if (false === $append && false === $this->getKeepDatabaseAndSchemaParameter()) { // TODO: handle case when using persistent connections. Fail loudly? $schemaTool = new SchemaTool($this->om); @@ -99,15 +67,6 @@ public function loadFixtures(array $classNames = [], bool $append = false): Abst $loader = $this->fixturesLoaderFactory->getFixtureLoader($classNames); $executor->execute($loader->getFixtures(), true); - if ($backupService) { - $event = new ReferenceSaveEvent($this->om, $executor, $backupService->getBackupFilePath()); - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::PRE_REFERENCE_SAVE); - - $backupService->backup($executor); - - $this->eventDispatcher->dispatch($event, LiipTestFixturesEvents::POST_REFERENCE_SAVE); - } - return $executor; } diff --git a/tests/AppConfigEvents/EventListener/FixturesSubscriber.php b/tests/AppConfigEvents/EventListener/FixturesSubscriber.php index ff784af7..a71bc7db 100644 --- a/tests/AppConfigEvents/EventListener/FixturesSubscriber.php +++ b/tests/AppConfigEvents/EventListener/FixturesSubscriber.php @@ -14,9 +14,6 @@ namespace Liip\Acme\Tests\AppConfigEvents\EventListener; use Liip\TestFixturesBundle\Event\FixtureEvent; -use Liip\TestFixturesBundle\Event\PostFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\PreFixtureBackupRestoreEvent; -use Liip\TestFixturesBundle\Event\ReferenceSaveEvent; use Liip\TestFixturesBundle\LiipTestFixturesEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; @@ -25,51 +22,13 @@ class FixturesSubscriber implements EventSubscriberInterface public static function getSubscribedEvents(): array { return [ - LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE => 'preFixtureBackupRestore', LiipTestFixturesEvents::POST_FIXTURE_SETUP => 'postFixtureSetup', - LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE => 'postFixtureBackupRestore', - LiipTestFixturesEvents::PRE_REFERENCE_SAVE => 'preReferenceSave', - LiipTestFixturesEvents::POST_REFERENCE_SAVE => 'postReferenceSave', ]; } - public function preFixtureBackupRestore(PreFixtureBackupRestoreEvent $preFixtureBackupRestoreEvent): void - { - $manager = $preFixtureBackupRestoreEvent->getManager(); - $repository = $preFixtureBackupRestoreEvent->getRepository(); - $backupFilePath = $preFixtureBackupRestoreEvent->getBackupFilePath(); - - // your code - } - - public function postFixtureSetup(FixtureEvent $fixture): void + public function postFixtureSetup(FixtureEvent $fixtureEvent): void { // There are no parameters // your code } - - public function postFixtureBackupRestore(PostFixtureBackupRestoreEvent $postFixtureBackupRestoreEvent): void - { - $backupFilePath = $postFixtureBackupRestoreEvent->getBackupFilePath(); - - // your code - } - - public function preReferenceSave(ReferenceSaveEvent $referenceSaveEvent): void - { - $manager = $referenceSaveEvent->getManager(); - $executor = $referenceSaveEvent->getExecutor(); - $backupFilePath = $referenceSaveEvent->getBackupFilePath(); - - // your code - } - - public function postReferenceSave(ReferenceSaveEvent $referenceSaveEvent): void - { - $manager = $referenceSaveEvent->getManager(); - $executor = $referenceSaveEvent->getExecutor(); - $backupFilePath = $referenceSaveEvent->getBackupFilePath(); - - // your code - } } diff --git a/tests/AppConfigMysqlCacheDb/AppConfigMysqlKernelCacheDb.php b/tests/AppConfigMysqlCacheDb/AppConfigMysqlKernelCacheDb.php deleted file mode 100644 index 48cb78a8..00000000 --- a/tests/AppConfigMysqlCacheDb/AppConfigMysqlKernelCacheDb.php +++ /dev/null @@ -1,35 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\Acme\Tests\AppConfigMysqlCacheDb; - -use Liip\Acme\Tests\AppConfigMysql\AppConfigMysqlKernel; -use Symfony\Component\Config\Loader\LoaderInterface; -use Symfony\Component\DependencyInjection\ContainerBuilder; - -class AppConfigMysqlKernelCacheDb extends AppConfigMysqlKernel -{ - public function getCacheDir(): string - { - return __DIR__.'/var/cache/'; - } - - protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void - { - // Load the default file. - parent::configureContainer($container, $loader); - - // Load the file with specific configuration - $loader->load(__DIR__.'/config.yml'); - } -} diff --git a/tests/AppConfigMysqlCacheDb/config.yml b/tests/AppConfigMysqlCacheDb/config.yml deleted file mode 100644 index 9922b9d5..00000000 --- a/tests/AppConfigMysqlCacheDb/config.yml +++ /dev/null @@ -1,5 +0,0 @@ -# inherits configuration from ../AppConfigMysql/config.yml - -liip_test_fixtures: - cache_db: - mysql: 'Liip\TestFixturesBundle\Services\DatabaseBackup\MysqlDatabaseBackup' diff --git a/tests/Test/ConfigEventsTest.php b/tests/Test/ConfigEventsTest.php index d4677eb0..80df19df 100644 --- a/tests/Test/ConfigEventsTest.php +++ b/tests/Test/ConfigEventsTest.php @@ -20,7 +20,6 @@ use Liip\TestFixturesBundle\Services\DatabaseToolCollection; use Liip\TestFixturesBundle\Services\DatabaseTools\AbstractDatabaseTool; use Liip\TestFixturesBundle\Services\DatabaseTools\ORMSqliteDatabaseTool; -use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\PreserveGlobalState; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; @@ -64,30 +63,19 @@ public function testLoadEmptyFixturesAndCheckEvents(): void $eventDispatcher = $this->getTestContainer()->get('event_dispatcher'); - $event = $eventDispatcher->getListeners(LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE); - $this->assertSame('preFixtureBackupRestore', $event[0][1]); - $event = $eventDispatcher->getListeners(LiipTestFixturesEvents::POST_FIXTURE_SETUP); $this->assertSame('postFixtureSetup', $event[0][1]); - - $event = $eventDispatcher->getListeners(LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE); - $this->assertSame('postFixtureBackupRestore', $event[0][1]); - - $event = $eventDispatcher->getListeners(LiipTestFixturesEvents::PRE_REFERENCE_SAVE); - $this->assertSame('preReferenceSave', $event[0][1]); - - $event = $eventDispatcher->getListeners(LiipTestFixturesEvents::POST_REFERENCE_SAVE); - $this->assertSame('postReferenceSave', $event[0][1]); } /** - * Check that events are called. - * - * We disable the cache to ensure that all the code is executed. + * Check that the event is called. */ - #[DataProvider('fixturesEventsProvider')] - public function testLoadEmptyFixturesAndCheckEventsAreCalled(string $eventName, string $methodName, int $numberOfInvocations, ?bool $withCache = true): void + public function testLoadEmptyFixturesAndCheckEventsAreCalled(): void { + $eventName = LiipTestFixturesEvents::POST_FIXTURE_SETUP; + $methodName = 'postFixtureSetup'; + $numberOfInvocations = 1; + /** @var AbstractDatabaseTool $databaseTool */ $databaseTool = $this->getTestContainer()->get(DatabaseToolCollection::class)->get(); @@ -108,11 +96,7 @@ public function testLoadEmptyFixturesAndCheckEventsAreCalled(string $eventName, ); // By loading fixtures, the events will be called (or not) - if ($withCache) { - $fixtures = $databaseTool->loadFixtures([]); - } else { - $fixtures = $databaseTool->withDatabaseCacheEnabled(false)->loadFixtures([]); - } + $fixtures = $databaseTool->loadFixtures([]); $this->assertInstanceOf( 'Doctrine\Common\DataFixtures\Executor\ORMExecutor', @@ -120,27 +104,6 @@ public function testLoadEmptyFixturesAndCheckEventsAreCalled(string $eventName, ); } - /** - * We disable the cache to ensure that other events are called. - */ - #[DataProvider('fixturesEventsProvider')] - public function testLoadEmptyFixturesAndCheckEventsAreCalledWithoutCache(string $eventName, string $methodName, int $numberOfInvocations): void - { - // Swap 0 → 1 and 1 → 0 - $numberOfInvocations = (int) (!$numberOfInvocations); - - $this->testLoadEmptyFixturesAndCheckEventsAreCalled($eventName, $methodName, $numberOfInvocations, false); - } - - public static function fixturesEventsProvider(): iterable - { - yield 'preFixtureBackupRestore' => [LiipTestFixturesEvents::PRE_FIXTURE_BACKUP_RESTORE, 'preFixtureBackupRestore', 1]; - yield 'postFixtureSetup' => [LiipTestFixturesEvents::POST_FIXTURE_SETUP, 'postFixtureSetup', 0]; - yield 'postFixtureBackupRestore' => [LiipTestFixturesEvents::POST_FIXTURE_BACKUP_RESTORE, 'postFixtureBackupRestore', 1]; - yield 'preReferenceSave' => [LiipTestFixturesEvents::PRE_REFERENCE_SAVE, 'preReferenceSave', 0]; - yield 'postReferenceSave' => [LiipTestFixturesEvents::POST_REFERENCE_SAVE, 'postReferenceSave', 0]; - } - protected static function getKernelClass(): string { return AppConfigEventsKernel::class; diff --git a/tests/Test/ConfigMysqlCacheDbTest.php b/tests/Test/ConfigMysqlCacheDbTest.php deleted file mode 100644 index fc400350..00000000 --- a/tests/Test/ConfigMysqlCacheDbTest.php +++ /dev/null @@ -1,129 +0,0 @@ - - * - * This source file is subject to the MIT license that is bundled - * with this source code in the file LICENSE. - */ - -namespace Liip\Acme\Tests\Test; - -use Liip\Acme\Tests\App\Entity\User; -use Liip\Acme\Tests\AppConfigMysqlCacheDb\AppConfigMysqlKernelCacheDb; -use PHPUnit\Framework\Attributes\PreserveGlobalState; - -/** - * Test MySQL database with database caching enabled. - * - * The following tests require a connection to a MySQL database, - * they are disabled by default (see phpunit.xml.dist). - * - * In order to run them, you have to set the MySQL connection - * parameters in the Tests/AppConfigMysql/config.yml file. - * - * Use Tests/AppConfigMysql/AppConfigMysqlKernelCacheDb.php instead of - * Tests/App/AppKernel.php. - * So it must be loaded in a separate process. - * - * @internal - */ -#[PreserveGlobalState(false)] -class ConfigMysqlCacheDbTest extends ConfigMysqlTest -{ - public function testLoadFixturesAndCheckBackup(): void - { - $this->assertTrue($this->databaseTool->isDatabaseCacheEnabled()); - - $this->databaseTool->loadFixtures([ - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadUserData', - ]); - - // Load data from database - $users = $this->userRepository->findAll(); - - // Check that all User have been saved to database - $this->assertCount( - 2, - $users - ); - - /** @var User $user1 */ - $user1 = $this->userRepository - ->findOneBy([ - 'id' => 1, - ]) - ; - - $this->assertSame( - 'foo@bar.com', - $user1->getEmail() - ); - - // Store salt for later use - $salt = $user1->getSalt(); - - // Clean database - $this->databaseTool->loadFixtures(); - - $users = $this->userRepository->findAll(); - - // Check that all User have been removed from database - $this->assertCount( - 0, - $users - ); - - // Load fixtures again - $this->databaseTool->loadFixtures([ - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadUserData', - ]); - - $users = $this->userRepository->findAll(); - - // Check that all User have been loaded again in database - $this->assertCount( - 2, - $users - ); - - $user1 = $this->userRepository - ->findOneBy([ - 'id' => 1, - ]) - ; - - // Salt is a random string, if it's the same as before it means that the backup has been saved and loaded - // successfully - $this->assertSame( - $salt, - $user1->getSalt() - ); - } - - public function testLoadFixturesCheckReferences(): void - { - $this->markTestSkipped('This test is broken right now.'); - $referenceRepository = $this->databaseTool->loadFixtures([ - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadUserData', - ])->getReferenceRepository(); - - $this->assertCount(1, $referenceRepository->getReferences()); - - $referenceRepository = $this->databaseTool->loadFixtures([ - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadUserData', - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadSecondUserData', - ])->getReferenceRepository(); - - $this->assertCount(2, $referenceRepository->getReferences()); - } - - protected static function getKernelClass(): string - { - return AppConfigMysqlKernelCacheDb::class; - } -} diff --git a/tests/Test/ConfigMysqlTest.php b/tests/Test/ConfigMysqlTest.php index 7ca5e186..e7747f99 100644 --- a/tests/Test/ConfigMysqlTest.php +++ b/tests/Test/ConfigMysqlTest.php @@ -195,6 +195,8 @@ public function testLoadFixturesAndExcludeFromPurge(): void 2, $this->userRepository->findAll() ); + + $this->databaseTool->setExcludedDoctrineTables([]); } /** diff --git a/tests/Test/ConfigTest.php b/tests/Test/ConfigTest.php index 0bf18ffb..ac2aa60f 100644 --- a/tests/Test/ConfigTest.php +++ b/tests/Test/ConfigTest.php @@ -17,7 +17,6 @@ use Liip\Acme\Tests\App\Entity\User; use Liip\Acme\Tests\AppConfig\AppConfigKernel; use Liip\Acme\Tests\Traits\ContainerProvider; -use Liip\TestFixturesBundle\Services\DatabaseBackup\SqliteDatabaseBackup; use Liip\TestFixturesBundle\Services\DatabaseToolCollection; use Liip\TestFixturesBundle\Services\DatabaseTools\AbstractDatabaseTool; use Liip\TestFixturesBundle\Services\DatabaseTools\ORMSqliteDatabaseTool; @@ -42,8 +41,6 @@ class ConfigTest extends KernelTestCase protected $databaseTool; /** @var ObjectRepository */ private $userRepository; - /** @var SqliteDatabaseBackup */ - private $sqliteDatabaseBackup; protected function setUp(): void { @@ -58,10 +55,6 @@ protected function setUp(): void $this->databaseTool = $this->getTestContainer()->get(DatabaseToolCollection::class)->get(); $this->assertInstanceOf(ORMSqliteDatabaseTool::class, $this->databaseTool); - - $this->sqliteDatabaseBackup = $this->getTestContainer()->get(SqliteDatabaseBackup::class); - - $this->assertInstanceOf(SqliteDatabaseBackup::class, $this->sqliteDatabaseBackup); } /** @@ -106,122 +99,6 @@ public function testLoadFixturesFilesWithCustomProvider(): void ); } - public function testCacheCanBeDisabled(): void - { - $fixtures = [ - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadDependentUserData', - ]; - - $this->databaseTool->setDatabaseCacheEnabled(false); - - $this->databaseTool->loadFixtures($fixtures); - - // Load data from database - /** @var User $user1 */ - $user1 = $this->userRepository->findOneBy(['id' => 1]); - - // Store random data, in order to check it after reloading fixtures. - $user1Salt = $user1->getSalt(); - - sleep(2); - - // Reload the fixtures. - $this->databaseTool->loadFixtures($fixtures); - - /** @var User $user1 */ - $user1 = $this->userRepository->findOneBy(['id' => 1]); - - // The salt are not the same because cache were not used - $this->assertNotSame($user1Salt, $user1->getSalt()); - - // Enable the cache again - $this->databaseTool->setDatabaseCacheEnabled(true); - } - - /** - * Update a fixture file and check that the cache will be refreshed. - */ - public function testBackupIsRefreshed(): void - { - $fixtures = [ - 'Liip\Acme\Tests\App\DataFixtures\ORM\LoadDependentUserData', - ]; - - $this->databaseTool->loadFixtures($fixtures); - - // Load data from database - /** @var User $user1 */ - $user1 = $this->userRepository->findOneBy(['id' => 1]); - - // Store random data, in order to check it after reloading fixtures. - $user1Salt = $user1->getSalt(); - - $dependentFixtureFilePath = static::$kernel->locateResource( - '@AcmeBundle/DataFixtures/ORM/LoadUserData.php' - ); - - $dependentFixtureFilemtime = filemtime($dependentFixtureFilePath); - - // The backup service provide the path of the backup file - $databaseFilePath = $this->sqliteDatabaseBackup->getBackupFilePath(); - - if (!is_file($databaseFilePath)) { - $this->fail($databaseFilePath.' is not a file.'); - } - - $databaseFilemtime = filemtime($databaseFilePath); - - sleep(2); - - // Reload the fixtures. - $this->databaseTool->loadFixtures($fixtures); - - // The mtime of the file has not changed. - $this->assertSame( - $dependentFixtureFilemtime, - filemtime($dependentFixtureFilePath), - 'File modification time of the fixture has been updated.' - ); - - // The backup has not been updated. - $this->assertSame( - $databaseFilemtime, - filemtime($databaseFilePath), - 'File modification time of the backup has been updated.' - ); - - $user1 = $this->userRepository->findOneBy(['id' => 1]); - - // Check that random data has not been changed, to ensure that backup was created and loaded successfully. - $this->assertSame($user1Salt, $user1->getSalt()); - - sleep(2); - - // Update the filemtime of the fixture file used as a dependency. - touch($dependentFixtureFilePath); - - $this->databaseTool->loadFixtures($fixtures); - - // The mtime of the fixture file has been updated. - $this->assertGreaterThan( - $dependentFixtureFilemtime, - filemtime($dependentFixtureFilePath), - 'File modification time of the fixture has not been updated.' - ); - - // The backup has been refreshed: mtime is greater. - $this->assertGreaterThan( - $databaseFilemtime, - filemtime($databaseFilePath), - 'File modification time of the backup has not been updated.' - ); - - $user1 = $this->userRepository->findOneBy(['id' => 1]); - - // Check that random data has been changed, to ensure that backup was not used. - $this->assertNotSame($user1Salt, $user1->getSalt()); - } - protected static function getKernelClass(): string { return AppConfigKernel::class;