From 5ad82b0667dc67745e9cd775a3ca0cdf68960bc3 Mon Sep 17 00:00:00 2001 From: "Eloy Lafuente (stronk7)" Date: Wed, 11 Oct 2023 18:50:09 +0200 Subject: [PATCH] Add tests to cover what is testable in SelfUpdate command Note that only helper methods can be tested for that command, not the execution of the update itself (it has to happen within a PHAR). And it doesn't make much sense to start mocking lots of stuff for that. Some integration tests @ CIS will be in charge of covering the real execution instead. Coming soon. --- src/Command/SelfUpdateCommand.php | 10 ++-- tests/Command/SelfUpdateCommandTest.php | 62 +++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 tests/Command/SelfUpdateCommandTest.php diff --git a/src/Command/SelfUpdateCommand.php b/src/Command/SelfUpdateCommand.php index 1a3322ac..86828470 100644 --- a/src/Command/SelfUpdateCommand.php +++ b/src/Command/SelfUpdateCommand.php @@ -93,13 +93,17 @@ protected function execute(InputInterface $input, OutputInterface $output): int } /** + * Calculate the full path where the old PHAR file will be backup (to be able to roll back to it). + * + * @param string|null $directory the directory where the backup will be stored + * * @return string */ - protected function getBackupPath(): string + protected function getBackupPath(?string $directory = null): string { - $directory = getenv('HOME'); + $directory = $directory ?? getenv('HOME'); // Default to $HOME as base directory if not provided. if (empty($directory) || !is_dir($directory)) { - throw new \RuntimeException('Your $HOME enviroment variable is either not set or is not a directory'); + throw new \RuntimeException("The {$directory} path is not an existing directory"); } $directory .= '/.moodle-plugin-ci'; diff --git a/tests/Command/SelfUpdateCommandTest.php b/tests/Command/SelfUpdateCommandTest.php new file mode 100644 index 00000000..1dd1046c --- /dev/null +++ b/tests/Command/SelfUpdateCommandTest.php @@ -0,0 +1,62 @@ +expectException(\RuntimeException::class); + + // Use reflection to test the protected method. + $method = new \ReflectionMethod($command, 'getBackupPath'); + $method->setAccessible(true); + $this->assertSame($rollBackFile, $method->invoke($command, $rollBackDir)); + } + + /** + * @covers \MoodlePluginCI\Command\SelfUpdateCommand::getBackupPath + */ + public function testGetBackupPathExists() + { + $command = new SelfUpdateCommand(); + + // Try with a existing directory. + $rollBackDir = sys_get_temp_dir() . '/existing_dir'; + (new Filesystem())->mkdir($rollBackDir); // Let's create the directory. + $rollBackFile = $rollBackDir . '/.moodle-plugin-ci/moodle-plugin-ci-old.phar'; + + // Use reflection to test the protected method. + $method = new \ReflectionMethod($command, 'getBackupPath'); + $method->setAccessible(true); + $this->assertSame($rollBackFile, $method->invoke($command, $rollBackDir)); + } +}