From 1e1ec16f73a8a73e048cd8d2306a4dc2fb5f4605 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20D?= Date: Sun, 4 Dec 2022 14:33:17 +0100 Subject: [PATCH] chore: Remove BypassFinals and Pseudo PDO. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rubén D --- composer.json | 2 - composer.lock | 124 +------- lib/SP/Core/Acl/Acl.php | 12 +- lib/SP/Core/Application.php | 23 +- lib/SP/Core/DataCollection.php | 10 +- lib/SP/Domain/Account/Services/AccountAcl.php | 2 +- lib/SP/Domain/Common/Services/Service.php | 8 +- .../Export/Ports/BackupFilesInterface.php | 61 ++++ lib/SP/Domain/Export/Services/BackupFiles.php | 9 +- .../Export/Services/FileBackupService.php | 25 +- .../Domain/Install/Services/MysqlService.php | 3 +- .../Infrastructure/Database/DatabaseUtil.php | 11 +- .../Infrastructure/Database/QueryResult.php | 2 +- .../Export/Services/FileBackupServiceTest.php | 20 +- .../Domain/Install/Services/InstallerTest.php | 22 +- .../SP/Domain/Install/Services/MySQLTest.php | 290 +++++++++++------- .../ConfigDataGenerator.php} | 35 +-- .../Repositories/AccountRepositoryTest.php | 31 +- tests/SP/UnitaryTestCase.php | 29 +- 19 files changed, 357 insertions(+), 362 deletions(-) create mode 100644 lib/SP/Domain/Export/Ports/BackupFilesInterface.php rename tests/SP/{Stubs/Pdo.php => Generators/ConfigDataGenerator.php} (50%) diff --git a/composer.json b/composer.json index 58d9e5ba..0d2fd10a 100644 --- a/composer.json +++ b/composer.json @@ -64,8 +64,6 @@ "fzaninotto/faker": "1.9.x-dev", "fabpot/goutte": "^v3.2", "nikic/php-parser": "^v4.1", - "dg/bypass-finals": "^v1.3", - "jimbojsb/pseudo": "^0.5", "squizlabs/php_codesniffer": "^3", "phpstan/phpstan": "^1.9" }, diff --git a/composer.lock b/composer.lock index 59161a1c..07284899 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "6fb2448797e2a31979571f067d57d035", + "content-hash": "7c6a01ea8b616908b57b64e2c6e49c48", "packages": [ { "name": "ademarre/binary-to-text-php", @@ -2487,16 +2487,16 @@ }, { "name": "symfony/console", - "version": "v5.4.15", + "version": "v5.4.16", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "ea59bb0edfaf9f28d18d8791410ee0355f317669" + "reference": "8e9b9c8dfb33af6057c94e1b44846bee700dc5ef" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/ea59bb0edfaf9f28d18d8791410ee0355f317669", - "reference": "ea59bb0edfaf9f28d18d8791410ee0355f317669", + "url": "https://api.github.com/repos/symfony/console/zipball/8e9b9c8dfb33af6057c94e1b44846bee700dc5ef", + "reference": "8e9b9c8dfb33af6057c94e1b44846bee700dc5ef", "shasum": "" }, "require": { @@ -2566,7 +2566,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v5.4.15" + "source": "https://github.com/symfony/console/tree/v5.4.16" }, "funding": [ { @@ -2582,7 +2582,7 @@ "type": "tidelift" } ], - "time": "2022-10-26T21:41:52+00:00" + "time": "2022-11-25T14:09:27+00:00" }, { "name": "symfony/deprecation-contracts", @@ -3697,59 +3697,6 @@ } ], "packages-dev": [ - { - "name": "dg/bypass-finals", - "version": "v1.4.1", - "source": { - "type": "git", - "url": "https://github.com/dg/bypass-finals.git", - "reference": "4c424c3ed359220fce044f35cdf9f48b0089b2ca" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/dg/bypass-finals/zipball/4c424c3ed359220fce044f35cdf9f48b0089b2ca", - "reference": "4c424c3ed359220fce044f35cdf9f48b0089b2ca", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "require-dev": { - "nette/tester": "^2.3", - "phpstan/phpstan": "^0.12" - }, - "type": "library", - "autoload": { - "classmap": [ - "src/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause", - "GPL-2.0", - "GPL-3.0" - ], - "authors": [ - { - "name": "David Grudl", - "homepage": "https://davidgrudl.com" - } - ], - "description": "Removes final keyword from source code on-the-fly and allows mocking of final methods and classes", - "keywords": [ - "finals", - "mocking", - "phpunit", - "testing", - "unit" - ], - "support": { - "issues": "https://github.com/dg/bypass-finals/issues", - "source": "https://github.com/dg/bypass-finals/tree/v1.4.1" - }, - "time": "2022-09-13T17:27:26+00:00" - }, { "name": "doctrine/instantiator", "version": "1.4.1", @@ -3935,49 +3882,6 @@ "abandoned": true, "time": "2020-12-11T09:59:14+00:00" }, - { - "name": "jimbojsb/pseudo", - "version": "0.5", - "source": { - "type": "git", - "url": "https://github.com/jimbojsb/pseudo.git", - "reference": "d75d639baf6b5f0a770d0691607ffb7385ba3c10" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/jimbojsb/pseudo/zipball/d75d639baf6b5f0a770d0691607ffb7385ba3c10", - "reference": "d75d639baf6b5f0a770d0691607ffb7385ba3c10", - "shasum": "" - }, - "require-dev": { - "phpunit/phpunit": "^5.0" - }, - "type": "library", - "autoload": { - "files": [ - "src/php-sql-parser.php" - ], - "psr-0": { - "Pseudo": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Josh Butts", - "email": "josh@joshbutts.com" - } - ], - "description": "PDO/MySQL Connection Mocking", - "support": { - "issues": "https://github.com/jimbojsb/pseudo/issues", - "source": "https://github.com/jimbojsb/pseudo/tree/0.5" - }, - "time": "2021-09-27T03:12:35+00:00" - }, { "name": "myclabs/deep-copy", "version": "1.11.0", @@ -4689,12 +4593,12 @@ "source": { "type": "git", "url": "https://github.com/Roave/SecurityAdvisories.git", - "reference": "0399700d159e09b16645945758b65b921d3491fe" + "reference": "891ecbb72eac808c80fb97f2cce67824e94e5652" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/0399700d159e09b16645945758b65b921d3491fe", - "reference": "0399700d159e09b16645945758b65b921d3491fe", + "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/891ecbb72eac808c80fb97f2cce67824e94e5652", + "reference": "891ecbb72eac808c80fb97f2cce67824e94e5652", "shasum": "" }, "conflict": { @@ -4719,12 +4623,12 @@ "awesome-support/awesome-support": "<=6.0.7", "aws/aws-sdk-php": ">=3,<3.2.1", "backdrop/backdrop": "<=1.23", - "badaso/core": "<2.6.1", + "badaso/core": "<2.7", "bagisto/bagisto": "<0.1.5", "barrelstrength/sprout-base-email": "<1.2.7", "barrelstrength/sprout-forms": "<3.9", "barryvdh/laravel-translation-manager": "<0.6.2", - "baserproject/basercms": "<4.5.4", + "baserproject/basercms": "<=4.7.1", "billz/raspap-webgui": "<=2.6.6", "bk2k/bootstrap-package": ">=7.1,<7.1.2|>=8,<8.0.8|>=9,<9.0.4|>=9.1,<9.1.3|>=10,<10.0.10|>=11,<11.0.3", "bmarshall511/wordpress_zero_spam": "<5.2.13", @@ -4983,6 +4887,7 @@ "phpunit/phpunit": ">=4.8.19,<4.8.28|>=5,<5.6.3", "phpwhois/phpwhois": "<=4.2.5", "phpxmlrpc/extras": "<0.6.1", + "phpxmlrpc/phpxmlrpc": "<4.9", "pimcore/data-hub": "<1.2.4", "pimcore/pimcore": "<10.5.9", "pocketmine/bedrock-protocol": "<8.0.2", @@ -5051,6 +4956,7 @@ "snipe/snipe-it": "<6.0.11|>= 6.0.0-RC-1, <= 6.0.0-RC-5", "socalnick/scn-social-auth": "<1.15.2", "socialiteproviders/steam": "<1.1", + "spatie/browsershot": "<3.57.4", "spipu/html2pdf": "<5.2.4", "spoonity/tcpdf": "<6.2.22", "squizlabs/php_codesniffer": ">=1,<2.8.1|>=3,<3.0.1", @@ -5222,7 +5128,7 @@ "type": "tidelift" } ], - "time": "2022-11-23T23:04:03+00:00" + "time": "2022-12-02T23:04:13+00:00" }, { "name": "sebastian/cli-parser", diff --git a/lib/SP/Core/Acl/Acl.php b/lib/SP/Core/Acl/Acl.php index d61913d8..7657235e 100644 --- a/lib/SP/Core/Acl/Acl.php +++ b/lib/SP/Core/Acl/Acl.php @@ -28,20 +28,17 @@ namespace SP\Core\Acl; use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; use SP\Core\Events\EventDispatcher; +use SP\Core\Events\EventDispatcherInterface; use SP\Core\Events\EventMessage; use function SP\__u; use function SP\processException; -defined('APP_ROOT') || die(); - /** * Esta clase es la encargada de calcular las access lists de acceso a usuarios. */ class Acl implements ActionsInterface { protected static ?Actions $actions = null; - private ContextInterface $context; - private EventDispatcher $eventDispatcher; /** * Acl constructor. @@ -51,13 +48,10 @@ class Acl implements ActionsInterface * @param Actions|null $actions */ public function __construct( - ContextInterface $context, - EventDispatcher $eventDispatcher, + private ContextInterface $context, + private EventDispatcherInterface $eventDispatcher, Actions $actions = null ) { - $this->context = $context; - $this->eventDispatcher = $eventDispatcher; - self::$actions = $actions; } diff --git a/lib/SP/Core/Application.php b/lib/SP/Core/Application.php index cda43f8c..5f0ece4c 100644 --- a/lib/SP/Core/Application.php +++ b/lib/SP/Core/Application.php @@ -24,9 +24,8 @@ namespace SP\Core; - use SP\Core\Context\ContextInterface; -use SP\Core\Events\EventDispatcher; +use SP\Core\Events\EventDispatcherInterface; use SP\Domain\Config\Ports\ConfigInterface; /** @@ -34,33 +33,25 @@ use SP\Domain\Config\Ports\ConfigInterface; */ final class Application { - private ConfigInterface $config; - private EventDispatcher $eventDispatcher; - private ContextInterface $context; - /** * Module constructor. * * @param ConfigInterface $config - * @param EventDispatcher $eventDispatcher + * @param EventDispatcherInterface $eventDispatcher * @param ContextInterface $context */ public function __construct( - ConfigInterface $config, - EventDispatcher $eventDispatcher, - ContextInterface $context - ) { - $this->config = $config; - $this->eventDispatcher = $eventDispatcher; - $this->context = $context; - } + private ConfigInterface $config, + private EventDispatcherInterface $eventDispatcher, + private ContextInterface $context + ) {} public function getConfig(): ConfigInterface { return $this->config; } - public function getEventDispatcher(): EventDispatcher + public function getEventDispatcher(): EventDispatcherInterface { return $this->eventDispatcher; } diff --git a/lib/SP/Core/DataCollection.php b/lib/SP/Core/DataCollection.php index 98f6653d..75ee375d 100644 --- a/lib/SP/Core/DataCollection.php +++ b/lib/SP/Core/DataCollection.php @@ -36,20 +36,20 @@ abstract class DataCollection extends ArrayObject public function get(string $key, mixed $default = null): mixed { - if (!property_exists($this, $key)) { - return $default; + if ($this->offsetExists($key)) { + return $this->offsetGet($key); } - return $this->{$key}; + return $default; } public function set(string $key, mixed $value): void { - $this->{$key} = $value; + $this->offsetSet($key, $value); } public function exists(string $key): bool { - return property_exists($this, $key); + return $this->offsetExists($key); } } diff --git a/lib/SP/Domain/Account/Services/AccountAcl.php b/lib/SP/Domain/Account/Services/AccountAcl.php index 79b7b203..460c4e0e 100644 --- a/lib/SP/Domain/Account/Services/AccountAcl.php +++ b/lib/SP/Domain/Account/Services/AccountAcl.php @@ -31,7 +31,7 @@ use SP\Core\Acl\ActionsInterface; * * @package SP\Domain\Account\Services */ -final class AccountAcl +class AccountAcl { private const ACTIONS_VIEW = [ ActionsInterface::ACCOUNT_VIEW, diff --git a/lib/SP/Domain/Common/Services/Service.php b/lib/SP/Domain/Common/Services/Service.php index 6ee91f9f..5675918a 100644 --- a/lib/SP/Domain/Common/Services/Service.php +++ b/lib/SP/Domain/Common/Services/Service.php @@ -30,7 +30,7 @@ use SP\Core\Context\ContextException; use SP\Core\Context\ContextInterface; use SP\Core\Context\SessionContext; use SP\Core\Crypt\Session; -use SP\Core\Events\EventDispatcher; +use SP\Core\Events\EventDispatcherInterface; use SP\Domain\Config\Ports\ConfigInterface; use function SP\__u; use function SP\logger; @@ -44,9 +44,9 @@ abstract class Service { protected const STATUS_INTERNAL_ERROR = 1000; - protected ConfigInterface $config; - protected ContextInterface $context; - protected EventDispatcher $eventDispatcher; + protected ConfigInterface $config; + protected ContextInterface $context; + protected EventDispatcherInterface $eventDispatcher; public function __construct(Application $application) { diff --git a/lib/SP/Domain/Export/Ports/BackupFilesInterface.php b/lib/SP/Domain/Export/Ports/BackupFilesInterface.php new file mode 100644 index 00000000..2e9cbbc3 --- /dev/null +++ b/lib/SP/Domain/Export/Ports/BackupFilesInterface.php @@ -0,0 +1,61 @@ +. + */ + +namespace SP\Domain\Export\Ports; + +use SP\Infrastructure\File\ArchiveHandlerInterface; +use SP\Infrastructure\File\FileHandlerInterface; + +/** + * BackupFiles + */ +interface BackupFilesInterface +{ + /** + * @return FileHandlerInterface + */ + public function getAppBackupFileHandler(): FileHandlerInterface; + + /** + * @return FileHandlerInterface + */ + public function getDbBackupFileHandler(): FileHandlerInterface; + + /** + * @return ArchiveHandlerInterface + * @throws \SP\Core\Exceptions\CheckException + */ + public function getDbBackupArchiveHandler(): ArchiveHandlerInterface; + + /** + * @return ArchiveHandlerInterface + * @throws \SP\Core\Exceptions\CheckException + */ + public function getAppBackupArchiveHandler(): ArchiveHandlerInterface; + + /** + * @return string + */ + public function getHash(): string; +} diff --git a/lib/SP/Domain/Export/Services/BackupFiles.php b/lib/SP/Domain/Export/Services/BackupFiles.php index 0f787622..6e0d79cc 100644 --- a/lib/SP/Domain/Export/Services/BackupFiles.php +++ b/lib/SP/Domain/Export/Services/BackupFiles.php @@ -24,19 +24,21 @@ namespace SP\Domain\Export\Services; - use SP\Core\AppInfoInterface; use SP\Core\Exceptions\CheckException; use SP\Core\PhpExtensionChecker; +use SP\Domain\Export\Ports\BackupFilesInterface; use SP\Infrastructure\File\ArchiveHandler; use SP\Infrastructure\File\ArchiveHandlerInterface; use SP\Infrastructure\File\FileHandler; use SP\Infrastructure\File\FileHandlerInterface; +use function SP\__; +use function SP\__u; /** * BackupFiles */ -final class BackupFiles +final class BackupFiles implements BackupFilesInterface { private const BACKUP_PREFFIX = 'sysPassBackup'; private string $hash; @@ -96,7 +98,6 @@ final class BackupFiles __u('Please, check the backup directory permissions') ); } - } public static function getAppBackupFilename( @@ -168,4 +169,4 @@ final class BackupFiles { return $this->hash; } -} \ No newline at end of file +} diff --git a/lib/SP/Domain/Export/Services/FileBackupService.php b/lib/SP/Domain/Export/Services/FileBackupService.php index 8dc76e34..6528eef0 100644 --- a/lib/SP/Domain/Export/Services/FileBackupService.php +++ b/lib/SP/Domain/Export/Services/FileBackupService.php @@ -29,15 +29,16 @@ use PDO; use SP\Core\AppInfoInterface; use SP\Core\Application; use SP\Core\Events\Event; -use SP\Core\Events\EventDispatcher; +use SP\Core\Events\EventDispatcherInterface; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\CheckException; use SP\Core\Exceptions\SPException; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Config\Ports\ConfigDataInterface; -use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\Config\Ports\ConfigInterface; +use SP\Domain\Export\Ports\BackupFilesInterface; use SP\Domain\Export\Ports\FileBackupServiceInterface; -use SP\Infrastructure\Database\Database; +use SP\Infrastructure\Database\DatabaseInterface; use SP\Infrastructure\Database\DatabaseUtil; use SP\Infrastructure\Database\QueryData; use SP\Infrastructure\File\ArchiveHandler; @@ -55,19 +56,19 @@ final class FileBackupService implements FileBackupServiceInterface public const BACKUP_INCLUDE_REGEX = /** @lang RegExp */ '#^(?:[A-Z]:)?(?:/(?!(\.git|backup|cache|temp|vendor|tests))[^/]+)+/[^/]+\.\w+$#Di'; - private Database $database; - private DatabaseUtil $databaseUtil; - private EventDispatcher $eventDispatcher; - private ConfigFileService $config; - private ConfigDataInterface $configData; - private BackupFiles $backupFiles; - private ?string $backupPath = null; + private DatabaseInterface $database; + private DatabaseUtil $databaseUtil; + private EventDispatcherInterface $eventDispatcher; + private ConfigInterface $config; + private ConfigDataInterface $configData; + private BackupFilesInterface $backupFiles; + private ?string $backupPath = null; public function __construct( Application $application, - Database $database, + DatabaseInterface $database, DatabaseUtil $databaseUtil, - BackupFiles $backupFiles + BackupFilesInterface $backupFiles ) { $this->config = $application->getConfig(); $this->eventDispatcher = $application->getEventDispatcher(); diff --git a/lib/SP/Domain/Install/Services/MysqlService.php b/lib/SP/Domain/Install/Services/MysqlService.php index 5786896d..a2d4acf1 100644 --- a/lib/SP/Domain/Install/Services/MysqlService.php +++ b/lib/SP/Domain/Install/Services/MysqlService.php @@ -303,7 +303,8 @@ final class MysqlService implements DatabaseSetupInterface ) ); - if ($this->installData->getDbAuthHost() !== $this->installData->getDbAuthHostDns()) { + if ($this->installData->getDbAuthHostDns() + && $this->installData->getDbAuthHost() !== $this->installData->getDbAuthHostDns()) { $dbc->exec( sprintf( 'DROP USER IF EXISTS %s@%s', diff --git a/lib/SP/Infrastructure/Database/DatabaseUtil.php b/lib/SP/Infrastructure/Database/DatabaseUtil.php index 22fa2503..a1e3ea11 100644 --- a/lib/SP/Infrastructure/Database/DatabaseUtil.php +++ b/lib/SP/Infrastructure/Database/DatabaseUtil.php @@ -25,13 +25,14 @@ namespace SP\Infrastructure\Database; use Exception; +use function SP\processException; /** * Class DBUtil con utilidades de la BD * * @package SP\Storage */ -final class DatabaseUtil +class DatabaseUtil { /** * @var array Tablas de la BBDD @@ -122,9 +123,9 @@ final class DatabaseUtil return true; } catch (Exception $e) { processException($e); - - return false; } + + return false; } /** @@ -149,8 +150,6 @@ final class DatabaseUtil } } catch (Exception $e) { processException($e); - - logger($e->getMessage()); } return $dbinfo; @@ -169,4 +168,4 @@ final class DatabaseUtil return $str; } -} \ No newline at end of file +} diff --git a/lib/SP/Infrastructure/Database/QueryResult.php b/lib/SP/Infrastructure/Database/QueryResult.php index 826a5681..324676c9 100644 --- a/lib/SP/Infrastructure/Database/QueryResult.php +++ b/lib/SP/Infrastructure/Database/QueryResult.php @@ -32,7 +32,7 @@ use function SP\__u; * * @package SP\Infrastructure\Database */ -final class QueryResult +class QueryResult { private ?array $data = null; private ?string $dataType = null; diff --git a/tests/SP/Domain/Export/Services/FileBackupServiceTest.php b/tests/SP/Domain/Export/Services/FileBackupServiceTest.php index 60add845..d8508ccb 100644 --- a/tests/SP/Domain/Export/Services/FileBackupServiceTest.php +++ b/tests/SP/Domain/Export/Services/FileBackupServiceTest.php @@ -24,13 +24,12 @@ namespace SP\Tests\Domain\Export\Services; -use SP\Core\PhpExtensionChecker; -use SP\Domain\Export\Services\BackupFiles; +use SP\Domain\Export\Ports\BackupFilesInterface; use SP\Domain\Export\Services\FileBackupService; -use SP\Infrastructure\Database\Database; +use SP\Infrastructure\Database\DatabaseInterface; use SP\Infrastructure\Database\DatabaseUtil; -use SP\Infrastructure\Database\MysqlHandler; -use SP\Infrastructure\File\ArchiveHandler; +use SP\Infrastructure\Database\DbStorageInterface; +use SP\Infrastructure\File\ArchiveHandlerInterface; use SP\Tests\UnitaryTestCase; /** @@ -64,12 +63,12 @@ class FileBackupServiceTest extends UnitaryTestCase { parent::setUp(); - $database = $this->createStub(Database::class); + $database = $this->createStub(DatabaseInterface::class); $database->method('getDbHandler')->willReturn( - $this->createStub(MysqlHandler::class) + $this->createStub(DbStorageInterface::class) ); - $archiveHandler = $this->createMock(ArchiveHandler::class); + $archiveHandler = $this->createMock(ArchiveHandlerInterface::class); $archiveHandler->expects(self::once()) ->method('compressFile') ->withAnyParameters(); @@ -80,10 +79,7 @@ class FileBackupServiceTest extends UnitaryTestCase FileBackupService::BACKUP_INCLUDE_REGEX ); - $backupFiles = $this->getMockBuilder(BackupFiles::class) - ->onlyMethods(['getDbBackupArchiveHandler', 'getAppBackupArchiveHandler']) - ->setConstructorArgs([new PhpExtensionChecker()]) - ->getMock(); + $backupFiles = $this->createStub(BackupFilesInterface::class); $backupFiles->method('getDbBackupArchiveHandler')->willReturn($archiveHandler); $backupFiles->method('getAppBackupArchiveHandler')->willReturn($archiveHandler); diff --git a/tests/SP/Domain/Install/Services/InstallerTest.php b/tests/SP/Domain/Install/Services/InstallerTest.php index ef3584f8..2545dc80 100644 --- a/tests/SP/Domain/Install/Services/InstallerTest.php +++ b/tests/SP/Domain/Install/Services/InstallerTest.php @@ -27,16 +27,14 @@ namespace SP\Tests\Domain\Install\Services; use Exception; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\SPException; -use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Config\Ports\ConfigServiceInterface; use SP\Domain\Install\Adapters\InstallData; use SP\Domain\Install\Ports\InstallerServiceInterface; use SP\Domain\Install\Services\DatabaseSetupInterface; use SP\Domain\Install\Services\InstallerService; +use SP\Domain\User\Ports\UserGroupServiceInterface; use SP\Domain\User\Ports\UserProfileServiceInterface; -use SP\Domain\User\Services\UserGroupService; -use SP\Domain\User\Services\UserProfileService; -use SP\Domain\User\Services\UserService; -use SP\Http\Request; +use SP\Domain\User\Ports\UserServiceInterface; use SP\Http\RequestInterface; use SP\Infrastructure\Database\DatabaseConnectionData; use SP\Tests\UnitaryTestCase; @@ -434,18 +432,14 @@ class InstallerTest extends UnitaryTestCase $installer->run($params); } - /** - * @noinspection ClassMockingCorrectnessInspection - * @noinspection PhpUnitInvalidMockingEntityInspection - */ protected function setUp(): void { $this->databaseSetup = $this->createMock(DatabaseSetupInterface::class); - $this->userService = $this->createMock(UserService::class); - $this->request = $this->createStub(Request::class); - $this->configService = $this->createMock(ConfigService::class); - $this->userGroupService = $this->createMock(UserGroupService::class); - $this->userProfileService = $this->createMock(UserProfileService::class); + $this->userService = $this->createMock(UserServiceInterface::class); + $this->request = $this->createStub(RequestInterface::class); + $this->configService = $this->createMock(ConfigServiceInterface::class); + $this->userGroupService = $this->createMock(UserGroupServiceInterface::class); + $this->userProfileService = $this->createMock(UserProfileServiceInterface::class); parent::setUp(); } diff --git a/tests/SP/Domain/Install/Services/MySQLTest.php b/tests/SP/Domain/Install/Services/MySQLTest.php index 90efb3e0..877e66ea 100644 --- a/tests/SP/Domain/Install/Services/MySQLTest.php +++ b/tests/SP/Domain/Install/Services/MySQLTest.php @@ -24,7 +24,10 @@ namespace SP\Tests\Domain\Install\Services; +use PDO; use PDOException; +use PHPUnit\Framework\Constraint\Callback; +use PHPUnit\Framework\MockObject\MockObject; use SP\Core\Exceptions\SPException; use SP\Domain\Config\Ports\ConfigDataInterface; use SP\Domain\Install\Adapters\InstallData; @@ -33,7 +36,6 @@ use SP\Infrastructure\Database\DatabaseFileInterface; use SP\Infrastructure\Database\DatabaseUtil; use SP\Infrastructure\Database\DbStorageInterface; use SP\Infrastructure\File\FileException; -use SP\Tests\Stubs\Pdo; use SP\Tests\UnitaryTestCase; use function SP\__; use function SP\__u; @@ -45,22 +47,22 @@ use function SP\__u; */ class MySQLTest extends UnitaryTestCase { - private DbStorageInterface $DBStorage; - private MysqlService $mysql; - private Pdo $pdo; - private InstallData $installData; - private ConfigDataInterface $configData; - private DatabaseFileInterface $databaseFile; - private DatabaseUtil $databaseUtil; + private DbStorageInterface|MockObject $dbStorage; + private MysqlService $mysqlService; + private PDO|MockObject $pdo; + private InstallData $installData; + private ConfigDataInterface $configData; + private DatabaseFileInterface|MockObject $databaseFile; + private DatabaseUtil|MockObject $databaseUtil; /** * @throws \SP\Core\Exceptions\SPException */ public function testConnectDatabaseIsSuccessful(): void { - $this->DBStorage->expects(self::once())->method('getConnectionSimple'); + $this->dbStorage->expects(self::once())->method('getConnectionSimple'); - $this->mysql->connectDatabase(); + $this->mysqlService->connectDatabase(); } /** @@ -68,7 +70,7 @@ class MySQLTest extends UnitaryTestCase */ public function testConnectDatabaseIsNotSuccessful(): void { - $this->DBStorage->expects(self::once()) + $this->dbStorage->expects(self::once()) ->method('getConnectionSimple') ->willThrowException( new SPException('test') @@ -77,7 +79,7 @@ class MySQLTest extends UnitaryTestCase $this->expectException(SPException::class); $this->expectExceptionMessage('Unable to connect to DB'); - $this->mysql->connectDatabase(); + $this->mysqlService->connectDatabase(); } /** @@ -85,48 +87,66 @@ class MySQLTest extends UnitaryTestCase */ public function testSetupUserIsSuccessful(): void { - $this->pdo->mock('SELECT COUNT(*) FROM mysql.user WHERE `user` = ? AND (`host` = ? OR `host` = ?)', []); + $query = 'SELECT COUNT(*) FROM mysql.user WHERE `user` = ? AND (`host` = ? OR `host` = ?)'; - [$user, $pass] = $this->mysql->setupDbUser(); + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + function ($args) { + return str_starts_with($args[0], 'sp_') + && $args[1] === $this->installData->getDbAuthHost() + && $args[2] === null; + } + )); + + [$user, $pass] = $this->mysqlService->setupDbUser(); $this->assertSame(preg_match('/sp_\w+/', $user), 1); $this->assertNotEmpty($pass); $this->assertEquals(16, strlen($pass)); - } public function testSetupUserIsNotSuccessful(): void { - $this->pdo->mock('SELECT COUNT(*) FROM mysql.user WHERE `user` = ? AND (`host` = ? OR `host` = ?)', []); - - $pdoException = new PDOException('test'); - - $this->DBStorage->expects(self::once()) + $this->dbStorage->expects(self::once()) ->method('getConnectionSimple') - ->willThrowException($pdoException); + ->willThrowException(new PDOException('test')); $this->expectException(SPException::class); $this->expectExceptionMessageMatches('/Unable to check the sysPass user \(sp_\w+\)/'); - $this->mysql->setupDbUser(); + $this->mysqlService->setupDbUser(); } public function testCheckDatabaseDoesNotExist(): void { - $this->pdo->mock('SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', [], []); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; - $this->assertFalse($this->mysql->checkDatabaseExists()); + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(0); + + $this->assertFalse($this->mysqlService->checkDatabaseExists()); } public function testCheckDatabaseExists(): void { - $this->pdo->mock( - 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', - [[1]], - [$this->installData->getDbName()] - ); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; - $this->assertTrue($this->mysql->checkDatabaseExists()); + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(1); + + $this->assertTrue($this->mysqlService->checkDatabaseExists()); } /** @@ -134,11 +154,15 @@ class MySQLTest extends UnitaryTestCase */ public function testCreateDatabaseIsSuccessful(): void { - $this->pdo->mock( - 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', - [], - [$this->installData->getDbName()] - ); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; + + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(0); $this->configData->setDbUser(self::$faker->userName); @@ -164,9 +188,13 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->withConsecutive(...$execArguments); - $this->mysql->createDatabase($this->configData->getDbUser()); - } + $this->pdo->expects(self::exactly(2))->method('quote')->withConsecutive( + [$this->configData->getDbUser()], + [$this->installData->getDbAuthHost()], + )->willReturnArgument(0); + $this->mysqlService->createDatabase($this->configData->getDbUser()); + } /** * @throws \SP\Core\Exceptions\SPException @@ -184,7 +212,7 @@ class MySQLTest extends UnitaryTestCase ) ); - $this->mysql->createDatabase(); + $this->mysqlService->createDatabase(); } /** @@ -192,16 +220,20 @@ class MySQLTest extends UnitaryTestCase */ public function testCreateDatabaseIsNotSuccessfulWithDuplicateDatabase(): void { - $this->pdo->mock( - 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', - [[1]], - [$this->installData->getDbName()] - ); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; + + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(1); $this->expectException(SPException::class); $this->expectExceptionMessage('The database already exists'); - $this->mysql->createDatabase(); + $this->mysqlService->createDatabase(); } /** @@ -209,11 +241,15 @@ class MySQLTest extends UnitaryTestCase */ public function testCreateDatabaseIsSuccessfulWithDns(): void { - $this->pdo->mock( - 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', - [], - [$this->installData->getDbName()] - ); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; + + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(0); $this->configData->setDbUser(self::$faker->userName); $this->installData->setDbAuthHostDns(self::$faker->domainName); @@ -248,7 +284,14 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->withConsecutive(...$execArguments); - $this->mysql->createDatabase($this->configData->getDbUser()); + $this->pdo->expects(self::exactly(4))->method('quote')->withConsecutive( + [$this->configData->getDbUser()], + [$this->installData->getDbAuthHost()], + [$this->configData->getDbUser()], + [$this->installData->getDbAuthHostDns()], + )->willReturnArgument(0); + + $this->mysqlService->createDatabase($this->configData->getDbUser()); } /** @@ -256,27 +299,28 @@ class MySQLTest extends UnitaryTestCase */ public function testCreateDatabaseIsNotSuccessfulWithCreateError(): void { - $this->pdo->mock( - 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', - [], - [$this->installData->getDbName()] - ); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; - $pdoException = new PDOException('test'); + $pdoStatement = $this->createMock(\PDOStatement::class); - $this->pdo->method('exec') - ->with( - sprintf( - 'CREATE SCHEMA `%s` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci', - $this->installData->getDbName() - ), - ) - ->willThrowException($pdoException); + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(0); + + $this->pdo->expects(self::once()) + ->method('exec') + ->with(sprintf( + 'CREATE SCHEMA `%s` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci', + $this->installData->getDbName() + )) + ->willThrowException(new PDOException('test')); $this->expectException(SPException::class); - $this->expectExceptionMessage(sprintf(__('Error while creating the DB (\'%s\')'), $pdoException->getMessage())); + $this->expectExceptionMessage(sprintf(__('Error while creating the DB (\'%s\')'), 'test')); - $this->mysql->createDatabase(); + $this->mysqlService->createDatabase(); } /** @@ -284,15 +328,18 @@ class MySQLTest extends UnitaryTestCase */ public function testCreateDatabaseIsNotSuccessfulWithPermissionError(): void { - $this->pdo->mock( - 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1', - [], - [$this->installData->getDbName()] - ); + $query = 'SELECT COUNT(*) FROM information_schema.schemata WHERE `schema_name` = ? LIMIT 1'; + + $pdoStatement = $this->createMock(\PDOStatement::class); + + $this->pdo->expects(self::once())->method('prepare')->with($query)->willReturn($pdoStatement); + $pdoStatement->expects(self::once())->method('execute')->with(new Callback( + fn($args) => $args[0] === $this->installData->getDbName() + )); + $pdoStatement->expects(self::once())->method('fetchColumn')->willReturn(0); $this->configData->setDbUser(self::$faker->userName); - $matcher = $this->any(); $execArguments = [ [ sprintf( @@ -308,24 +355,42 @@ class MySQLTest extends UnitaryTestCase $this->installData->getDbAuthHost() ), ], + [ + sprintf( + 'DROP DATABASE IF EXISTS `%s`', + $this->installData->getDbName() + ), + ], + [ + sprintf( + 'DROP USER IF EXISTS %s@%s', + $this->configData->getDbUser(), + $this->installData->getDbAuthHost() + ), + ], ]; - $pdoException = new PDOException('test'); + + $matcher = $this->any(); $this->pdo->expects($matcher) ->method('exec') ->withConsecutive(...$execArguments) - ->willReturnCallback(function () use ($matcher, $pdoException) { - if ($matcher->getInvocationCount() === 3) { - throw $pdoException; + ->willReturnCallback(function () use ($matcher) { + if ($matcher->getInvocationCount() === 2) { + throw new PDOException('test'); } + + return 1; }); + $this->pdo->method('quote')->willReturnArgument(0); + $this->expectException(SPException::class); $this->expectExceptionMessage( - sprintf(__('Error while setting the database permissions (\'%s\')'), $pdoException->getMessage()) + sprintf(__('Error while setting the database permissions (\'%s\')'), 'test') ); - $this->mysql->createDatabase($this->configData->getDbUser()); + $this->mysqlService->createDatabase($this->configData->getDbUser()); } /** @@ -355,12 +420,13 @@ class MySQLTest extends UnitaryTestCase ) ); - $this->mysql->createDatabase(); + $this->mysqlService->createDatabase(); } public function testRollbackIsSuccessful(): void { $this->configData->setDbUser(self::$faker->userName); + $this->installData->setDbAuthHostDns(self::$faker->domainName); $execArguments = [ [ @@ -389,7 +455,9 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->withConsecutive(...$execArguments); - $this->mysql->rollback($this->configData->getDbUser()); + $this->pdo->method('quote')->willReturnArgument(0); + + $this->mysqlService->rollback($this->configData->getDbUser()); } public function testRollbackIsSuccessfulWithSameDnsHost(): void @@ -418,7 +486,9 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->withConsecutive(...$execArguments); - $this->mysql->rollback($this->configData->getDbUser()); + $this->pdo->method('quote')->willReturnArgument(0); + + $this->mysqlService->rollback($this->configData->getDbUser()); } public function testRollbackIsSuccessfulWithHostingMode(): void @@ -430,7 +500,7 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->with($this->callback(fn($arg) => preg_match($dropRegex, $arg) > 0)); - $this->mysql->rollback(); + $this->mysqlService->rollback(); } /** @@ -455,7 +525,7 @@ class MySQLTest extends UnitaryTestCase ->method('parse') ->willReturn(['DROP TABLE IF EXISTS `Account`;']); - $this->mysql->createDBStructure(); + $this->mysqlService->createDBStructure(); } /** @@ -479,7 +549,7 @@ class MySQLTest extends UnitaryTestCase ) ); - $this->mysql->createDBStructure(); + $this->mysqlService->createDBStructure(); } /** @@ -487,7 +557,6 @@ class MySQLTest extends UnitaryTestCase */ public function testCreateDBStructureIsNotSuccessfulWithCreateSchemaError(): void { - $pdoException = new PDOException("test"); $execArguments = [ [ sprintf('USE `%s`', $this->installData->getDbName()), @@ -500,17 +569,19 @@ class MySQLTest extends UnitaryTestCase 'DROP DATABASE IF EXISTS `%s`', $this->installData->getDbName() ), - ] + ], ]; $matcher = $this->exactly(3); $this->pdo->expects($matcher) ->method('exec') ->withConsecutive(...$execArguments) - ->willReturnCallback(function () use ($matcher, $pdoException) { + ->willReturnCallback(function () use ($matcher) { if ($matcher->getInvocationCount() === 2) { - throw $pdoException; + throw new PDOException('test'); } + + return 1; }); $this->databaseFile->expects(self::once()) @@ -519,10 +590,10 @@ class MySQLTest extends UnitaryTestCase $this->expectException(SPException::class); $this->expectExceptionMessage( - sprintf(__('Error while creating the DB (\'%s\')'), $pdoException->getMessage()) + sprintf(__('Error while creating the DB (\'%s\')'), 'test') ); - $this->mysql->createDBStructure(); + $this->mysqlService->createDBStructure(); } /** @@ -540,7 +611,7 @@ class MySQLTest extends UnitaryTestCase 'DROP DATABASE IF EXISTS `%s`', $this->installData->getDbName() ), - ] + ], ]; $matcher = $this->exactly(2); @@ -557,7 +628,7 @@ class MySQLTest extends UnitaryTestCase sprintf(__('Error while creating the DB (\'%s\')'), $fileException->getMessage()) ); - $this->mysql->createDBStructure(); + $this->mysqlService->createDBStructure(); } /** @@ -570,7 +641,7 @@ class MySQLTest extends UnitaryTestCase ->with($this->installData->getDbName()) ->willReturn(true); - $this->mysql->checkConnection(); + $this->mysqlService->checkConnection(); } /** @@ -589,7 +660,7 @@ class MySQLTest extends UnitaryTestCase 'DROP DATABASE IF EXISTS `%s`', $this->installData->getDbName() ), - ] + ], ]; $this->pdo->expects(self::once()) @@ -599,7 +670,7 @@ class MySQLTest extends UnitaryTestCase $this->expectException(SPException::class); $this->expectExceptionMessage(__u('Error while checking the database')); - $this->mysql->checkConnection(); + $this->mysqlService->checkConnection(); } /** @@ -628,7 +699,9 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->withConsecutive(...$execArguments); - $this->mysql->createDBUser($user, $pass); + $this->pdo->method('quote')->willReturnArgument(0); + + $this->mysqlService->createDBUser($user, $pass); } /** @@ -667,7 +740,9 @@ class MySQLTest extends UnitaryTestCase ->method('exec') ->withConsecutive(...$execArguments); - $this->mysql->createDBUser($user, $pass); + $this->pdo->method('quote')->willReturnArgument(0); + + $this->mysqlService->createDBUser($user, $pass); } /** @@ -682,7 +757,7 @@ class MySQLTest extends UnitaryTestCase $this->pdo->expects(self::exactly(0))->method('exec'); - $this->mysql->createDBUser($user, $pass); + $this->mysqlService->createDBUser($user, $pass); } /** @@ -692,7 +767,7 @@ class MySQLTest extends UnitaryTestCase { $user = self::$faker->userName; $pass = self::$faker->password; - + $this->pdo->expects(self::once()) ->method('exec') ->willThrowException(new PDOException('test')); @@ -700,7 +775,7 @@ class MySQLTest extends UnitaryTestCase $this->expectException(SPException::class); $this->expectExceptionMessage(sprintf(__u('Error while creating the MySQL connection user \'%s\''), $user)); - $this->mysql->createDBUser($user, $pass); + $this->mysqlService->createDBUser($user, $pass); } /** @@ -710,17 +785,22 @@ class MySQLTest extends UnitaryTestCase { parent::setUp(); - $this->pdo = $this->getMockBuilder(Pdo::class)->enableProxyingToOriginalMethods()->getMock(); + $this->pdo = $this->createMock(PDO::class); + + $this->dbStorage = $this->createMock(DbStorageInterface::class); + $this->dbStorage->method('getConnection')->willReturn($this->pdo); + $this->dbStorage->method('getConnectionSimple')->willReturn($this->pdo); - $this->DBStorage = $this->createMock(DbStorageInterface::class); - $this->DBStorage->method('getConnectionSimple')->willReturn($this->pdo); $this->databaseFile = $this->createMock(DatabaseFileInterface::class); $this->installData = $this->getInstallData(); $this->configData = $this->config->getConfigData(); $this->databaseUtil = $this->createMock(DatabaseUtil::class); - $this->mysql = new MysqlService( - $this->DBStorage, $this->installData, $this->databaseFile, $this->databaseUtil + $this->mysqlService = new MysqlService( + $this->dbStorage, + $this->installData, + $this->databaseFile, + $this->databaseUtil ); } diff --git a/tests/SP/Stubs/Pdo.php b/tests/SP/Generators/ConfigDataGenerator.php similarity index 50% rename from tests/SP/Stubs/Pdo.php rename to tests/SP/Generators/ConfigDataGenerator.php index a5d21e80..c99440f4 100644 --- a/tests/SP/Stubs/Pdo.php +++ b/tests/SP/Generators/ConfigDataGenerator.php @@ -22,32 +22,21 @@ * along with sysPass. If not, see . */ -namespace SP\Tests\Stubs; +namespace SP\Tests\Generators; + +use SP\Domain\Config\Adapters\ConfigData; +use SP\Domain\Config\Ports\ConfigDataInterface; /** - * A PDO stub that overrides some unimplementd methods from \Pseudo\Pdo + * Class ConfigDataGenerator */ -class Pdo extends \Pseudo\Pdo +final class ConfigDataGenerator extends DataGenerator { - /** - * (PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.1)
- * Quotes a string for use in a query. - * - * @link https://php.net/manual/en/pdo.quote.php - * - * @param string $string

- * The string to be quoted. - *

- * @param int $type [optional]

- * Provides a data type hint for drivers that have alternate quoting styles. - *

- * - * @return string|false a quoted string that is theoretically safe to pass into an - * SQL statement. Returns FALSE if the driver does not support quoting in - * this way. - */ - public function quote($string, $parameter_type = self::PARAM_STR) + + public function buildConfigData(): ConfigData { - return $string; + return new ConfigData([ + ConfigDataInterface::PASSWORD_SALT => $this->faker->sha1, + ]); } -} \ No newline at end of file +} diff --git a/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php index 67122e48..d4d90fb4 100644 --- a/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php +++ b/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php @@ -32,7 +32,7 @@ use SP\DataModel\ItemSearchData; use SP\Domain\Account\Dtos\AccountPasswordRequest; use SP\Domain\Account\Dtos\AccountRequest; use SP\Domain\Account\Dtos\EncryptedPassword; -use SP\Domain\Account\Services\AccountFilterUser; +use SP\Domain\Account\Ports\AccountFilterUserInterface; use SP\Domain\Common\Adapters\SimpleModel; use SP\Infrastructure\Account\Repositories\AccountRepository; use SP\Infrastructure\Database\DatabaseInterface; @@ -48,9 +48,9 @@ use SP\Tests\UnitaryTestCase; */ class AccountRepositoryTest extends UnitaryTestCase { - private DatabaseInterface|MockObject $database; - private AccountRepository $accountRepository; - private AccountFilterUser $accountFilterUser; + private DatabaseInterface|MockObject $database; + private AccountRepository $accountRepository; + private AccountFilterUserInterface|MockObject $accountFilterUser; public function testGetTotalNumAccounts(): void { @@ -762,8 +762,6 @@ class AccountRepositoryTest extends UnitaryTestCase $params = $arg->getQuery()->getBindValues(); return $params['id'] === $id - && $params['userId'] === $this->context->getUserData()->getId() - && $params['userGroupId'] === $this->context->getUserData()->getUserGroupId() && $arg->getMapClassName() === SimpleModel::class && !empty($arg->getQuery()->getStatement()); } @@ -788,9 +786,7 @@ class AccountRepositoryTest extends UnitaryTestCase function (QueryData $arg) { $params = $arg->getQuery()->getBindValues(); - return $params['userId'] === $this->context->getUserData()->getId() - && $params['userGroupId'] === $this->context->getUserData()->getUserGroupId() - && count($params) === 2 + return count($params) === 0 && $arg->getMapClassName() === SimpleModel::class && !empty($arg->getQuery()->getStatement()); } @@ -818,8 +814,6 @@ class AccountRepositoryTest extends UnitaryTestCase $params = $arg->getQuery()->getBindValues(); return $params['parentId'] === $id - && $params['userId'] === $this->context->getUserData()->getId() - && $params['userGroupId'] === $this->context->getUserData()->getUserGroupId() && $arg->getMapClassName() === SimpleModel::class && !empty($arg->getQuery()->getStatement()); } @@ -863,16 +857,11 @@ class AccountRepositoryTest extends UnitaryTestCase $this->database = $this->createMock(DatabaseInterface::class); $queryFactory = new QueryFactory('mysql'); - /** @noinspection ClassMockingCorrectnessInspection */ - /** @noinspection PhpUnitInvalidMockingEntityInspection */ - $this->accountFilterUser = - $this->getMockBuilder(AccountFilterUser::class) - ->enableOriginalConstructor() - ->enableProxyingToOriginalMethods() - ->setConstructorArgs( - [$this->application->getContext(), $this->config->getConfigData(), $queryFactory] - ) - ->getMock(); + $select = (new QueryFactory('mysql', QueryFactory::COMMON))->newSelect(); + $this->accountFilterUser = $this->createMock(AccountFilterUserInterface::class); + $this->accountFilterUser->method('buildFilter')->willReturn($select); + $this->accountFilterUser->method('buildFilterHistory')->willReturn($select); + $this->accountRepository = new AccountRepository( $this->database, $this->context, diff --git a/tests/SP/UnitaryTestCase.php b/tests/SP/UnitaryTestCase.php index 79baf328..867fb4ed 100644 --- a/tests/SP/UnitaryTestCase.php +++ b/tests/SP/UnitaryTestCase.php @@ -24,21 +24,17 @@ namespace SP\Tests; -use DG\BypassFinals; use Faker\Factory; use Faker\Generator; use PHPUnit\Framework\TestCase; use SP\Core\Application; use SP\Core\Context\ContextInterface; use SP\Core\Context\StatelessContext; -use SP\Core\Events\EventDispatcher; +use SP\Core\Events\EventDispatcherInterface; use SP\DataModel\ProfileData; use SP\Domain\Config\Ports\ConfigInterface; -use SP\Domain\Config\Services\ConfigBackupService; -use SP\Domain\Config\Services\ConfigFileService; use SP\Domain\User\Services\UserLoginResponse; -use SP\Infrastructure\File\FileCache; -use SP\Infrastructure\File\XmlHandler; +use SP\Tests\Generators\ConfigDataGenerator; /** * A class to test using a mocked Dependency Injection Container @@ -54,9 +50,6 @@ abstract class UnitaryTestCase extends TestCase { defined('APP_ROOT') || die(); - BypassFinals::enable(); - BypassFinals::setWhitelist([APP_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'*']); - self::$faker = Factory::create(); parent::setUpBeforeClass(); @@ -80,7 +73,7 @@ abstract class UnitaryTestCase extends TestCase } /** - * @throws \SP\Core\Exceptions\ConfigException + * @return \SP\Core\Application * @throws \SP\Core\Context\ContextException */ private function mockApplication(): Application @@ -97,13 +90,15 @@ abstract class UnitaryTestCase extends TestCase $this->context->setUserData($userLogin); $this->context->setUserProfile(new ProfileData()); - $config = new ConfigFileService( - $this->createStub(XmlHandler::class), - $this->createStub(FileCache::class), - $this->context, - $this->createStub(ConfigBackupService::class) - ); + $configData = ConfigDataGenerator::factory()->buildConfigData(); - return new Application($config, $this->createStub(EventDispatcher::class), $this->context); + $config = $this->createStub(ConfigInterface::class); + $config->method('getConfigData')->willReturn($configData); + + return new Application( + $config, + $this->createStub(EventDispatcherInterface::class), + $this->context + ); } }