diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 078eaae..c6b7fec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,8 +3,7 @@ name: CI on: push: branches: - - 2.next-cake4 - - 3.next-cake5 + - 4.next-cake6 pull_request: branches: @@ -16,25 +15,21 @@ permissions: jobs: testsuite: name: PHP ${{ matrix.php-version }} - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 strategy: fail-fast: false matrix: - # composer.json declares php >=8.1 and cakephp/cakephp ^5.0. - # CakePHP 5.0-5.2 allow PHP 8.1; 5.3+ requires PHP 8.2, so on 8.1 - # composer resolves 5.2.x and on 8.2+ the latest 5.x. Test the whole - # declared range: 8.1 (min) -> 8.5 (newest). - php-version: ['8.1', '8.2', '8.3', '8.4', '8.5'] + # composer.json declares php >=8.5 and cakephp/cakephp ^6.0 (6.x-dev until 6.0.0 is tagged). + php-version: ['8.5'] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} - extensions: mbstring, intl, apcu, sqlite3, pdo_sqlite - ini-values: apc.enable_cli=1 + extensions: mbstring, intl, sqlite3, pdo_sqlite coverage: none - name: Get composer cache directory @@ -42,7 +37,7 @@ jobs: run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT" - name: Cache composer dependencies - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ matrix.php-version }}-${{ hashFiles('composer.json') }} @@ -58,18 +53,18 @@ jobs: - name: Run integration tests run: composer test-integration - cs: - name: Coding Standard - runs-on: ubuntu-24.04 + cs-stan: + name: Coding Standard & Static Analysis + runs-on: ubuntu-26.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: '8.2' - extensions: mbstring, intl, apcu + php-version: '8.5' + extensions: mbstring, intl, sqlite3, pdo_sqlite coverage: none - name: Install dependencies @@ -78,7 +73,5 @@ jobs: - name: Run PHP CodeSniffer run: composer cs-check - # NOTE: phpstan/psalm are pinned to 1.10.14 / 5.10.0 in .phive/phars.xml; - # those versions do not run on PHP 8.2+ (fatal in better-reflection) and - # report pre-existing findings. Modernize the pins in a separate change - # before wiring them back into CI as a blocking step. + - name: Run PHPStan + run: composer stan -- --no-progress diff --git a/.phive/phars.xml b/.phive/phars.xml deleted file mode 100644 index a8aff29..0000000 --- a/.phive/phars.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ccaf3b..ab1dab1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,23 @@ Changelog ========= +Releases for CakePHP 6.0 +------------------------ +* 4.0.0 (unreleased, tracks `cakephp/cakephp` `6.x-dev` until 6.0.0 is tagged; verified against core commit `421c644`, PHPUnit 13.4.6, PHP 8.5.12) + * **Breaking (requirements)** — PHP 8.5+, CakePHP 6.0 (`^6.0`, resolves `6.x-dev`: applications need `minimum-stability: dev` and `prefer-stable: true`), PHPUnit 13. + * **Breaking (API)** — the protected members of `BaseEngine`, `MysqlEngine`, `PostgresEngine`, `ExecuteTrait` and `FixtureManager` lost their underscore prefix, following CakePHP 6 and the `cakephp/cakephp-codesniffer` 6 standard: `_execute()` -> `execute()`, `_getBaseArguments()` -> `getBaseArguments()`, `_setPassword()` -> `setPassword()`, `__importTestSkeleton()` -> `importTestSkeleton()`, `_ensureFolder()` -> `ensureFolder()`, `$_verbose` -> `$verbose`, `$_database` -> `$database`. Subclasses must rename their overrides. + * **Breaking (API)** — `BaseEngine::isSuccess()` accepts `?int` (a `null` exit status is a failure). + * Fix: the `verbose` extension parameter is optional and parsed as a boolean string (`"false"` used to enable verbose logging, a missing parameter threw `ParameterDoesNotExistException`); `PHPUnitExtension::isVerbose()` is public + * Fix: engines build the CLI arguments from the keys the datasource defines (`host`, `port`, `username`, `password`) instead of raising `Undefined array key`; `PGPASSWORD` is only exported when a password is configured; a datasource without `database` throws `InvalidArgumentException` at engine construction + * Fix: `db_test` help text names `config/sql`; docs: verbose mode and plugin loading examples updated + * Fix: `fixture_import` reports a missing `test_template` datasource with its error message instead of an uncaught `MissingDatasourceConfigException` + * Fix: the MySQL password is shell-escaped (`escapeshellarg()`); a password containing a quote no longer breaks the command + * `DbTestCommand` and `FixtureImportCommand` follow the CakePHP 6 command shape: parameterless `execute()` reading `$this->args` and `$this->io`. + * Note — name `host`, `username`, `password` and `database` on the `test` and `test_template` connections (and `schema` on PostgreSQL when `createSchema()` should run): the engines read the raw datasource array (`Connection::config()`), the driver defaults (`localhost`, the default port, `public`) are never applied to it. + * Chore: `phpunit.xml.dbtest` migrated to the PHPUnit 13 schema (the `apc.enable_cli` ini line is gone: it is `PHP_INI_SYSTEM` and PHPUnit 12.5+ warns on it). + * Chore: the plugin's own suites fail on deprecations, notices and warnings; PHPStan 2 level 8 over `src/` and `tests/` without a baseline (only `missingType.iterableValue` is ignored by identifier) replaces the phive-installed PHPStan 1.10 and Psalm 5.10; `composer stan` runs it, `composer check` runs cs-check, stan and the unit suite. + * CI: PHP 8.5, coding standard and PHPStan job, `4.next-cake6` branch. + Releases for CakePHP 5.0 ------------------------ * 3.1.0 diff --git a/Docs/Documentation/Installation.md b/Docs/Documentation/Installation.md index 85a79c1..773b711 100644 --- a/Docs/Documentation/Installation.md +++ b/Docs/Documentation/Installation.md @@ -8,14 +8,17 @@ Composer composer require cakedc/cakephp-db-test ``` +Until CakePHP 6.0.0 is tagged the plugin resolves against `cakephp/cakephp` `6.x-dev`, so the application's +`composer.json` needs `"minimum-stability": "dev"` and `"prefer-stable": true`. + Load the plugin --------------- ``` bin/cake plugin load CakeDC/DbTest ``` -Note you'll need this plugin loaded in the `cli` section of your `Application::bootstrap`, around the line loading -Bake Plugin: `$this->addPlugin('DbTestPlugin');` +Or load it from `Application::bootstrap()` next to the other CLI-only plugins (Bake, Migrations): +`$this->addPlugin('CakeDC/DbTest');` Configuration ------------- @@ -43,9 +46,15 @@ Add the next configuration setting into app.php // ... ``` +Name `host`, `username`, `password` and `database` explicitly on both the `test` and the `test_template` +connections: the plugin reads the raw datasource array (`Connection::config()`), the driver defaults are never +applied to it, and the values go to `mysql`/`mysqladmin`/`mysqldump` or `psql`/`pg_dump`/`pg_restore` on the +command line. On PostgreSQL also name `schema` when the test database needs a `CREATE SCHEMA` after it is +recreated; without the key no schema is created. + PHPUnit ------- -Copy https://github.com/CakeDC/cakephp-db-test/blob/master/phpunit.xml.dbtest as phpunit.xml.dist in your +Copy https://github.com/CakeDC/cakephp-db-test/blob/4.next-cake6/phpunit.xml.dbtest as phpunit.xml.dist in your project (modify if needed) Fixture database diff --git a/Docs/Documentation/Workflow.md b/Docs/Documentation/Workflow.md index 7c8eb7c..4ff90e4 100644 --- a/Docs/Documentation/Workflow.md +++ b/Docs/Documentation/Workflow.md @@ -25,5 +25,13 @@ Copy phpunit.xml.dbtest as phpunit.xml.dist in your project (modify if needed) a Debug Test Suite ------------------- -Verbose mode enabled by second parameter of FixtureInjector set to true. -It is defined in phpunit.xml.dist in arguments section of FixtureInjector listener. +Verbose mode logs every shell command the engines run and its output (`Log::info()`). Enable it with the `verbose` +parameter of the extension in `phpunit.xml.dist` (`"true"`, `"1"`, `"on"` or `"yes"`; omitted or `"false"` is off): + +```xml + + + + + +``` diff --git a/Docs/Home.md b/Docs/Home.md index 2cbb45b..c00b8ad 100644 --- a/Docs/Home.md +++ b/Docs/Home.md @@ -6,11 +6,11 @@ The **DbTest** plugin enables developers to speeding up tests running on MySQL o Requirements ------------ -* CakePHP 5.0+ -* PHP 8.1+ +* CakePHP 6.0 (6.x-dev until 6.0.0 is tagged; `minimum-stability: dev` and `prefer-stable: true` in the application `composer.json`) +* PHP 8.5+ * MySQL database with InnoDb engine * PostgreSQL database -* Phpunit 10.* +* PHPUnit 13.* Documentation ------------- diff --git a/composer.json b/composer.json index 1498c20..6f06289 100644 --- a/composer.json +++ b/composer.json @@ -4,12 +4,13 @@ "type": "cakephp-plugin", "license": "MIT", "require": { - "php": ">=8.1", - "cakephp/cakephp": "^5.0" + "php": ">=8.5", + "cakephp/cakephp": "^6.0" }, "require-dev": { - "phpunit/phpunit": "^10.0", - "cakephp/cakephp-codesniffer": "^4.0", + "phpunit/phpunit": "^13.0", + "cakephp/cakephp-codesniffer": "6.x-dev", + "phpstan/phpstan": "^2.1", "ext-mbstring": "*" }, "autoload": { @@ -26,20 +27,12 @@ "scripts": { "check": [ "@cs-check", + "@stan", "@test" ], "cs-check": "phpcs --colors --parallel=16 -p src/ tests/", "cs-fix": "phpcbf --colors --parallel=16 -p src/ tests/", - "phpstan": "tools/phpstan analyse", - "psalm": "tools/psalm --show-info=false", - "stan": [ - "@phpstan", - "@psalm" - ], - "phpstan-tests": "tools/phpstan analyze -c tests/phpstan.neon", - "phpstan-baseline": "tools/phpstan --generate-baseline", - "psalm-baseline": "tools/psalm --set-baseline=psalm-baseline.xml", - "stan-setup": "phive install", + "stan": "phpstan analyse", "test": "phpunit", "test-integration": "phpunit -c phpunit.integration.xml" }, @@ -47,5 +40,7 @@ "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } - } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/phpcs.xml b/phpcs.xml index 1852cfd..97ebe88 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,6 +1,4 @@ - - diff --git a/phpstan.neon b/phpstan.neon index bedc53a..7e931f2 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,8 +1,10 @@ parameters: - level: 8 - treatPhpDocTypesAsCertain: false - checkGenericClassInNonGenericObjectType: false - bootstrapFiles: - - tests/bootstrap.php - paths: - - src/ + level: 8 + treatPhpDocTypesAsCertain: false + bootstrapFiles: + - tests/bootstrap.php + paths: + - src/ + - tests/ + ignoreErrors: + - identifier: missingType.iterableValue diff --git a/phpunit.integration.xml b/phpunit.integration.xml index fb38578..75707b1 100644 --- a/phpunit.integration.xml +++ b/phpunit.integration.xml @@ -1,23 +1,34 @@ + failOnDeprecation="true" + failOnPhpunitDeprecation="true" + failOnNotice="true" + failOnPhpunitNotice="true" + failOnWarning="true" + failOnRisky="true" + displayDetailsOnTestsThatTriggerDeprecations="true" + displayDetailsOnPhpunitDeprecations="true" + displayDetailsOnTestsThatTriggerNotices="true" + displayDetailsOnPhpunitNotices="true" + displayDetailsOnTestsThatTriggerWarnings="true" + displayDetailsOnTestsThatTriggerErrors="true"> - - + @@ -30,9 +41,17 @@ - + + src/ + + Cake\Core\deprecationWarning + deprecationWarning + diff --git a/phpunit.xml.dbtest b/phpunit.xml.dbtest index 10b4abd..ba869de 100644 --- a/phpunit.xml.dbtest +++ b/phpunit.xml.dbtest @@ -1,14 +1,13 @@ + cacheDirectory=".phpunit.cache"> - - + @@ -22,8 +21,8 @@ - - + + @@ -33,8 +32,5 @@ src/ plugins/*/src/ - - src/Console/Installer.php - diff --git a/phpunit.xml.dist b/phpunit.xml.dist index bd68de9..7dc6fa0 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,23 +1,34 @@ + failOnDeprecation="true" + failOnPhpunitDeprecation="true" + failOnNotice="true" + failOnPhpunitNotice="true" + failOnWarning="true" + failOnRisky="true" + displayDetailsOnTestsThatTriggerDeprecations="true" + displayDetailsOnPhpunitDeprecations="true" + displayDetailsOnTestsThatTriggerNotices="true" + displayDetailsOnPhpunitNotices="true" + displayDetailsOnTestsThatTriggerWarnings="true" + displayDetailsOnTestsThatTriggerErrors="true"> - - + @@ -26,9 +37,17 @@ - + + src/ + + Cake\Core\deprecationWarning + deprecationWarning + diff --git a/psalm.xml b/psalm.xml deleted file mode 100644 index 99db5dd..0000000 --- a/psalm.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/readme.md b/readme.md index ef6242f..ce35c13 100644 --- a/readme.md +++ b/readme.md @@ -10,11 +10,11 @@ The **DbTest** plugin enables developers to speeding up tests running on MySQL o Requirements ------------ -* CakePHP 5.0+ -* PHP 8.1+ +* CakePHP 6.0 (6.x-dev until 6.0.0 is tagged; `minimum-stability: dev` and `prefer-stable: true` in the application `composer.json`) +* PHP 8.5+ * MySQL database with InnoDb engine * PostgreSQL database -* Phpunit 10.* +* PHPUnit 13.* Documentation ------------- @@ -36,6 +36,6 @@ If you'd like to contribute new features, enhancements or bug fixes to the plugi License ------- -Copyright 2013-2023 Cake Development Corporation (CakeDC). All rights reserved. +Copyright 2013-2026 Cake Development Corporation (CakeDC). All rights reserved. Licensed under the [MIT](http://www.opensource.org/licenses/mit-license.php) License. Redistributions of the source code included in this repository must retain the copyright notice found in each file. diff --git a/src/Command/DbTestCommand.php b/src/Command/DbTestCommand.php index 304cacd..a341455 100644 --- a/src/Command/DbTestCommand.php +++ b/src/Command/DbTestCommand.php @@ -13,8 +13,6 @@ namespace CakeDC\DbTest\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; use Cake\Datasource\ConnectionManager; @@ -46,7 +44,7 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar 'boolean' => true, 'short' => 'i', 'help' => __d('cake_d_c/db_test', 'Drops test template database and imports ' . - 'test_db.sql file from app/Config/sql'), + 'test_db.sql file from config/sql'), ]) ->addOption('import-database-file', [ 'short' => 'f', @@ -57,26 +55,24 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * @inheritDoc */ - public function execute(Arguments $args, ConsoleIo $io) + public function execute(): int { Configure::load('app', 'default', false); - $io->out(__d('cake_d_c/db_test', 'Db Test Shell')); - $io->hr(); + $this->io->out(__d('cake_d_c/db_test', 'Db Test Shell')); + $this->io->hr(); - if ($args->getOption('import-database-template')) { + if ($this->args->getOption('import-database-template')) { $path = null; - if ( - !empty($args->getOption('import-database-file')) && - file_exists($args->getOption('import-database-file')) - ) { - $path = $args->getOption('import-database-file'); + $file = $this->args->getOption('import-database-file'); + if (is_string($file) && $file !== '' && file_exists($file)) { + $path = $file; } $skeletonDatabase = ConnectionManager::get('test_template')->config(); $manager = new FixtureManager(); $manager->setupDatabase($skeletonDatabase, true, true, $path); } else { - $io->out($this->getOptionParser()->help()); + $this->io->out($this->getOptionParser()->help()); } return self::CODE_SUCCESS; diff --git a/src/Command/FixtureImportCommand.php b/src/Command/FixtureImportCommand.php index f52767a..4c7b2c2 100644 --- a/src/Command/FixtureImportCommand.php +++ b/src/Command/FixtureImportCommand.php @@ -13,10 +13,9 @@ namespace CakeDC\DbTest\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Datasource\ConnectionManager; +use Cake\Datasource\Exception\MissingDatasourceConfigException; use CakeDC\DbTest\Engine\EngineFactory; use function Cake\I18n\__d; @@ -36,8 +35,8 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar ->setDescription( __d( 'cake_d_c/db_test', - 'DbTest fixture importer, dumps the template database' - ) + 'DbTest fixture importer, dumps the template database', + ), ) ->addOption('dump-folder', [ 'short' => 'd', @@ -48,31 +47,36 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * @inheritDoc */ - public function execute(Arguments $args, ConsoleIo $io) + public function execute(): int { - $skeletonDatabase = ConnectionManager::get('test_template')->config(); - - if (empty($skeletonDatabase)) { - $io->error( - __d('cake_d_c/db_test', 'Missing `test_template` datasource configuration') + try { + $skeletonDatabase = ConnectionManager::get('test_template')->config(); + } catch (MissingDatasourceConfigException) { + $this->io->error( + __d('cake_d_c/db_test', 'Missing `test_template` datasource configuration'), ); return self::CODE_ERROR; } + $engine = EngineFactory::engine($skeletonDatabase); $skeletonName = $skeletonDatabase['database']; - $dumpFolder = $args->getOption('dump-folder') ?? CONFIG . DS . 'sql'; + $dumpFolder = $this->args->getOption('dump-folder'); + if (!is_string($dumpFolder) || $dumpFolder === '') { + $dumpFolder = CONFIG . 'sql'; + } if (!is_dir($dumpFolder)) { mkdir( directory: $dumpFolder, permissions: 0755, - recursive: true + recursive: true, ); } $dumpFile = $dumpFolder . DS . 'test_db.sql'; - $io->out(__d('cake_d_c/db_test', "Exporting data from skeleton database: $skeletonName \n")); - $engine = EngineFactory::engine($skeletonDatabase); + $this->io->out(__d('cake_d_c/db_test', "Exporting data from skeleton database: $skeletonName \n")); $engine->export($dumpFile, ['format' => 'plain']); + + return self::CODE_SUCCESS; } } diff --git a/src/Engine/BaseEngine.php b/src/Engine/BaseEngine.php index 404456a..71980d4 100644 --- a/src/Engine/BaseEngine.php +++ b/src/Engine/BaseEngine.php @@ -13,6 +13,8 @@ namespace CakeDC\DbTest\Engine; use CakeDC\DbTest\Engine\Traits\ExecuteTrait; +use InvalidArgumentException; +use function Cake\I18n\__d; abstract class BaseEngine implements EngineInterface { @@ -23,14 +25,14 @@ abstract class BaseEngine implements EngineInterface * * @var bool */ - protected bool $_verbose = false; + protected bool $verbose = false; /** * Database configuration * * @var array */ - protected array $_database = []; + protected array $database = []; /** * Constructor method @@ -40,24 +42,29 @@ abstract class BaseEngine implements EngineInterface */ public function __construct(array $database, bool $verbose = false) { - $this->_database = $database; - $this->_verbose = $verbose; + if (empty($database['database']) || !is_string($database['database'])) { + throw new InvalidArgumentException( + __d('cake_d_c/db_test', 'The datasource configuration must name a `database`'), + ); + } + $this->database = $database; + $this->verbose = $verbose; } /** * Check if success. * - * @param int $check Check value + * @param int|null $check Exit status of the executed command, null when unknown * @return bool */ - public function isSuccess(int $check): bool + public function isSuccess(?int $check): bool { $allowed = [ 0 => true, 1 => true, ]; - return isset($allowed[$check]); + return $check !== null && isset($allowed[$check]); } /** diff --git a/src/Engine/EngineFactory.php b/src/Engine/EngineFactory.php index e78f5e6..d5338b8 100644 --- a/src/Engine/EngineFactory.php +++ b/src/Engine/EngineFactory.php @@ -38,7 +38,7 @@ public static function engine(array $database, bool $verbose = false): EngineInt * Translate a cake engine into a DbTest engine * * @param string $driver Driver name - * @return string + * @return class-string<\CakeDC\DbTest\Engine\EngineInterface> */ protected static function getEngineClass(string $driver): string { @@ -50,14 +50,14 @@ protected static function getEngineClass(string $driver): string $type = str_replace('Cake\\Database\\Driver\\', '', $driver); if (!in_array($type, array_keys($engineMap))) { throw new NotFoundException( - __d('cake_d_c/db_test', 'Database engine {0} is not supported', $type) + __d('cake_d_c/db_test', 'Database engine {0} is not supported', $type), ); } $engineClass = $engineMap[$type]; if (!class_exists($engineClass)) { throw new NotFoundException( - __d('cake_d_c/db_test', 'Can\'t load engine ' . $engineClass) + __d('cake_d_c/db_test', 'Can\'t load engine ' . $engineClass), ); } diff --git a/src/Engine/MysqlEngine.php b/src/Engine/MysqlEngine.php index f0c9a9d..4eeeeaf 100644 --- a/src/Engine/MysqlEngine.php +++ b/src/Engine/MysqlEngine.php @@ -23,15 +23,15 @@ class MysqlEngine extends BaseEngine */ public function recreateTestDatabase(): bool { - $databaseName = $this->_database['database']; - $baseArgs = $this->_getBaseArguments(); + $databaseName = $this->database['database']; + $baseArgs = $this->getBaseArguments(); $output = []; $success = 0; Log::info(__d('cake_d_c/db_test', "Dropping database: $databaseName \n")); - $this->_execute("mysqladmin -f $baseArgs drop $databaseName", $output, $success); + $this->execute("mysqladmin -f $baseArgs drop $databaseName", $output, $success); if ($this->isSuccess($success)) { Log::info(__d('cake_d_c/db_test', "Creating database: $databaseName \n")); - $this->_execute("mysqladmin -f $baseArgs create $databaseName", $output, $success); + $this->execute("mysqladmin -f $baseArgs create $databaseName", $output, $success); } return $success === 0; @@ -42,11 +42,11 @@ public function recreateTestDatabase(): bool */ public function import(string $file, array $options = []): bool { - $databaseName = $this->_database['database']; - $baseArgs = $this->_getBaseArguments(); + $databaseName = $this->database['database']; + $baseArgs = $this->getBaseArguments(); $command = "mysql $baseArgs $databaseName < $file"; - return $this->_execute($command, $output); + return $this->execute($command, $output); } /** @@ -54,8 +54,8 @@ public function import(string $file, array $options = []): bool */ public function export(string $file, array $options = []): bool { - $databaseName = $this->_database['database']; - $baseArgs = $this->_getBaseArguments(); + $databaseName = $this->database['database']; + $baseArgs = $this->getBaseArguments(); $command = 'mysqldump'; if (Configure::read('DbTest.dumpExtendedInserts') !== true) { $command .= ' --extended-insert=FALSE'; @@ -68,7 +68,7 @@ public function export(string $file, array $options = []): bool $command .= " > $file"; } - return $this->_execute($command, $output); + return $this->execute($command, $output); } /** @@ -76,17 +76,22 @@ public function export(string $file, array $options = []): bool * * @return string */ - protected function _getBaseArguments(): string + protected function getBaseArguments(): string { - $user = $this->_database['username']; - $password = $this->_database['password']; - $host = $this->_database['host']; - $port = ''; - if (!empty($this->_database['port'])) { - $port = ' --port=' . $this->_database['port']; + $args = []; + if (!empty($this->database['host'])) { + $args[] = '--host=' . $this->database['host']; + } + if (!empty($this->database['port'])) { + $args[] = '--port=' . $this->database['port']; + } + if (!empty($this->database['username'])) { + $args[] = '--user=' . $this->database['username']; + } + if (isset($this->database['password'])) { + $args[] = '--password=' . escapeshellarg((string)$this->database['password']); } - $quote = DS === '/' ? "'" : '"'; - return "--host=$host $port --user=$user --password=$quote$password$quote"; + return implode(' ', $args); } } diff --git a/src/Engine/PostgresEngine.php b/src/Engine/PostgresEngine.php index 6e16467..6b0a752 100644 --- a/src/Engine/PostgresEngine.php +++ b/src/Engine/PostgresEngine.php @@ -22,22 +22,22 @@ class PostgresEngine extends BaseEngine */ public function recreateTestDatabase(): bool { - $baseArgs = $this->_getBaseArguments(); - $this->_setPassword(); - $databaseName = $this->_database['database']; + $baseArgs = $this->getBaseArguments(); + $this->setPassword(); + $databaseName = $this->database['database']; $systemUser = 'postgres'; $terminateQuery = 'select pg_terminate_backend(pg_stat_activity.pid) from pg_stat_activity ' . "where pg_stat_activity.datname = '$databaseName'"; - $this->_execute("psql $baseArgs -c \"$terminateQuery\" $systemUser", $output, $success); + $this->execute("psql $baseArgs -c \"$terminateQuery\" $systemUser", $output, $success); $output = []; $success = 0; Log::info(__d('cake_d_c/db_test', "Dropping database: $databaseName \n")); - $this->_execute("dropdb $baseArgs $databaseName", $output, $success); + $this->execute("dropdb $baseArgs $databaseName", $output, $success); if ($this->isSuccess($success)) { Log::info(__d('cake_d_c/db_test', "Creating database: $databaseName \n")); - $this->_execute("createdb $baseArgs $databaseName", $output, $success); + $this->execute("createdb $baseArgs $databaseName", $output, $success); } return $this->isSuccess($success); @@ -48,16 +48,16 @@ public function recreateTestDatabase(): bool */ public function createSchema(): bool { - $baseArgs = $this->_getBaseArguments(); - $this->_setPassword(); + $baseArgs = $this->getBaseArguments(); + $this->setPassword(); $success = 0; - $testDbName = $this->_database['database']; - if (!empty($this->_database['schema'])) { - $schema = $this->_database['schema']; + $testDbName = $this->database['database']; + if (!empty($this->database['schema'])) { + $schema = $this->database['schema']; } if (!empty($schema)) { - $this->_execute("psql $baseArgs -c \"create schema $schema;\" $testDbName", $output, $success); + $this->execute("psql $baseArgs -c \"create schema $schema;\" $testDbName", $output, $success); } return $this->isSuccess($success); @@ -68,9 +68,9 @@ public function createSchema(): bool */ public function import(string $file, array $options = []): bool { - $baseArgs = $this->_getBaseArguments(); - $testDbName = $this->_database['database']; - $this->_setPassword(); + $baseArgs = $this->getBaseArguments(); + $testDbName = $this->database['database']; + $this->setPassword(); if (isset($options['format']) && $options['format'] == 'plain') { $command = "psql $baseArgs $testDbName < $file"; @@ -78,7 +78,7 @@ public function import(string $file, array $options = []): bool $command = "pg_restore $baseArgs -j 8 -Fc -d $testDbName $file"; } - return $this->_execute($command, $output); + return $this->execute($command, $output); } /** @@ -86,9 +86,9 @@ public function import(string $file, array $options = []): bool */ public function export(string $file, array $options = []): bool { - $baseArgs = $this->_getBaseArguments(); - $this->_setPassword(); - $testDbName = $this->_database['database']; + $baseArgs = $this->getBaseArguments(); + $this->setPassword(); + $testDbName = $this->database['database']; $format = ' -Fc '; if (isset($options['format']) && $options['format'] == 'plain') { $format = ' -Fp '; @@ -96,7 +96,7 @@ public function export(string $file, array $options = []): bool $command = "pg_dump $baseArgs --compress=0 --file=$file $format $testDbName"; - return $this->_execute($command, $output); + return $this->execute($command, $output); } /** @@ -104,16 +104,20 @@ public function export(string $file, array $options = []): bool * * @return string */ - protected function _getBaseArguments(): string + protected function getBaseArguments(): string { - $user = $this->_database['username']; - $host = $this->_database['host']; - $port = ''; - if (!empty($this->_database['port'])) { - $port = ' --port=' . $this->_database['port']; + $args = []; + if (!empty($this->database['host'])) { + $args[] = '--host=' . $this->database['host']; + } + if (!empty($this->database['port'])) { + $args[] = '--port=' . $this->database['port']; + } + if (!empty($this->database['username'])) { + $args[] = '--username=' . $this->database['username']; } - return "--host=$host $port --username=$user"; + return implode(' ', $args); } /** @@ -121,9 +125,11 @@ protected function _getBaseArguments(): string * * @return void */ - protected function _setPassword(): void + protected function setPassword(): void { - $password = $this->_database['password']; - putenv("PGPASSWORD=$password"); + if (!isset($this->database['password'])) { + return; + } + putenv('PGPASSWORD=' . $this->database['password']); } } diff --git a/src/Engine/Traits/ExecuteTrait.php b/src/Engine/Traits/ExecuteTrait.php index a57181c..9572992 100644 --- a/src/Engine/Traits/ExecuteTrait.php +++ b/src/Engine/Traits/ExecuteTrait.php @@ -28,16 +28,16 @@ trait ExecuteTrait * @param int|null $return_var Return status of the executed command * @return bool The last line from the result of the command */ - protected function _execute( + protected function execute( string $command, ?array &$output = null, - ?int &$return_var = null + ?int &$return_var = null, ): bool { - if ($this->_verbose) { + if ($this->verbose) { Log::info(__d('cake_d_c/db_test', $command . "\n")); } $result = exec($command, $output, $return_var); - if ($this->_verbose) { + if ($this->verbose) { Log::info(__d('cake_d_c/db_test', implode("\n", $output) . "\n")); } diff --git a/src/TestSuite/Fixture/Extension/PHPUnitExtension.php b/src/TestSuite/Fixture/Extension/PHPUnitExtension.php index bc03bc1..e56472d 100644 --- a/src/TestSuite/Fixture/Extension/PHPUnitExtension.php +++ b/src/TestSuite/Fixture/Extension/PHPUnitExtension.php @@ -32,15 +32,32 @@ class PHPUnitExtension implements Extension public function bootstrap(Configuration $configuration, Facade $facade, ParameterCollection $parameters): void { $fixtureManager = new FixtureManager(); - $verbose = (bool)$parameters->get('verbose'); - $fixtureManager->setVerbose($verbose); + $fixtureManager->setVerbose($this->isVerbose($parameters)); $facade->registerSubscribers( new PHPUnitStartedSubscriber($fixtureManager), new PHPUnitPreparationStartedSubscriber(), new PHPUnitAfterTestMethodFinishedSubscriber(), new PHPUnitTestFinishedSubscriber(), - new PHPUnitTestRunnerFinishedSubscriber() + new PHPUnitTestRunnerFinishedSubscriber(), ); } + + /** + * Reads the `verbose` extension parameter. + * + * The parameter is optional (`ParameterCollection::get()` throws on a missing name) and arrives as a string, + * so `"false"`, `"0"`, `"off"` and `"no"` are false; `"true"`, `"1"`, `"on"` and `"yes"` are true. + * + * @param \PHPUnit\Runner\Extension\ParameterCollection $parameters Parameters + * @return bool + */ + public function isVerbose(ParameterCollection $parameters): bool + { + if (!$parameters->has('verbose')) { + return false; + } + + return filter_var($parameters->get('verbose'), FILTER_VALIDATE_BOOLEAN); + } } diff --git a/src/TestSuite/Fixture/Extension/PHPUnitStartedSubscriber.php b/src/TestSuite/Fixture/Extension/PHPUnitStartedSubscriber.php index 534580f..1223c84 100644 --- a/src/TestSuite/Fixture/Extension/PHPUnitStartedSubscriber.php +++ b/src/TestSuite/Fixture/Extension/PHPUnitStartedSubscriber.php @@ -27,11 +27,11 @@ class PHPUnitStartedSubscriber implements StartedSubscriber use TestConnectionTrait; /** - * @var true + * @var bool */ protected bool $databaseLoaded = false; /** - * @var true + * @var bool */ protected bool $initialized = false; @@ -41,7 +41,7 @@ class PHPUnitStartedSubscriber implements StartedSubscriber */ public function __construct( private readonly FixtureManager $fixtureManager, - private readonly TransactionGuard $guard = new TransactionGuard() + private readonly TransactionGuard $guard = new TransactionGuard(), ) { } diff --git a/src/TestSuite/Fixture/FixtureManager.php b/src/TestSuite/Fixture/FixtureManager.php index b0d2fb2..08de317 100644 --- a/src/TestSuite/Fixture/FixtureManager.php +++ b/src/TestSuite/Fixture/FixtureManager.php @@ -24,7 +24,7 @@ class FixtureManager * * @var bool */ - protected bool $_verbose = false; + protected bool $verbose = false; /** * Drops existing connections to test database, recreates db, @@ -40,16 +40,16 @@ public function setupDatabase( array $database, bool $createSchema, bool $importTestSkeleton = false, - ?string $sqlFilePath = null + ?string $sqlFilePath = null, ): bool { - $engine = EngineFactory::engine($database, $this->_verbose); + $engine = EngineFactory::engine($database, $this->verbose); $success = $engine->recreateTestDatabase(); if ($success && $createSchema) { $success = $engine->createSchema(); } if ($success && $importTestSkeleton) { - $this->__importTestSkeleton($database, $sqlFilePath); + $this->importTestSkeleton($database, $sqlFilePath); } return $success; @@ -67,23 +67,23 @@ public function setupDatabase( */ public function transferData(array $database): void { + $engine = EngineFactory::engine($database, $this->verbose); $testDbName = $database['database']; $skeletonDatabase = ConnectionManager::get('test_template')->config(); if (!empty($skeletonDatabase)) { + $skeletonEngine = EngineFactory::engine($skeletonDatabase, $this->verbose); $skeletonName = $skeletonDatabase['database']; $cacheFolder = CACHE . 'fixtures'; - $this->_ensureFolder($cacheFolder); + $this->ensureFolder($cacheFolder); $tmpFile = $cacheFolder . DS . 'db_dump_backup.custom'; if (!file_exists($tmpFile)) { Log::info(__d('cake_d_c/db_test', "Backing up data from skeleton database: $skeletonName \n")); - $engine = EngineFactory::engine($skeletonDatabase, $this->_verbose); - $engine->export($tmpFile); + $skeletonEngine->export($tmpFile); } Log::info(__d('cake_d_c/db_test', "Restoring data to: $testDbName \n")); - $engine = EngineFactory::engine($database, $this->_verbose); $engine->import($tmpFile); } } @@ -95,11 +95,12 @@ public function transferData(array $database): void * @param string|null $sqlFilePath Path to the sql script to import * @return void */ - private function __importTestSkeleton(array $database, ?string $sqlFilePath = null): void + private function importTestSkeleton(array $database, ?string $sqlFilePath = null): void { + $engine = EngineFactory::engine($database, $this->verbose); $testDbName = $database['database']; $cacheFolder = CACHE . 'fixtures'; - $this->_ensureFolder($cacheFolder); + $this->ensureFolder($cacheFolder); $tmpFile = $cacheFolder . DS . 'db_dump_backup.custom'; Log::info(__d('cake_d_c/db_test', "Deleting cached file: $tmpFile \n")); if (is_file($tmpFile)) { @@ -112,7 +113,6 @@ private function __importTestSkeleton(array $database, ?string $sqlFilePath = nu $testSkeletonFile = $sqlFilePath; } - $engine = EngineFactory::engine($database, $this->_verbose); Log::info(__d('cake_d_c/db_test', "Importing test skeleton from: $testSkeletonFile \n")); $engine->import($testSkeletonFile, ['format' => 'plain']); Log::info(__d('cake_d_c/db_test', "Backing up data from skeleton database: $testDbName \n\n")); @@ -127,7 +127,7 @@ private function __importTestSkeleton(array $database, ?string $sqlFilePath = nu */ public function setVerbose(bool $verbose): void { - $this->_verbose = $verbose; + $this->verbose = $verbose; } /** @@ -136,13 +136,13 @@ public function setVerbose(bool $verbose): void * @param string $path Path to folder * @return void */ - protected function _ensureFolder(string $path): void + protected function ensureFolder(string $path): void { if (!is_dir($path)) { mkdir( directory: $path, permissions: 0755, - recursive: true + recursive: true, ); } } diff --git a/tests/TestCase/Command/DbTestCommandTest.php b/tests/TestCase/Command/DbTestCommandTest.php new file mode 100644 index 0000000..4d0532a --- /dev/null +++ b/tests/TestCase/Command/DbTestCommandTest.php @@ -0,0 +1,45 @@ +run([], $io); + + $this->assertSame(DbTestCommand::CODE_SUCCESS, $code); + $output = implode("\n", $out->messages()); + $this->assertStringContainsString('Db Test Shell', $output); + $this->assertStringContainsString('--import-database-template', $output); + $this->assertStringContainsString('--import-database-file', $output); + $this->assertStringContainsString('config/sql', $output); + $this->assertStringNotContainsString('app/Config', $output); + } +} diff --git a/tests/TestCase/Command/FixtureImportCommandTest.php b/tests/TestCase/Command/FixtureImportCommandTest.php new file mode 100644 index 0000000..05c72e5 --- /dev/null +++ b/tests/TestCase/Command/FixtureImportCommandTest.php @@ -0,0 +1,63 @@ +assertNotContains('test_template', ConnectionManager::configured()); + $out = new StubConsoleOutput(); + $err = new StubConsoleOutput(); + $io = new ConsoleIo($out, $err); + + $code = (new FixtureImportCommand())->run([], $io); + + $this->assertSame(FixtureImportCommand::CODE_ERROR, $code); + $this->assertStringContainsString('Missing `test_template` datasource configuration', implode("\n", $err->messages())); + } + + /** + * @return void + */ + public function testUnsupportedDriverIsRejectedBeforeAnyDump(): void + { + ConnectionManager::setConfig('test_template', ['url' => 'sqlite:///:memory:']); + $io = new ConsoleIo(new StubConsoleOutput(), new StubConsoleOutput()); + + $this->expectExceptionMessage('Database engine Sqlite is not supported'); + + (new FixtureImportCommand())->run([], $io); + } +} diff --git a/tests/TestCase/Engine/MysqlEngineTest.php b/tests/TestCase/Engine/MysqlEngineTest.php new file mode 100644 index 0000000..ed3d0d7 --- /dev/null +++ b/tests/TestCase/Engine/MysqlEngineTest.php @@ -0,0 +1,72 @@ + 'app_test', + 'host' => 'db', + 'port' => 3307, + 'username' => 'user', + 'password' => 'secret', + ]); + + $this->assertSame("--host=db --port=3307 --user=user --password='secret'", $engine->baseArguments()); + } + + /** + * @return void + */ + public function testBaseArgumentsWithoutOptionalKeys(): void + { + $engine = new MysqlEngineProbe(['database' => 'app_test']); + + $this->assertSame('', $engine->baseArguments()); + } + + /** + * @return void + */ + public function testEmptyPasswordIsPassedEmpty(): void + { + $engine = new MysqlEngineProbe(['database' => 'app_test', 'username' => 'root', 'password' => '']); + + $this->assertSame("--user=root --password=''", $engine->baseArguments()); + } + + /** + * @return void + */ + public function testDatabaseNameIsRequired(): void + { + $this->expectException(InvalidArgumentException::class); + + $this->expectExceptionMessage('must name a `database`'); + + new MysqlEngine(['host' => 'db']); + } +} diff --git a/tests/TestCase/Engine/PostgresEngineTest.php b/tests/TestCase/Engine/PostgresEngineTest.php new file mode 100644 index 0000000..96bce2e --- /dev/null +++ b/tests/TestCase/Engine/PostgresEngineTest.php @@ -0,0 +1,80 @@ +ambientPassword = getenv('PGPASSWORD'); + putenv('PGPASSWORD'); + } + + /** + * @return void + */ + protected function tearDown(): void + { + if ($this->ambientPassword === false) { + putenv('PGPASSWORD'); + } else { + putenv('PGPASSWORD=' . $this->ambientPassword); + } + parent::tearDown(); + } + + /** + * @return void + */ + public function testBaseArgumentsWithFullConfig(): void + { + $engine = new PostgresEngineProbe([ + 'database' => 'app_test', + 'host' => 'db', + 'port' => 5433, + 'username' => 'user', + 'password' => 'secret', + ]); + + $this->assertSame('--host=db --port=5433 --username=user', $engine->baseArguments()); + $engine->exposePassword(); + $this->assertSame('secret', getenv('PGPASSWORD')); + } + + /** + * @return void + */ + public function testBaseArgumentsWithoutOptionalKeys(): void + { + $engine = new PostgresEngineProbe(['database' => 'app_test']); + + $this->assertSame('', $engine->baseArguments()); + $engine->exposePassword(); + $this->assertFalse(getenv('PGPASSWORD')); + } +} diff --git a/tests/TestCase/TestSuite/Fixture/Extension/PHPUnitExtensionTest.php b/tests/TestCase/TestSuite/Fixture/Extension/PHPUnitExtensionTest.php new file mode 100644 index 0000000..33220f0 --- /dev/null +++ b/tests/TestCase/TestSuite/Fixture/Extension/PHPUnitExtensionTest.php @@ -0,0 +1,54 @@ +, bool}> + */ + public static function verboseProvider(): array + { + return [ + 'missing' => [[], false], + 'false' => [['verbose' => 'false'], false], + 'zero' => [['verbose' => '0'], false], + 'empty' => [['verbose' => ''], false], + 'garbage' => [['verbose' => 'maybe'], false], + 'true' => [['verbose' => 'true'], true], + 'one' => [['verbose' => '1'], true], + 'on' => [['verbose' => 'on'], true], + ]; + } + + /** + * @param array $parameters Extension parameters + * @param bool $expected Expected result + * @return void + */ + #[DataProvider('verboseProvider')] + public function testIsVerbose(array $parameters, bool $expected): void + { + $extension = new PHPUnitExtension(); + + $this->assertSame($expected, $extension->isVerbose(ParameterCollection::fromArray($parameters))); + } +} diff --git a/tests/TestCase/TestSuite/Fixture/Extension/TransactionGuardTest.php b/tests/TestCase/TestSuite/Fixture/Extension/TransactionGuardTest.php index 3937bef..94af133 100644 --- a/tests/TestCase/TestSuite/Fixture/Extension/TransactionGuardTest.php +++ b/tests/TestCase/TestSuite/Fixture/Extension/TransactionGuardTest.php @@ -12,7 +12,7 @@ */ namespace CakeDC\DbTest\Test\TestCase\TestSuite\Fixture\Extension; -use Cake\Database\Connection; +use CakeDC\DbTest\Test\TestSuite\Fixture\RecordingConnection; use CakeDC\DbTest\TestSuite\Fixture\Extension\TransactionGuard; use PHPUnit\Framework\TestCase; @@ -22,9 +22,9 @@ class TransactionGuardTest extends TestCase { /** - * @var \Cake\Database\Connection + * @var \CakeDC\DbTest\Test\TestSuite\Fixture\RecordingConnection */ - protected Connection $connection; + protected RecordingConnection $connection; /** * @return void @@ -33,7 +33,7 @@ protected function setUp(): void { parent::setUp(); - $this->connection = $this->fakeConnection(); + $this->connection = new RecordingConnection(); } /** @@ -82,58 +82,4 @@ public function testEndDoesNothingWithoutTransaction(): void $this->assertSame([], $this->connection->calls); } - - /** - * @return \Cake\Database\Connection - */ - protected function fakeConnection(): Connection - { - return new class extends Connection { - /** - * @var array - */ - public array $calls = []; - - /** - * @var bool - */ - public bool $inTransaction = false; - - /** - * Skip the parent constructor, the test never touches the driver. - */ - public function __construct() - { - } - - /** - * @return bool - */ - public function inTransaction(): bool - { - return $this->inTransaction; - } - - /** - * @return void - */ - public function begin(): void - { - $this->calls[] = 'begin'; - $this->inTransaction = true; - } - - /** - * @param bool|null $toBeginning Whether the transaction should be rolled back to the beginning. - * @return bool - */ - public function rollback(?bool $toBeginning = null): bool - { - $this->calls[] = 'rollback'; - $this->inTransaction = false; - - return true; - } - }; - } } diff --git a/tests/TestSuite/Fixture/MysqlEngineProbe.php b/tests/TestSuite/Fixture/MysqlEngineProbe.php new file mode 100644 index 0000000..cafc549 --- /dev/null +++ b/tests/TestSuite/Fixture/MysqlEngineProbe.php @@ -0,0 +1,29 @@ +getBaseArguments(); + } +} diff --git a/tests/TestSuite/Fixture/PostgresEngineProbe.php b/tests/TestSuite/Fixture/PostgresEngineProbe.php new file mode 100644 index 0000000..dab092c --- /dev/null +++ b/tests/TestSuite/Fixture/PostgresEngineProbe.php @@ -0,0 +1,37 @@ +getBaseArguments(); + } + + /** + * @return void + */ + public function exposePassword(): void + { + $this->setPassword(); + } +} diff --git a/tests/TestSuite/Fixture/RecordingConnection.php b/tests/TestSuite/Fixture/RecordingConnection.php new file mode 100644 index 0000000..5c603ef --- /dev/null +++ b/tests/TestSuite/Fixture/RecordingConnection.php @@ -0,0 +1,67 @@ + + */ + public array $calls = []; + + /** + * @var bool + */ + public bool $inTransaction = false; + + /** + * Skip the parent constructor, the tests never touch the driver. + */ + public function __construct() + { + } + + /** + * @return bool + */ + public function inTransaction(): bool + { + return $this->inTransaction; + } + + /** + * @return void + */ + public function begin(): void + { + $this->calls[] = 'begin'; + $this->inTransaction = true; + } + + /** + * @param bool|null $toBeginning Whether the transaction should be rolled back to the beginning. + * @return bool + */ + public function rollback(?bool $toBeginning = null): bool + { + $this->calls[] = 'rollback'; + $this->inTransaction = false; + + return true; + } +} diff --git a/tests/TestSuite/Fixture/SqliteExtension.php b/tests/TestSuite/Fixture/SqliteExtension.php index 25d2bd6..5607577 100644 --- a/tests/TestSuite/Fixture/SqliteExtension.php +++ b/tests/TestSuite/Fixture/SqliteExtension.php @@ -46,7 +46,7 @@ public function bootstrap(Configuration $configuration, Facade $facade, Paramete $facade->registerSubscribers( new PHPUnitPreparationStartedSubscriber(), new PHPUnitTestFinishedSubscriber(), - new PHPUnitTestRunnerFinishedSubscriber() + new PHPUnitTestRunnerFinishedSubscriber(), ); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index acb189c..7d73696 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -12,13 +12,14 @@ */ use Cake\Cache\Cache; use Cake\Core\Configure; +use Cake\Core\Configure\Engine\PhpConfig; use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; use Cake\Log\Log; use Cake\TestSuite\Fixture\SchemaLoader; use CakeDC\DbTest\DbTestPlugin; -require_once 'vendor/autoload.php'; +require_once dirname(__DIR__) . '/vendor/autoload.php'; // Path constants to a few helpful things. if (!defined('DS')) { @@ -29,8 +30,8 @@ define('CORE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp' . DS); define('CAKE', CORE_PATH . 'src' . DS); define('TESTS', ROOT . DS . 'tests'); -define('APP', ROOT . DS . 'tests' . DS . 'test_app' . DS); -define('APP_DIR', 'test_app'); +define('APP', ROOT . DS . 'tests' . DS); +define('APP_DIR', 'tests'); define('WEBROOT_DIR', 'webroot'); define('WWW_ROOT', APP . 'webroot' . DS); define('TMP', sys_get_temp_dir() . DS); @@ -45,9 +46,10 @@ date_default_timezone_set('UTC'); mb_internal_encoding('UTF-8'); +Configure::config('default', new PhpConfig()); Configure::write('debug', true); Configure::write('App', [ - 'namespace' => 'DebugKit\TestApp', + 'namespace' => 'CakeDC\DbTest\Test', 'encoding' => 'UTF-8', 'base' => false, 'baseUrl' => false, @@ -68,9 +70,9 @@ ]); Cache::setConfig([ - '_cake_core_' => [ + '_cake_translations_' => [ 'engine' => 'File', - 'prefix' => 'cake_core_', + 'prefix' => 'cake_translations_', 'serialize' => true, ], '_cake_model_' => [ @@ -87,7 +89,7 @@ // Ensure default test connection is defined if (!getenv('DB_URL')) { - putenv('DB_URL=sqlite://127.0.0.1/' . TMP . 'debug_kit_test.sqlite'); + putenv('DB_URL=sqlite://127.0.0.1/' . TMP . 'db_test_test.sqlite'); } $config = [ @@ -95,9 +97,7 @@ 'timezone' => 'UTC', ]; -// Use the test connection for 'debug_kit' as well. ConnectionManager::setConfig('test', $config); -ConnectionManager::setConfig('test_debug_kit', $config); Log::setConfig([ 'debug' => [ @@ -117,7 +117,8 @@ Plugin::getCollection()->add(new DbTestPlugin()); // Create test database schema -if (env('FIXTURE_SCHEMA_METADATA')) { +$schemaFile = env('FIXTURE_SCHEMA_METADATA'); +if (is_string($schemaFile) && $schemaFile !== '') { $loader = new SchemaLoader(); - $loader->loadInternalFile(env('FIXTURE_SCHEMA_METADATA'), 'test'); + $loader->loadInternalFile($schemaFile, 'test'); } diff --git a/tests/config/app.php b/tests/config/app.php new file mode 100644 index 0000000..e382b3d --- /dev/null +++ b/tests/config/app.php @@ -0,0 +1,16 @@ +