From c2cd15dac2bfaebe6d32f7649fbdedc07400fa08 Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Fri, 16 Oct 2020 13:34:59 +0200 Subject: Move utils classes to Shaarli\Helper namespace and folder --- tests/ApplicationUtilsTest.php | 414 --------------------------------- tests/FileUtilsTest.php | 196 ---------------- tests/helper/ApplicationUtilsTest.php | 415 ++++++++++++++++++++++++++++++++++ tests/helper/FileUtilsTest.php | 196 ++++++++++++++++ tests/security/BanManagerTest.php | 2 +- tests/utils/FakeApplicationUtils.php | 2 + tests/utils/ReferenceHistory.php | 2 +- 7 files changed, 615 insertions(+), 612 deletions(-) delete mode 100644 tests/ApplicationUtilsTest.php delete mode 100644 tests/FileUtilsTest.php create mode 100644 tests/helper/ApplicationUtilsTest.php create mode 100644 tests/helper/FileUtilsTest.php (limited to 'tests') diff --git a/tests/ApplicationUtilsTest.php b/tests/ApplicationUtilsTest.php deleted file mode 100644 index ac46cbf1..00000000 --- a/tests/ApplicationUtilsTest.php +++ /dev/null @@ -1,414 +0,0 @@ -assertEquals( - '0.5.4', - ApplicationUtils::getVersion( - 'https://raw.githubusercontent.com/shaarli/Shaarli/' - .'v0.5.4/shaarli_version.php', - $testTimeout - ) - ); - $this->assertRegExp( - self::$versionPattern, - ApplicationUtils::getVersion( - 'https://raw.githubusercontent.com/shaarli/Shaarli/' - .'latest/shaarli_version.php', - $testTimeout - ) - ); - } - - /** - * Attempt to retrieve the latest version from an invalid File - */ - public function testGetVersionCodeFromFile() - { - file_put_contents('sandbox/version.php', ''. PHP_EOL); - $this->assertEquals( - '1.2.3', - ApplicationUtils::getVersion('sandbox/version.php', 1) - ); - } - - /** - * Attempt to retrieve the latest version from an invalid File - */ - public function testGetVersionCodeInvalidFile() - { - $oldlog = ini_get('error_log'); - ini_set('error_log', '/dev/null'); - $this->assertFalse( - ApplicationUtils::getVersion('idontexist', 1) - ); - ini_set('error_log', $oldlog); - } - - /** - * Test update checks - the user is logged off - */ - public function testCheckUpdateLoggedOff() - { - $this->assertFalse( - ApplicationUtils::checkUpdate(self::$testVersion, 'null', 0, false, false) - ); - } - - /** - * Test update checks - the user has disabled updates - */ - public function testCheckUpdateUserDisabled() - { - $this->assertFalse( - ApplicationUtils::checkUpdate(self::$testVersion, 'null', 0, false, true) - ); - } - - /** - * A newer version is available - */ - public function testCheckUpdateNewVersionAvailable() - { - $newVersion = '1.8.3'; - FakeApplicationUtils::$VERSION_CODE = $newVersion; - - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - - $this->assertEquals($newVersion, $version); - } - - /** - * No available information about versions - */ - public function testCheckUpdateNewVersionUnavailable() - { - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - - $this->assertFalse($version); - } - - /** - * Test update checks - invalid Git branch - */ - public function testCheckUpdateInvalidGitBranch() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessageRegExp('/Invalid branch selected for updates/'); - - ApplicationUtils::checkUpdate('', 'null', 0, true, true, 'unstable'); - } - - /** - * Shaarli is up-to-date - */ - public function testCheckUpdateNewVersionUpToDate() - { - FakeApplicationUtils::$VERSION_CODE = self::$testVersion; - - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - - $this->assertFalse($version); - } - - /** - * Time-traveller's Shaarli - */ - public function testCheckUpdateNewVersionMaartiMcFly() - { - FakeApplicationUtils::$VERSION_CODE = '0.4.1'; - - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - - $this->assertFalse($version); - } - - /** - * The version has been checked recently and Shaarli is up-to-date - */ - public function testCheckUpdateNewVersionTwiceUpToDate() - { - FakeApplicationUtils::$VERSION_CODE = self::$testVersion; - - // Create the update file - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - - $this->assertFalse($version); - - // Reuse the update file - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - - $this->assertFalse($version); - } - - /** - * The version has been checked recently and Shaarli is outdated - */ - public function testCheckUpdateNewVersionTwiceOutdated() - { - $newVersion = '1.8.3'; - FakeApplicationUtils::$VERSION_CODE = $newVersion; - - // Create the update file - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - $this->assertEquals($newVersion, $version); - - // Reuse the update file - $version = FakeApplicationUtils::checkUpdate( - self::$testVersion, - self::$testUpdateFile, - 100, - true, - true - ); - $this->assertEquals($newVersion, $version); - } - - /** - * Check supported PHP versions - */ - public function testCheckSupportedPHPVersion() - { - $minVersion = '5.3'; - $this->assertTrue(ApplicationUtils::checkPHPVersion($minVersion, '5.4.32')); - $this->assertTrue(ApplicationUtils::checkPHPVersion($minVersion, '5.5')); - $this->assertTrue(ApplicationUtils::checkPHPVersion($minVersion, '5.6.10')); - } - - /** - * Check a unsupported PHP version - */ - public function testCheckSupportedPHPVersion51() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessageRegExp('/Your PHP version is obsolete/'); - - $this->assertTrue(ApplicationUtils::checkPHPVersion('5.3', '5.1.0')); - } - - /** - * Check another unsupported PHP version - */ - public function testCheckSupportedPHPVersion52() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessageRegExp('/Your PHP version is obsolete/'); - - $this->assertTrue(ApplicationUtils::checkPHPVersion('5.3', '5.2')); - } - - /** - * Checks resource permissions for the current Shaarli installation - */ - public function testCheckCurrentResourcePermissions() - { - $conf = new ConfigManager(''); - $conf->set('resource.thumbnails_cache', 'cache'); - $conf->set('resource.config', 'data/config.php'); - $conf->set('resource.data_dir', 'data'); - $conf->set('resource.datastore', 'data/datastore.php'); - $conf->set('resource.ban_file', 'data/ipbans.php'); - $conf->set('resource.log', 'data/log.txt'); - $conf->set('resource.page_cache', 'pagecache'); - $conf->set('resource.raintpl_tmp', 'tmp'); - $conf->set('resource.raintpl_tpl', 'tpl'); - $conf->set('resource.theme', 'default'); - $conf->set('resource.update_check', 'data/lastupdatecheck.txt'); - - $this->assertEquals( - array(), - ApplicationUtils::checkResourcePermissions($conf) - ); - } - - /** - * Checks resource permissions for a non-existent Shaarli installation - */ - public function testCheckCurrentResourcePermissionsErrors() - { - $conf = new ConfigManager(''); - $conf->set('resource.thumbnails_cache', 'null/cache'); - $conf->set('resource.config', 'null/data/config.php'); - $conf->set('resource.data_dir', 'null/data'); - $conf->set('resource.datastore', 'null/data/store.php'); - $conf->set('resource.ban_file', 'null/data/ipbans.php'); - $conf->set('resource.log', 'null/data/log.txt'); - $conf->set('resource.page_cache', 'null/pagecache'); - $conf->set('resource.raintpl_tmp', 'null/tmp'); - $conf->set('resource.raintpl_tpl', 'null/tpl'); - $conf->set('resource.raintpl_theme', 'null/tpl/default'); - $conf->set('resource.update_check', 'null/data/lastupdatecheck.txt'); - $this->assertEquals( - array( - '"null/tpl" directory is not readable', - '"null/tpl/default" directory is not readable', - '"null/cache" directory is not readable', - '"null/cache" directory is not writable', - '"null/data" directory is not readable', - '"null/data" directory is not writable', - '"null/pagecache" directory is not readable', - '"null/pagecache" directory is not writable', - '"null/tmp" directory is not readable', - '"null/tmp" directory is not writable' - ), - ApplicationUtils::checkResourcePermissions($conf) - ); - } - - /** - * Checks resource permissions in minimal mode. - */ - public function testCheckCurrentResourcePermissionsErrorsMinimalMode(): void - { - $conf = new ConfigManager(''); - $conf->set('resource.thumbnails_cache', 'null/cache'); - $conf->set('resource.config', 'null/data/config.php'); - $conf->set('resource.data_dir', 'null/data'); - $conf->set('resource.datastore', 'null/data/store.php'); - $conf->set('resource.ban_file', 'null/data/ipbans.php'); - $conf->set('resource.log', 'null/data/log.txt'); - $conf->set('resource.page_cache', 'null/pagecache'); - $conf->set('resource.raintpl_tmp', 'null/tmp'); - $conf->set('resource.raintpl_tpl', 'null/tpl'); - $conf->set('resource.raintpl_theme', 'null/tpl/default'); - $conf->set('resource.update_check', 'null/data/lastupdatecheck.txt'); - - static::assertSame( - [ - '"null/tpl" directory is not readable', - '"null/tpl/default" directory is not readable', - '"null/tmp" directory is not readable', - '"null/tmp" directory is not writable' - ], - ApplicationUtils::checkResourcePermissions($conf, true) - ); - } - - /** - * Check update with 'dev' as curent version (master branch). - * It should always return false. - */ - public function testCheckUpdateDev() - { - $this->assertFalse( - ApplicationUtils::checkUpdate('dev', self::$testUpdateFile, 100, true, true) - ); - } - - /** - * Basic test of getPhpExtensionsRequirement() - */ - public function testGetPhpExtensionsRequirementSimple(): void - { - static::assertCount(8, ApplicationUtils::getPhpExtensionsRequirement()); - static::assertSame([ - 'name' => 'json', - 'required' => true, - 'desc' => 'Configuration parsing', - 'loaded' => true, - ], ApplicationUtils::getPhpExtensionsRequirement()[0]); - } - - /** - * Test getPhpEol with a known version: 7.4 -> 2022 - */ - public function testGetKnownPhpEol(): void - { - static::assertSame('2022-11-28', ApplicationUtils::getPhpEol('7.4.7')); - } - - /** - * Test getPhpEol with an unknown version: 7.4 -> 2022 - */ - public function testGetUnknownPhpEol(): void - { - static::assertSame( - (((int) (new \DateTime())->format('Y')) + 2) . (new \DateTime())->format('-m-d'), - ApplicationUtils::getPhpEol('7.51.34') - ); - } -} diff --git a/tests/FileUtilsTest.php b/tests/FileUtilsTest.php deleted file mode 100644 index 3384504a..00000000 --- a/tests/FileUtilsTest.php +++ /dev/null @@ -1,196 +0,0 @@ -assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); - $this->assertTrue(startsWith(file_get_contents(self::$file), 'assertEquals($data, FileUtils::readFlatDB(self::$file)); - - $data = 0; - $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); - $this->assertEquals($data, FileUtils::readFlatDB(self::$file)); - - $data = null; - $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); - $this->assertEquals($data, FileUtils::readFlatDB(self::$file)); - - $data = false; - $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); - $this->assertEquals($data, FileUtils::readFlatDB(self::$file)); - } - - /** - * File not writable: raise an exception. - */ - public function testWriteWithoutPermission() - { - $this->expectException(\Shaarli\Exceptions\IOException::class); - $this->expectExceptionMessage('Error accessing "sandbox/flat.db"'); - - touch(self::$file); - chmod(self::$file, 0440); - FileUtils::writeFlatDB(self::$file, null); - } - - /** - * Folder non existent: raise an exception. - */ - public function testWriteFolderDoesNotExist() - { - $this->expectException(\Shaarli\Exceptions\IOException::class); - $this->expectExceptionMessage('Error accessing "nopefolder"'); - - FileUtils::writeFlatDB('nopefolder/file', null); - } - - /** - * Folder non writable: raise an exception. - */ - public function testWriteFolderPermission() - { - $this->expectException(\Shaarli\Exceptions\IOException::class); - $this->expectExceptionMessage('Error accessing "sandbox"'); - - chmod(dirname(self::$file), 0555); - try { - FileUtils::writeFlatDB(self::$file, null); - } catch (Exception $e) { - chmod(dirname(self::$file), 0755); - throw $e; - } - } - - /** - * Read non existent file, use default parameter. - */ - public function testReadNotExistentFile() - { - $this->assertEquals(null, FileUtils::readFlatDB(self::$file)); - $this->assertEquals(['test'], FileUtils::readFlatDB(self::$file, ['test'])); - } - - /** - * Read non readable file, use default parameter. - */ - public function testReadNotReadable() - { - touch(self::$file); - chmod(self::$file, 0220); - $this->assertEquals(null, FileUtils::readFlatDB(self::$file)); - $this->assertEquals(['test'], FileUtils::readFlatDB(self::$file, ['test'])); - } - - /** - * Test clearFolder with self delete and excluded files - */ - public function testClearFolderSelfDeleteWithExclusion(): void - { - FileUtils::clearFolder('sandbox', true, ['file2']); - - static::assertFileExists('sandbox/folder1/file2'); - static::assertFileExists('sandbox/folder1'); - static::assertFileExists('sandbox/file2'); - static::assertFileExists('sandbox'); - - static::assertFileNotExists('sandbox/folder1/file1'); - static::assertFileNotExists('sandbox/file1'); - static::assertFileNotExists('sandbox/folder3'); - } - - /** - * Test clearFolder with self delete and excluded files - */ - public function testClearFolderSelfDeleteWithoutExclusion(): void - { - FileUtils::clearFolder('sandbox', true); - - static::assertFileNotExists('sandbox'); - } - - /** - * Test clearFolder with self delete and excluded files - */ - public function testClearFolderNoSelfDeleteWithoutExclusion(): void - { - FileUtils::clearFolder('sandbox', false); - - static::assertFileExists('sandbox'); - - // 2 because '.' and '..' - static::assertCount(2, new \DirectoryIterator('sandbox')); - } - - /** - * Test clearFolder on a file instead of a folder - */ - public function testClearFolderOnANonDirectory(): void - { - $this->expectException(IOException::class); - $this->expectExceptionMessage('Provided path is not a directory.'); - - FileUtils::clearFolder('sandbox/file1', false); - } - - /** - * Test clearFolder on a file instead of a folder - */ - public function testClearFolderOutsideOfShaarliDirectory(): void - { - $this->expectException(IOException::class); - $this->expectExceptionMessage('Trying to delete a folder outside of Shaarli path.'); - - - FileUtils::clearFolder('/tmp/shaarli-to-delete', true); - } -} diff --git a/tests/helper/ApplicationUtilsTest.php b/tests/helper/ApplicationUtilsTest.php new file mode 100644 index 00000000..654857b9 --- /dev/null +++ b/tests/helper/ApplicationUtilsTest.php @@ -0,0 +1,415 @@ +assertEquals( + '0.5.4', + ApplicationUtils::getVersion( + 'https://raw.githubusercontent.com/shaarli/Shaarli/' + .'v0.5.4/shaarli_version.php', + $testTimeout + ) + ); + $this->assertRegExp( + self::$versionPattern, + ApplicationUtils::getVersion( + 'https://raw.githubusercontent.com/shaarli/Shaarli/' + .'latest/shaarli_version.php', + $testTimeout + ) + ); + } + + /** + * Attempt to retrieve the latest version from an invalid File + */ + public function testGetVersionCodeFromFile() + { + file_put_contents('sandbox/version.php', ''. PHP_EOL); + $this->assertEquals( + '1.2.3', + ApplicationUtils::getVersion('sandbox/version.php', 1) + ); + } + + /** + * Attempt to retrieve the latest version from an invalid File + */ + public function testGetVersionCodeInvalidFile() + { + $oldlog = ini_get('error_log'); + ini_set('error_log', '/dev/null'); + $this->assertFalse( + ApplicationUtils::getVersion('idontexist', 1) + ); + ini_set('error_log', $oldlog); + } + + /** + * Test update checks - the user is logged off + */ + public function testCheckUpdateLoggedOff() + { + $this->assertFalse( + ApplicationUtils::checkUpdate(self::$testVersion, 'null', 0, false, false) + ); + } + + /** + * Test update checks - the user has disabled updates + */ + public function testCheckUpdateUserDisabled() + { + $this->assertFalse( + ApplicationUtils::checkUpdate(self::$testVersion, 'null', 0, false, true) + ); + } + + /** + * A newer version is available + */ + public function testCheckUpdateNewVersionAvailable() + { + $newVersion = '1.8.3'; + FakeApplicationUtils::$VERSION_CODE = $newVersion; + + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + + $this->assertEquals($newVersion, $version); + } + + /** + * No available information about versions + */ + public function testCheckUpdateNewVersionUnavailable() + { + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + + $this->assertFalse($version); + } + + /** + * Test update checks - invalid Git branch + */ + public function testCheckUpdateInvalidGitBranch() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessageRegExp('/Invalid branch selected for updates/'); + + ApplicationUtils::checkUpdate('', 'null', 0, true, true, 'unstable'); + } + + /** + * Shaarli is up-to-date + */ + public function testCheckUpdateNewVersionUpToDate() + { + FakeApplicationUtils::$VERSION_CODE = self::$testVersion; + + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + + $this->assertFalse($version); + } + + /** + * Time-traveller's Shaarli + */ + public function testCheckUpdateNewVersionMaartiMcFly() + { + FakeApplicationUtils::$VERSION_CODE = '0.4.1'; + + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + + $this->assertFalse($version); + } + + /** + * The version has been checked recently and Shaarli is up-to-date + */ + public function testCheckUpdateNewVersionTwiceUpToDate() + { + FakeApplicationUtils::$VERSION_CODE = self::$testVersion; + + // Create the update file + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + + $this->assertFalse($version); + + // Reuse the update file + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + + $this->assertFalse($version); + } + + /** + * The version has been checked recently and Shaarli is outdated + */ + public function testCheckUpdateNewVersionTwiceOutdated() + { + $newVersion = '1.8.3'; + FakeApplicationUtils::$VERSION_CODE = $newVersion; + + // Create the update file + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + $this->assertEquals($newVersion, $version); + + // Reuse the update file + $version = FakeApplicationUtils::checkUpdate( + self::$testVersion, + self::$testUpdateFile, + 100, + true, + true + ); + $this->assertEquals($newVersion, $version); + } + + /** + * Check supported PHP versions + */ + public function testCheckSupportedPHPVersion() + { + $minVersion = '5.3'; + $this->assertTrue(ApplicationUtils::checkPHPVersion($minVersion, '5.4.32')); + $this->assertTrue(ApplicationUtils::checkPHPVersion($minVersion, '5.5')); + $this->assertTrue(ApplicationUtils::checkPHPVersion($minVersion, '5.6.10')); + } + + /** + * Check a unsupported PHP version + */ + public function testCheckSupportedPHPVersion51() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessageRegExp('/Your PHP version is obsolete/'); + + $this->assertTrue(ApplicationUtils::checkPHPVersion('5.3', '5.1.0')); + } + + /** + * Check another unsupported PHP version + */ + public function testCheckSupportedPHPVersion52() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessageRegExp('/Your PHP version is obsolete/'); + + $this->assertTrue(ApplicationUtils::checkPHPVersion('5.3', '5.2')); + } + + /** + * Checks resource permissions for the current Shaarli installation + */ + public function testCheckCurrentResourcePermissions() + { + $conf = new ConfigManager(''); + $conf->set('resource.thumbnails_cache', 'cache'); + $conf->set('resource.config', 'data/config.php'); + $conf->set('resource.data_dir', 'data'); + $conf->set('resource.datastore', 'data/datastore.php'); + $conf->set('resource.ban_file', 'data/ipbans.php'); + $conf->set('resource.log', 'data/log.txt'); + $conf->set('resource.page_cache', 'pagecache'); + $conf->set('resource.raintpl_tmp', 'tmp'); + $conf->set('resource.raintpl_tpl', 'tpl'); + $conf->set('resource.theme', 'default'); + $conf->set('resource.update_check', 'data/lastupdatecheck.txt'); + + $this->assertEquals( + array(), + ApplicationUtils::checkResourcePermissions($conf) + ); + } + + /** + * Checks resource permissions for a non-existent Shaarli installation + */ + public function testCheckCurrentResourcePermissionsErrors() + { + $conf = new ConfigManager(''); + $conf->set('resource.thumbnails_cache', 'null/cache'); + $conf->set('resource.config', 'null/data/config.php'); + $conf->set('resource.data_dir', 'null/data'); + $conf->set('resource.datastore', 'null/data/store.php'); + $conf->set('resource.ban_file', 'null/data/ipbans.php'); + $conf->set('resource.log', 'null/data/log.txt'); + $conf->set('resource.page_cache', 'null/pagecache'); + $conf->set('resource.raintpl_tmp', 'null/tmp'); + $conf->set('resource.raintpl_tpl', 'null/tpl'); + $conf->set('resource.raintpl_theme', 'null/tpl/default'); + $conf->set('resource.update_check', 'null/data/lastupdatecheck.txt'); + $this->assertEquals( + array( + '"null/tpl" directory is not readable', + '"null/tpl/default" directory is not readable', + '"null/cache" directory is not readable', + '"null/cache" directory is not writable', + '"null/data" directory is not readable', + '"null/data" directory is not writable', + '"null/pagecache" directory is not readable', + '"null/pagecache" directory is not writable', + '"null/tmp" directory is not readable', + '"null/tmp" directory is not writable' + ), + ApplicationUtils::checkResourcePermissions($conf) + ); + } + + /** + * Checks resource permissions in minimal mode. + */ + public function testCheckCurrentResourcePermissionsErrorsMinimalMode(): void + { + $conf = new ConfigManager(''); + $conf->set('resource.thumbnails_cache', 'null/cache'); + $conf->set('resource.config', 'null/data/config.php'); + $conf->set('resource.data_dir', 'null/data'); + $conf->set('resource.datastore', 'null/data/store.php'); + $conf->set('resource.ban_file', 'null/data/ipbans.php'); + $conf->set('resource.log', 'null/data/log.txt'); + $conf->set('resource.page_cache', 'null/pagecache'); + $conf->set('resource.raintpl_tmp', 'null/tmp'); + $conf->set('resource.raintpl_tpl', 'null/tpl'); + $conf->set('resource.raintpl_theme', 'null/tpl/default'); + $conf->set('resource.update_check', 'null/data/lastupdatecheck.txt'); + + static::assertSame( + [ + '"null/tpl" directory is not readable', + '"null/tpl/default" directory is not readable', + '"null/tmp" directory is not readable', + '"null/tmp" directory is not writable' + ], + ApplicationUtils::checkResourcePermissions($conf, true) + ); + } + + /** + * Check update with 'dev' as curent version (master branch). + * It should always return false. + */ + public function testCheckUpdateDev() + { + $this->assertFalse( + ApplicationUtils::checkUpdate('dev', self::$testUpdateFile, 100, true, true) + ); + } + + /** + * Basic test of getPhpExtensionsRequirement() + */ + public function testGetPhpExtensionsRequirementSimple(): void + { + static::assertCount(8, ApplicationUtils::getPhpExtensionsRequirement()); + static::assertSame([ + 'name' => 'json', + 'required' => true, + 'desc' => 'Configuration parsing', + 'loaded' => true, + ], ApplicationUtils::getPhpExtensionsRequirement()[0]); + } + + /** + * Test getPhpEol with a known version: 7.4 -> 2022 + */ + public function testGetKnownPhpEol(): void + { + static::assertSame('2022-11-28', ApplicationUtils::getPhpEol('7.4.7')); + } + + /** + * Test getPhpEol with an unknown version: 7.4 -> 2022 + */ + public function testGetUnknownPhpEol(): void + { + static::assertSame( + (((int) (new \DateTime())->format('Y')) + 2) . (new \DateTime())->format('-m-d'), + ApplicationUtils::getPhpEol('7.51.34') + ); + } +} diff --git a/tests/helper/FileUtilsTest.php b/tests/helper/FileUtilsTest.php new file mode 100644 index 00000000..948e46d1 --- /dev/null +++ b/tests/helper/FileUtilsTest.php @@ -0,0 +1,196 @@ +assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); + $this->assertTrue(startsWith(file_get_contents(self::$file), 'assertEquals($data, FileUtils::readFlatDB(self::$file)); + + $data = 0; + $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); + $this->assertEquals($data, FileUtils::readFlatDB(self::$file)); + + $data = null; + $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); + $this->assertEquals($data, FileUtils::readFlatDB(self::$file)); + + $data = false; + $this->assertTrue(FileUtils::writeFlatDB(self::$file, $data) > 0); + $this->assertEquals($data, FileUtils::readFlatDB(self::$file)); + } + + /** + * File not writable: raise an exception. + */ + public function testWriteWithoutPermission() + { + $this->expectException(\Shaarli\Exceptions\IOException::class); + $this->expectExceptionMessage('Error accessing "sandbox/flat.db"'); + + touch(self::$file); + chmod(self::$file, 0440); + FileUtils::writeFlatDB(self::$file, null); + } + + /** + * Folder non existent: raise an exception. + */ + public function testWriteFolderDoesNotExist() + { + $this->expectException(\Shaarli\Exceptions\IOException::class); + $this->expectExceptionMessage('Error accessing "nopefolder"'); + + FileUtils::writeFlatDB('nopefolder/file', null); + } + + /** + * Folder non writable: raise an exception. + */ + public function testWriteFolderPermission() + { + $this->expectException(\Shaarli\Exceptions\IOException::class); + $this->expectExceptionMessage('Error accessing "sandbox"'); + + chmod(dirname(self::$file), 0555); + try { + FileUtils::writeFlatDB(self::$file, null); + } catch (Exception $e) { + chmod(dirname(self::$file), 0755); + throw $e; + } + } + + /** + * Read non existent file, use default parameter. + */ + public function testReadNotExistentFile() + { + $this->assertEquals(null, FileUtils::readFlatDB(self::$file)); + $this->assertEquals(['test'], FileUtils::readFlatDB(self::$file, ['test'])); + } + + /** + * Read non readable file, use default parameter. + */ + public function testReadNotReadable() + { + touch(self::$file); + chmod(self::$file, 0220); + $this->assertEquals(null, FileUtils::readFlatDB(self::$file)); + $this->assertEquals(['test'], FileUtils::readFlatDB(self::$file, ['test'])); + } + + /** + * Test clearFolder with self delete and excluded files + */ + public function testClearFolderSelfDeleteWithExclusion(): void + { + FileUtils::clearFolder('sandbox', true, ['file2']); + + static::assertFileExists('sandbox/folder1/file2'); + static::assertFileExists('sandbox/folder1'); + static::assertFileExists('sandbox/file2'); + static::assertFileExists('sandbox'); + + static::assertFileNotExists('sandbox/folder1/file1'); + static::assertFileNotExists('sandbox/file1'); + static::assertFileNotExists('sandbox/folder3'); + } + + /** + * Test clearFolder with self delete and excluded files + */ + public function testClearFolderSelfDeleteWithoutExclusion(): void + { + FileUtils::clearFolder('sandbox', true); + + static::assertFileNotExists('sandbox'); + } + + /** + * Test clearFolder with self delete and excluded files + */ + public function testClearFolderNoSelfDeleteWithoutExclusion(): void + { + FileUtils::clearFolder('sandbox', false); + + static::assertFileExists('sandbox'); + + // 2 because '.' and '..' + static::assertCount(2, new \DirectoryIterator('sandbox')); + } + + /** + * Test clearFolder on a file instead of a folder + */ + public function testClearFolderOnANonDirectory(): void + { + $this->expectException(IOException::class); + $this->expectExceptionMessage('Provided path is not a directory.'); + + FileUtils::clearFolder('sandbox/file1', false); + } + + /** + * Test clearFolder on a file instead of a folder + */ + public function testClearFolderOutsideOfShaarliDirectory(): void + { + $this->expectException(IOException::class); + $this->expectExceptionMessage('Trying to delete a folder outside of Shaarli path.'); + + + FileUtils::clearFolder('/tmp/shaarli-to-delete', true); + } +} diff --git a/tests/security/BanManagerTest.php b/tests/security/BanManagerTest.php index 22aa8666..29d2791b 100644 --- a/tests/security/BanManagerTest.php +++ b/tests/security/BanManagerTest.php @@ -4,7 +4,7 @@ namespace Shaarli\Security; use Psr\Log\LoggerInterface; -use Shaarli\FileUtils; +use Shaarli\Helper\FileUtils; use Shaarli\TestCase; /** diff --git a/tests/utils/FakeApplicationUtils.php b/tests/utils/FakeApplicationUtils.php index de83d598..d5289ede 100644 --- a/tests/utils/FakeApplicationUtils.php +++ b/tests/utils/FakeApplicationUtils.php @@ -2,6 +2,8 @@ namespace Shaarli; +use Shaarli\Helper\ApplicationUtils; + /** * Fake ApplicationUtils class to avoid HTTP requests */ diff --git a/tests/utils/ReferenceHistory.php b/tests/utils/ReferenceHistory.php index 516c9f51..aed5d2cf 100644 --- a/tests/utils/ReferenceHistory.php +++ b/tests/utils/ReferenceHistory.php @@ -1,6 +1,6 @@ Date: Fri, 16 Oct 2020 11:50:53 +0200 Subject: Feature: add weekly and monthly view/RSS feed for daily page - Heavy refactoring of DailyController - Add a banner like in tag cloud to display monthly and weekly links - Translations: t() now supports variables with optional first letter uppercase Fixes #160 --- tests/bookmark/BookmarkFileServiceTest.php | 124 +++++-- .../controller/visitor/DailyControllerTest.php | 412 ++++++++++++++++----- tests/helper/DailyPageHelperTest.php | 262 +++++++++++++ 3 files changed, 677 insertions(+), 121 deletions(-) create mode 100644 tests/helper/DailyPageHelperTest.php (limited to 'tests') diff --git a/tests/bookmark/BookmarkFileServiceTest.php b/tests/bookmark/BookmarkFileServiceTest.php index 47970117..8e0ff8dd 100644 --- a/tests/bookmark/BookmarkFileServiceTest.php +++ b/tests/bookmark/BookmarkFileServiceTest.php @@ -685,22 +685,6 @@ class BookmarkFileServiceTest extends TestCase $this->assertEquals(0, $linkDB->count()); } - /** - * List the days for which bookmarks have been posted - */ - public function testDays() - { - $this->assertSame( - ['20100309', '20100310', '20121206', '20121207', '20130614', '20150310'], - $this->publicLinkDB->days() - ); - - $this->assertSame( - ['20100309', '20100310', '20121206', '20121207', '20130614', '20141125', '20150310'], - $this->privateLinkDB->days() - ); - } - /** * The URL corresponds to an existing entry in the DB */ @@ -1074,33 +1058,105 @@ class BookmarkFileServiceTest extends TestCase } /** - * Test filterDay while logged in + * Test find by dates in the middle of the datastore (sorted by dates) with a single bookmark as a result. */ - public function testFilterDayLoggedIn(): void + public function testFilterByDateMidTimePeriodSingleBookmark(): void { - $bookmarks = $this->privateLinkDB->filterDay('20121206'); - $expectedIds = [4, 9, 1, 0]; + $bookmarks = $this->privateLinkDB->findByDate( + DateTime::createFromFormat('Ymd_His', '20121206_150000'), + DateTime::createFromFormat('Ymd_His', '20121206_160000'), + $before, + $after + ); - static::assertCount(4, $bookmarks); - foreach ($bookmarks as $bookmark) { - $i = ($i ?? -1) + 1; - static::assertSame($expectedIds[$i], $bookmark->getId()); - } + static::assertCount(1, $bookmarks); + + static::assertSame(9, $bookmarks[0]->getId()); + static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_142300'), $before); + static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_172539'), $after); } /** - * Test filterDay while logged out + * Test find by dates in the middle of the datastore (sorted by dates) with a multiple bookmarks as a result. */ - public function testFilterDayLoggedOut(): void + public function testFilterByDateMidTimePeriodMultipleBookmarks(): void { - $bookmarks = $this->publicLinkDB->filterDay('20121206'); - $expectedIds = [4, 9, 1]; + $bookmarks = $this->privateLinkDB->findByDate( + DateTime::createFromFormat('Ymd_His', '20121206_150000'), + DateTime::createFromFormat('Ymd_His', '20121206_180000'), + $before, + $after + ); - static::assertCount(3, $bookmarks); - foreach ($bookmarks as $bookmark) { - $i = ($i ?? -1) + 1; - static::assertSame($expectedIds[$i], $bookmark->getId()); - } + static::assertCount(2, $bookmarks); + + static::assertSame(1, $bookmarks[0]->getId()); + static::assertSame(9, $bookmarks[1]->getId()); + static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_142300'), $before); + static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_182539'), $after); + } + + /** + * Test find by dates at the end of the datastore (sorted by dates). + */ + public function testFilterByDateLastTimePeriod(): void + { + $after = new DateTime(); + $bookmarks = $this->privateLinkDB->findByDate( + DateTime::createFromFormat('Ymd_His', '20150310_114640'), + DateTime::createFromFormat('Ymd_His', '20450101_010101'), + $before, + $after + ); + + static::assertCount(1, $bookmarks); + + static::assertSame(41, $bookmarks[0]->getId()); + static::assertEquals(DateTime::createFromFormat('Ymd_His', '20150310_114633'), $before); + static::assertNull($after); + } + + /** + * Test find by dates at the beginning of the datastore (sorted by dates). + */ + public function testFilterByDateFirstTimePeriod(): void + { + $before = new DateTime(); + $bookmarks = $this->privateLinkDB->findByDate( + DateTime::createFromFormat('Ymd_His', '20000101_101010'), + DateTime::createFromFormat('Ymd_His', '20100309_110000'), + $before, + $after + ); + + static::assertCount(1, $bookmarks); + + static::assertSame(11, $bookmarks[0]->getId()); + static::assertNull($before); + static::assertEquals(DateTime::createFromFormat('Ymd_His', '20100310_101010'), $after); + } + + /** + * Test getLatest with a sticky bookmark: it should be ignored and return the latest by creation date instead. + */ + public function testGetLatestWithSticky(): void + { + $bookmark = $this->publicLinkDB->getLatest(); + + static::assertSame(41, $bookmark->getId()); + } + + /** + * Test getLatest with a sticky bookmark: it should be ignored and return the latest by creation date instead. + */ + public function testGetLatestEmptyDatastore(): void + { + unlink($this->conf->get('resource.datastore')); + $this->publicLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, false); + + $bookmark = $this->publicLinkDB->getLatest(); + + static::assertNull($bookmark); } /** diff --git a/tests/front/controller/visitor/DailyControllerTest.php b/tests/front/controller/visitor/DailyControllerTest.php index fc78bc13..758e7219 100644 --- a/tests/front/controller/visitor/DailyControllerTest.php +++ b/tests/front/controller/visitor/DailyControllerTest.php @@ -28,52 +28,49 @@ class DailyControllerTest extends TestCase public function testValidIndexControllerInvokeDefault(): void { $currentDay = new \DateTimeImmutable('2020-05-13'); + $previousDate = new \DateTime('2 days ago 00:00:00'); + $nextDate = new \DateTime('today 00:00:00'); $request = $this->createMock(Request::class); - $request->method('getQueryParam')->willReturn($currentDay->format('Ymd')); + $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string { + return $key === 'day' ? $currentDay->format('Ymd') : null; + }); $response = new Response(); // Save RainTPL assigned variables $assignedVariables = []; $this->assignTemplateVars($assignedVariables); - // Links dataset: 2 links with thumbnails - $this->container->bookmarkService - ->expects(static::once()) - ->method('days') - ->willReturnCallback(function () use ($currentDay): array { - return [ - '20200510', - $currentDay->format('Ymd'), - '20200516', - ]; - }) - ; $this->container->bookmarkService ->expects(static::once()) - ->method('filterDay') - ->willReturnCallback(function (): array { - return [ - (new Bookmark()) - ->setId(1) - ->setUrl('http://url.tld') - ->setTitle(static::generateString(50)) - ->setDescription(static::generateString(500)) - , - (new Bookmark()) - ->setId(2) - ->setUrl('http://url2.tld') - ->setTitle(static::generateString(50)) - ->setDescription(static::generateString(500)) - , - (new Bookmark()) - ->setId(3) - ->setUrl('http://url3.tld') - ->setTitle(static::generateString(50)) - ->setDescription(static::generateString(500)) - , - ]; - }) + ->method('findByDate') + ->willReturnCallback( + function ($from, $to, &$previous, &$next) use ($currentDay, $previousDate, $nextDate): array { + $previous = $previousDate; + $next = $nextDate; + + return [ + (new Bookmark()) + ->setId(1) + ->setUrl('http://url.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + (new Bookmark()) + ->setId(2) + ->setUrl('http://url2.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + (new Bookmark()) + ->setId(3) + ->setUrl('http://url3.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + ]; + } + ) ; // Make sure that PluginManager hook is triggered @@ -81,20 +78,22 @@ class DailyControllerTest extends TestCase ->expects(static::atLeastOnce()) ->method('executeHooks') ->withConsecutive(['render_daily']) - ->willReturnCallback(function (string $hook, array $data, array $param) use ($currentDay): array { - if ('render_daily' === $hook) { - static::assertArrayHasKey('linksToDisplay', $data); - static::assertCount(3, $data['linksToDisplay']); - static::assertSame(1, $data['linksToDisplay'][0]['id']); - static::assertSame($currentDay->getTimestamp(), $data['day']); - static::assertSame('20200510', $data['previousday']); - static::assertSame('20200516', $data['nextday']); - - static::assertArrayHasKey('loggedin', $param); + ->willReturnCallback( + function (string $hook, array $data, array $param) use ($currentDay, $previousDate, $nextDate): array { + if ('render_daily' === $hook) { + static::assertArrayHasKey('linksToDisplay', $data); + static::assertCount(3, $data['linksToDisplay']); + static::assertSame(1, $data['linksToDisplay'][0]['id']); + static::assertSame($currentDay->getTimestamp(), $data['day']); + static::assertSame($previousDate->format('Ymd'), $data['previousday']); + static::assertSame($nextDate->format('Ymd'), $data['nextday']); + + static::assertArrayHasKey('loggedin', $param); + } + + return $data; } - - return $data; - }) + ) ; $result = $this->controller->index($request, $response); @@ -107,6 +106,11 @@ class DailyControllerTest extends TestCase ); static::assertEquals($currentDay, $assignedVariables['dayDate']); static::assertEquals($currentDay->getTimestamp(), $assignedVariables['day']); + static::assertSame($previousDate->format('Ymd'), $assignedVariables['previousday']); + static::assertSame($nextDate->format('Ymd'), $assignedVariables['nextday']); + static::assertSame('day', $assignedVariables['type']); + static::assertSame('May 13, 2020', $assignedVariables['dayDesc']); + static::assertSame('Daily', $assignedVariables['localizedType']); static::assertCount(3, $assignedVariables['linksToDisplay']); $link = $assignedVariables['linksToDisplay'][0]; @@ -171,26 +175,19 @@ class DailyControllerTest extends TestCase $currentDay = new \DateTimeImmutable('2020-05-13'); $request = $this->createMock(Request::class); + $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string { + return $key === 'day' ? $currentDay->format('Ymd') : null; + }); $response = new Response(); // Save RainTPL assigned variables $assignedVariables = []; $this->assignTemplateVars($assignedVariables); - // Links dataset: 2 links with thumbnails $this->container->bookmarkService ->expects(static::once()) - ->method('days') + ->method('findByDate') ->willReturnCallback(function () use ($currentDay): array { - return [ - $currentDay->format($currentDay->format('Ymd')), - ]; - }) - ; - $this->container->bookmarkService - ->expects(static::once()) - ->method('filterDay') - ->willReturnCallback(function (): array { return [ (new Bookmark()) ->setId(1) @@ -250,20 +247,10 @@ class DailyControllerTest extends TestCase $assignedVariables = []; $this->assignTemplateVars($assignedVariables); - // Links dataset: 2 links with thumbnails $this->container->bookmarkService ->expects(static::once()) - ->method('days') + ->method('findByDate') ->willReturnCallback(function () use ($currentDay): array { - return [ - $currentDay->format($currentDay->format('Ymd')), - ]; - }) - ; - $this->container->bookmarkService - ->expects(static::once()) - ->method('filterDay') - ->willReturnCallback(function (): array { return [ (new Bookmark())->setId(1)->setUrl('http://url.tld')->setTitle('title'), (new Bookmark()) @@ -320,14 +307,7 @@ class DailyControllerTest extends TestCase // Links dataset: 2 links with thumbnails $this->container->bookmarkService ->expects(static::once()) - ->method('days') - ->willReturnCallback(function (): array { - return []; - }) - ; - $this->container->bookmarkService - ->expects(static::once()) - ->method('filterDay') + ->method('findByDate') ->willReturnCallback(function (): array { return []; }) @@ -347,7 +327,7 @@ class DailyControllerTest extends TestCase static::assertSame(200, $result->getStatusCode()); static::assertSame('daily', (string) $result->getBody()); static::assertCount(0, $assignedVariables['linksToDisplay']); - static::assertSame('Today', $assignedVariables['dayDesc']); + static::assertSame('Today - ' . (new \DateTime())->format('F d, Y'), $assignedVariables['dayDesc']); static::assertEquals((new \DateTime())->setTime(0, 0)->getTimestamp(), $assignedVariables['day']); static::assertEquals((new \DateTime())->setTime(0, 0), $assignedVariables['dayDate']); } @@ -361,6 +341,7 @@ class DailyControllerTest extends TestCase new \DateTimeImmutable('2020-05-17'), new \DateTimeImmutable('2020-05-15'), new \DateTimeImmutable('2020-05-13'), + new \DateTimeImmutable('+1 month'), ]; $request = $this->createMock(Request::class); @@ -371,6 +352,7 @@ class DailyControllerTest extends TestCase (new Bookmark())->setId(2)->setCreated($dates[1])->setUrl('http://domain.tld/2'), (new Bookmark())->setId(3)->setCreated($dates[1])->setUrl('http://domain.tld/3'), (new Bookmark())->setId(4)->setCreated($dates[2])->setUrl('http://domain.tld/4'), + (new Bookmark())->setId(5)->setCreated($dates[3])->setUrl('http://domain.tld/5'), ]); $this->container->pageCacheManager @@ -397,13 +379,14 @@ class DailyControllerTest extends TestCase static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']); static::assertSame('http://shaarli/subfolder/daily-rss', $assignedVariables['page_url']); static::assertFalse($assignedVariables['hide_timestamps']); - static::assertCount(2, $assignedVariables['days']); + static::assertCount(3, $assignedVariables['days']); $day = $assignedVariables['days'][$dates[0]->format('Ymd')]; + $date = $dates[0]->setTime(23, 59, 59); - static::assertEquals($dates[0], $day['date']); - static::assertSame($dates[0]->format(\DateTime::RSS), $day['date_rss']); - static::assertSame(format_date($dates[0], false), $day['date_human']); + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame(format_date($date, false), $day['date_human']); static::assertSame('http://shaarli/subfolder/daily?day='. $dates[0]->format('Ymd'), $day['absolute_url']); static::assertCount(1, $day['links']); static::assertSame(1, $day['links'][0]['id']); @@ -411,10 +394,11 @@ class DailyControllerTest extends TestCase static::assertEquals($dates[0], $day['links'][0]['created']); $day = $assignedVariables['days'][$dates[1]->format('Ymd')]; + $date = $dates[1]->setTime(23, 59, 59); - static::assertEquals($dates[1], $day['date']); - static::assertSame($dates[1]->format(\DateTime::RSS), $day['date_rss']); - static::assertSame(format_date($dates[1], false), $day['date_human']); + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame(format_date($date, false), $day['date_human']); static::assertSame('http://shaarli/subfolder/daily?day='. $dates[1]->format('Ymd'), $day['absolute_url']); static::assertCount(2, $day['links']); @@ -424,6 +408,18 @@ class DailyControllerTest extends TestCase static::assertSame(3, $day['links'][1]['id']); static::assertSame('http://domain.tld/3', $day['links'][1]['url']); static::assertEquals($dates[1], $day['links'][1]['created']); + + $day = $assignedVariables['days'][$dates[2]->format('Ymd')]; + $date = $dates[2]->setTime(23, 59, 59); + + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame(format_date($date, false), $day['date_human']); + static::assertSame('http://shaarli/subfolder/daily?day='. $dates[2]->format('Ymd'), $day['absolute_url']); + static::assertCount(1, $day['links']); + static::assertSame(4, $day['links'][0]['id']); + static::assertSame('http://domain.tld/4', $day['links'][0]['url']); + static::assertEquals($dates[2], $day['links'][0]['created']); } /** @@ -475,4 +471,246 @@ class DailyControllerTest extends TestCase static::assertFalse($assignedVariables['hide_timestamps']); static::assertCount(0, $assignedVariables['days']); } + + /** + * Test simple display index with week parameter + */ + public function testSimpleIndexWeekly(): void + { + $currentDay = new \DateTimeImmutable('2020-05-13'); + $expectedDay = new \DateTimeImmutable('2020-05-11'); + + $request = $this->createMock(Request::class); + $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string { + return $key === 'week' ? $currentDay->format('YW') : null; + }); + $response = new Response(); + + // Save RainTPL assigned variables + $assignedVariables = []; + $this->assignTemplateVars($assignedVariables); + + $this->container->bookmarkService + ->expects(static::once()) + ->method('findByDate') + ->willReturnCallback( + function (): array { + return [ + (new Bookmark()) + ->setId(1) + ->setUrl('http://url.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + (new Bookmark()) + ->setId(2) + ->setUrl('http://url2.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + ]; + } + ) + ; + + $result = $this->controller->index($request, $response); + + static::assertSame(200, $result->getStatusCode()); + static::assertSame('daily', (string) $result->getBody()); + static::assertSame( + 'Weekly - Week 20 (May 11, 2020) - Shaarli', + $assignedVariables['pagetitle'] + ); + + static::assertCount(2, $assignedVariables['linksToDisplay']); + static::assertEquals($expectedDay->setTime(0, 0), $assignedVariables['dayDate']); + static::assertSame($expectedDay->setTime(0, 0)->getTimestamp(), $assignedVariables['day']); + static::assertSame('', $assignedVariables['previousday']); + static::assertSame('', $assignedVariables['nextday']); + static::assertSame('Week 20 (May 11, 2020)', $assignedVariables['dayDesc']); + static::assertSame('week', $assignedVariables['type']); + static::assertSame('Weekly', $assignedVariables['localizedType']); + } + + /** + * Test simple display index with month parameter + */ + public function testSimpleIndexMonthly(): void + { + $currentDay = new \DateTimeImmutable('2020-05-13'); + $expectedDay = new \DateTimeImmutable('2020-05-01'); + + $request = $this->createMock(Request::class); + $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string { + return $key === 'month' ? $currentDay->format('Ym') : null; + }); + $response = new Response(); + + // Save RainTPL assigned variables + $assignedVariables = []; + $this->assignTemplateVars($assignedVariables); + + $this->container->bookmarkService + ->expects(static::once()) + ->method('findByDate') + ->willReturnCallback( + function (): array { + return [ + (new Bookmark()) + ->setId(1) + ->setUrl('http://url.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + (new Bookmark()) + ->setId(2) + ->setUrl('http://url2.tld') + ->setTitle(static::generateString(50)) + ->setDescription(static::generateString(500)) + , + ]; + } + ) + ; + + $result = $this->controller->index($request, $response); + + static::assertSame(200, $result->getStatusCode()); + static::assertSame('daily', (string) $result->getBody()); + static::assertSame( + 'Monthly - May, 2020 - Shaarli', + $assignedVariables['pagetitle'] + ); + + static::assertCount(2, $assignedVariables['linksToDisplay']); + static::assertEquals($expectedDay->setTime(0, 0), $assignedVariables['dayDate']); + static::assertSame($expectedDay->setTime(0, 0)->getTimestamp(), $assignedVariables['day']); + static::assertSame('', $assignedVariables['previousday']); + static::assertSame('', $assignedVariables['nextday']); + static::assertSame('May, 2020', $assignedVariables['dayDesc']); + static::assertSame('month', $assignedVariables['type']); + static::assertSame('Monthly', $assignedVariables['localizedType']); + } + + /** + * Test simple display RSS with week parameter + */ + public function testSimpleRssWeekly(): void + { + $dates = [ + new \DateTimeImmutable('2020-05-19'), + new \DateTimeImmutable('2020-05-13'), + ]; + $expectedDates = [ + new \DateTimeImmutable('2020-05-24 23:59:59'), + new \DateTimeImmutable('2020-05-17 23:59:59'), + ]; + + $this->container->environment['QUERY_STRING'] = 'week'; + $request = $this->createMock(Request::class); + $request->method('getQueryParam')->willReturnCallback(function (string $key): ?string { + return $key === 'week' ? '' : null; + }); + $response = new Response(); + + $this->container->bookmarkService->expects(static::once())->method('search')->willReturn([ + (new Bookmark())->setId(1)->setCreated($dates[0])->setUrl('http://domain.tld/1'), + (new Bookmark())->setId(2)->setCreated($dates[1])->setUrl('http://domain.tld/2'), + (new Bookmark())->setId(3)->setCreated($dates[1])->setUrl('http://domain.tld/3'), + ]); + + // Save RainTPL assigned variables + $assignedVariables = []; + $this->assignTemplateVars($assignedVariables); + + $result = $this->controller->rss($request, $response); + + static::assertSame(200, $result->getStatusCode()); + static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]); + static::assertSame('dailyrss', (string) $result->getBody()); + static::assertSame('Shaarli', $assignedVariables['title']); + static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']); + static::assertSame('http://shaarli/subfolder/daily-rss?week', $assignedVariables['page_url']); + static::assertFalse($assignedVariables['hide_timestamps']); + static::assertCount(2, $assignedVariables['days']); + + $day = $assignedVariables['days'][$dates[0]->format('YW')]; + $date = $expectedDates[0]; + + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame('Week 21 (May 18, 2020)', $day['date_human']); + static::assertSame('http://shaarli/subfolder/daily?week='. $dates[0]->format('YW'), $day['absolute_url']); + static::assertCount(1, $day['links']); + + $day = $assignedVariables['days'][$dates[1]->format('YW')]; + $date = $expectedDates[1]; + + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame('Week 20 (May 11, 2020)', $day['date_human']); + static::assertSame('http://shaarli/subfolder/daily?week='. $dates[1]->format('YW'), $day['absolute_url']); + static::assertCount(2, $day['links']); + } + + /** + * Test simple display RSS with month parameter + */ + public function testSimpleRssMonthly(): void + { + $dates = [ + new \DateTimeImmutable('2020-05-19'), + new \DateTimeImmutable('2020-04-13'), + ]; + $expectedDates = [ + new \DateTimeImmutable('2020-05-31 23:59:59'), + new \DateTimeImmutable('2020-04-30 23:59:59'), + ]; + + $this->container->environment['QUERY_STRING'] = 'month'; + $request = $this->createMock(Request::class); + $request->method('getQueryParam')->willReturnCallback(function (string $key): ?string { + return $key === 'month' ? '' : null; + }); + $response = new Response(); + + $this->container->bookmarkService->expects(static::once())->method('search')->willReturn([ + (new Bookmark())->setId(1)->setCreated($dates[0])->setUrl('http://domain.tld/1'), + (new Bookmark())->setId(2)->setCreated($dates[1])->setUrl('http://domain.tld/2'), + (new Bookmark())->setId(3)->setCreated($dates[1])->setUrl('http://domain.tld/3'), + ]); + + // Save RainTPL assigned variables + $assignedVariables = []; + $this->assignTemplateVars($assignedVariables); + + $result = $this->controller->rss($request, $response); + + static::assertSame(200, $result->getStatusCode()); + static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]); + static::assertSame('dailyrss', (string) $result->getBody()); + static::assertSame('Shaarli', $assignedVariables['title']); + static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']); + static::assertSame('http://shaarli/subfolder/daily-rss?month', $assignedVariables['page_url']); + static::assertFalse($assignedVariables['hide_timestamps']); + static::assertCount(2, $assignedVariables['days']); + + $day = $assignedVariables['days'][$dates[0]->format('Ym')]; + $date = $expectedDates[0]; + + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame('May, 2020', $day['date_human']); + static::assertSame('http://shaarli/subfolder/daily?month='. $dates[0]->format('Ym'), $day['absolute_url']); + static::assertCount(1, $day['links']); + + $day = $assignedVariables['days'][$dates[1]->format('Ym')]; + $date = $expectedDates[1]; + + static::assertEquals($date, $day['date']); + static::assertSame($date->format(\DateTime::RSS), $day['date_rss']); + static::assertSame('April, 2020', $day['date_human']); + static::assertSame('http://shaarli/subfolder/daily?month='. $dates[1]->format('Ym'), $day['absolute_url']); + static::assertCount(2, $day['links']); + } } diff --git a/tests/helper/DailyPageHelperTest.php b/tests/helper/DailyPageHelperTest.php new file mode 100644 index 00000000..e0378491 --- /dev/null +++ b/tests/helper/DailyPageHelperTest.php @@ -0,0 +1,262 @@ +createMock(Request::class); + $request->method('getQueryParam')->willReturnCallback(function ($key) use ($queryParams): ?string { + return $queryParams[$key] ?? null; + }); + + $type = DailyPageHelper::extractRequestedType($request); + + static::assertSame($type, $expectedType); + } + + /** + * @dataProvider getRequestedDateTimes + */ + public function testExtractRequestedDateTime( + string $type, + string $input, + ?Bookmark $bookmark, + \DateTimeInterface $expectedDateTime, + string $compareFormat = 'Ymd' + ): void { + $dateTime = DailyPageHelper::extractRequestedDateTime($type, $input, $bookmark); + + static::assertSame($dateTime->format($compareFormat), $expectedDateTime->format($compareFormat)); + } + + public function testExtractRequestedDateTimeExceptionUnknownType(): void + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Unsupported daily format type'); + + DailyPageHelper::extractRequestedDateTime('nope', null, null); + } + + /** + * @dataProvider getFormatsByType + */ + public function testGetFormatByType(string $type, string $expectedFormat): void + { + $format = DailyPageHelper::getFormatByType($type); + + static::assertSame($expectedFormat, $format); + } + + public function testGetFormatByTypeExceptionUnknownType(): void + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Unsupported daily format type'); + + DailyPageHelper::getFormatByType('nope'); + } + + /** + * @dataProvider getStartDatesByType + */ + public function testGetStartDatesByType( + string $type, + \DateTimeImmutable $dateTime, + \DateTimeInterface $expectedDateTime + ): void { + $startDateTime = DailyPageHelper::getStartDateTimeByType($type, $dateTime); + + static::assertEquals($expectedDateTime, $startDateTime); + } + + public function testGetStartDatesByTypeExceptionUnknownType(): void + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Unsupported daily format type'); + + DailyPageHelper::getStartDateTimeByType('nope', new \DateTimeImmutable()); + } + + /** + * @dataProvider getEndDatesByType + */ + public function testGetEndDatesByType( + string $type, + \DateTimeImmutable $dateTime, + \DateTimeInterface $expectedDateTime + ): void { + $endDateTime = DailyPageHelper::getEndDateTimeByType($type, $dateTime); + + static::assertEquals($expectedDateTime, $endDateTime); + } + + public function testGetEndDatesByTypeExceptionUnknownType(): void + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Unsupported daily format type'); + + DailyPageHelper::getEndDateTimeByType('nope', new \DateTimeImmutable()); + } + + /** + * @dataProvider getDescriptionsByType + */ + public function testGeDescriptionsByType( + string $type, + \DateTimeImmutable $dateTime, + string $expectedDescription + ): void { + $description = DailyPageHelper::getDescriptionByType($type, $dateTime); + + static::assertEquals($expectedDescription, $description); + } + + public function getDescriptionByTypeExceptionUnknownType(): void + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Unsupported daily format type'); + + DailyPageHelper::getDescriptionByType('nope', new \DateTimeImmutable()); + } + + /** + * @dataProvider getRssLengthsByType + */ + public function testGeRssLengthsByType(string $type): void { + $length = DailyPageHelper::getRssLengthByType($type); + + static::assertIsInt($length); + } + + public function testGeRssLengthsByTypeExceptionUnknownType(): void + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Unsupported daily format type'); + + DailyPageHelper::getRssLengthByType('nope'); + } + + /** + * Data provider for testExtractRequestedType() test method. + */ + public function getRequestedTypes(): array + { + return [ + [['month' => null], DailyPageHelper::DAY], + [['month' => ''], DailyPageHelper::MONTH], + [['month' => 'content'], DailyPageHelper::MONTH], + [['week' => null], DailyPageHelper::DAY], + [['week' => ''], DailyPageHelper::WEEK], + [['week' => 'content'], DailyPageHelper::WEEK], + [['day' => null], DailyPageHelper::DAY], + [['day' => ''], DailyPageHelper::DAY], + [['day' => 'content'], DailyPageHelper::DAY], + ]; + } + + /** + * Data provider for testExtractRequestedDateTime() test method. + */ + public function getRequestedDateTimes(): array + { + return [ + [DailyPageHelper::DAY, '20201013', null, new \DateTime('2020-10-13')], + [ + DailyPageHelper::DAY, + '', + (new Bookmark())->setCreated($date = new \DateTime('2020-10-13 12:05:31')), + $date, + ], + [DailyPageHelper::DAY, '', null, new \DateTime()], + [DailyPageHelper::WEEK, '202030', null, new \DateTime('2020-07-20')], + [ + DailyPageHelper::WEEK, + '', + (new Bookmark())->setCreated($date = new \DateTime('2020-10-13 12:05:31')), + new \DateTime('2020-10-13'), + ], + [DailyPageHelper::WEEK, '', null, new \DateTime(), 'Ym'], + [DailyPageHelper::MONTH, '202008', null, new \DateTime('2020-08-01'), 'Ym'], + [ + DailyPageHelper::MONTH, + '', + (new Bookmark())->setCreated($date = new \DateTime('2020-10-13 12:05:31')), + new \DateTime('2020-10-13'), + 'Ym' + ], + [DailyPageHelper::MONTH, '', null, new \DateTime(), 'Ym'], + ]; + } + + /** + * Data provider for testGetFormatByType() test method. + */ + public function getFormatsByType(): array + { + return [ + [DailyPageHelper::DAY, 'Ymd'], + [DailyPageHelper::WEEK, 'YW'], + [DailyPageHelper::MONTH, 'Ym'], + ]; + } + + /** + * Data provider for testGetStartDatesByType() test method. + */ + public function getStartDatesByType(): array + { + return [ + [DailyPageHelper::DAY, new \DateTimeImmutable('2020-10-09 04:05:06'), new \DateTime('2020-10-09 00:00:00')], + [DailyPageHelper::WEEK, new \DateTimeImmutable('2020-10-09 04:05:06'), new \DateTime('2020-10-05 00:00:00')], + [DailyPageHelper::MONTH, new \DateTimeImmutable('2020-10-09 04:05:06'), new \DateTime('2020-10-01 00:00:00')], + ]; + } + + /** + * Data provider for testGetEndDatesByType() test method. + */ + public function getEndDatesByType(): array + { + return [ + [DailyPageHelper::DAY, new \DateTimeImmutable('2020-10-09 04:05:06'), new \DateTime('2020-10-09 23:59:59')], + [DailyPageHelper::WEEK, new \DateTimeImmutable('2020-10-09 04:05:06'), new \DateTime('2020-10-11 23:59:59')], + [DailyPageHelper::MONTH, new \DateTimeImmutable('2020-10-09 04:05:06'), new \DateTime('2020-10-31 23:59:59')], + ]; + } + + /** + * Data provider for testGetDescriptionsByType() test method. + */ + public function getDescriptionsByType(): array + { + return [ + [DailyPageHelper::DAY, $date = new \DateTimeImmutable(), 'Today - ' . $date->format('F d, Y')], + [DailyPageHelper::DAY, $date = new \DateTimeImmutable('-1 day'), 'Yesterday - ' . $date->format('F d, Y')], + [DailyPageHelper::DAY, new \DateTimeImmutable('2020-10-09 04:05:06'), 'October 9, 2020'], + [DailyPageHelper::WEEK, new \DateTimeImmutable('2020-10-09 04:05:06'), 'Week 41 (October 5, 2020)'], + [DailyPageHelper::MONTH, new \DateTimeImmutable('2020-10-09 04:05:06'), 'October, 2020'], + ]; + } + + /** + * Data provider for testGetDescriptionsByType() test method. + */ + public function getRssLengthsByType(): array + { + return [ + [DailyPageHelper::DAY], + [DailyPageHelper::WEEK], + [DailyPageHelper::MONTH], + ]; + } +} -- cgit v1.2.3 From 54afb1d6f65f727b20b66582bb63a42c421eea4d Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Tue, 27 Oct 2020 19:55:29 +0100 Subject: Fix rebase issue --- tests/helper/FileUtilsTest.php | 1 + 1 file changed, 1 insertion(+) (limited to 'tests') diff --git a/tests/helper/FileUtilsTest.php b/tests/helper/FileUtilsTest.php index 948e46d1..8035f79c 100644 --- a/tests/helper/FileUtilsTest.php +++ b/tests/helper/FileUtilsTest.php @@ -4,6 +4,7 @@ namespace Shaarli\Helper; use Exception; use Shaarli\Exceptions\IOException; +use Shaarli\TestCase; /** * Class FileUtilsTest -- cgit v1.2.3