From bdc5152d486ca75372c271f94623b248bc127800 Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Sun, 2 Dec 2018 23:24:58 +0100 Subject: namespacing: \Shaarli\History Signed-off-by: VirtualTam --- tests/HistoryTest.php | 7 +++++-- tests/NetscapeBookmarkUtils/BookmarkImportTest.php | 1 + tests/api/controllers/history/HistoryTest.php | 20 ++++++++++---------- tests/api/controllers/links/DeleteLinkTest.php | 6 +++--- tests/api/controllers/links/PostLinkTest.php | 8 ++++---- tests/api/controllers/links/PutLinkTest.php | 8 ++++---- tests/api/controllers/tags/DeleteTagTest.php | 10 +++++----- tests/api/controllers/tags/PutTagTest.php | 8 ++++---- tests/utils/ReferenceHistory.php | 2 ++ 9 files changed, 38 insertions(+), 32 deletions(-) (limited to 'tests') diff --git a/tests/HistoryTest.php b/tests/HistoryTest.php index d3bef5a3..7723c461 100644 --- a/tests/HistoryTest.php +++ b/tests/HistoryTest.php @@ -1,9 +1,12 @@ container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = true; - $this->container['history'] = new \History(self::$testHistory); + $this->container['history'] = new \Shaarli\History(self::$testHistory); $this->controller = new History($this->container); } @@ -78,35 +78,35 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals($this->refHistory->count(), count($data)); - $this->assertEquals(\History::DELETED, $data[0]['event']); + $this->assertEquals(\Shaarli\History::DELETED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM), $data[0]['datetime'] ); $this->assertEquals(124, $data[0]['id']); - $this->assertEquals(\History::SETTINGS, $data[1]['event']); + $this->assertEquals(\Shaarli\History::SETTINGS, $data[1]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170302_121215')->format(\DateTime::ATOM), $data[1]['datetime'] ); $this->assertNull($data[1]['id']); - $this->assertEquals(\History::UPDATED, $data[2]['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $data[2]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170301_121214')->format(\DateTime::ATOM), $data[2]['datetime'] ); $this->assertEquals(123, $data[2]['id']); - $this->assertEquals(\History::CREATED, $data[3]['event']); + $this->assertEquals(\Shaarli\History::CREATED, $data[3]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170201_121214')->format(\DateTime::ATOM), $data[3]['datetime'] ); $this->assertEquals(124, $data[3]['id']); - $this->assertEquals(\History::CREATED, $data[4]['event']); + $this->assertEquals(\Shaarli\History::CREATED, $data[4]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170101_121212')->format(\DateTime::ATOM), $data[4]['datetime'] @@ -131,7 +131,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\History::DELETED, $data[0]['event']); + $this->assertEquals(\Shaarli\History::DELETED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM), $data[0]['datetime'] @@ -156,7 +156,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\History::CREATED, $data[0]['event']); + $this->assertEquals(\Shaarli\History::CREATED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170101_121212')->format(\DateTime::ATOM), $data[0]['datetime'] @@ -181,7 +181,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\History::DELETED, $data[0]['event']); + $this->assertEquals(\Shaarli\History::DELETED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM), $data[0]['datetime'] @@ -206,7 +206,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\History::SETTINGS, $data[0]['event']); + $this->assertEquals(\Shaarli\History::SETTINGS, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170302_121215')->format(\DateTime::ATOM), $data[0]['datetime'] diff --git a/tests/api/controllers/links/DeleteLinkTest.php b/tests/api/controllers/links/DeleteLinkTest.php index 7d797137..07371e7a 100644 --- a/tests/api/controllers/links/DeleteLinkTest.php +++ b/tests/api/controllers/links/DeleteLinkTest.php @@ -37,7 +37,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase protected $linkDB; /** - * @var \History instance. + * @var \Shaarli\History instance. */ protected $history; @@ -62,7 +62,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase $this->linkDB = new \LinkDB(self::$testDatastore, true, false); $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \History(self::$testHistory); + $this->history = new \Shaarli\History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = $this->linkDB; @@ -100,7 +100,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase $this->assertFalse(isset($this->linkDB[$id])); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\History::DELETED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::DELETED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/links/PostLinkTest.php b/tests/api/controllers/links/PostLinkTest.php index 5c2b5623..a73f443c 100644 --- a/tests/api/controllers/links/PostLinkTest.php +++ b/tests/api/controllers/links/PostLinkTest.php @@ -40,7 +40,7 @@ class PostLinkTest extends TestCase protected $refDB = null; /** - * @var \History instance. + * @var \Shaarli\History instance. */ protected $history; @@ -70,12 +70,12 @@ class PostLinkTest extends TestCase $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \History(self::$testHistory); + $this->history = new \Shaarli\History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); - $this->container['history'] = new \History(self::$testHistory); + $this->container['history'] = new \Shaarli\History(self::$testHistory); $this->controller = new Links($this->container); @@ -133,7 +133,7 @@ class PostLinkTest extends TestCase $this->assertEquals('', $data['updated']); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\History::CREATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::CREATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/links/PutLinkTest.php b/tests/api/controllers/links/PutLinkTest.php index f276b4c1..3bb4d43f 100644 --- a/tests/api/controllers/links/PutLinkTest.php +++ b/tests/api/controllers/links/PutLinkTest.php @@ -32,7 +32,7 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \History instance. + * @var \Shaarli\History instance. */ protected $history; @@ -62,12 +62,12 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \History(self::$testHistory); + $this->history = new \Shaarli\History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); - $this->container['history'] = new \History(self::$testHistory); + $this->container['history'] = new \Shaarli\History(self::$testHistory); $this->controller = new Links($this->container); @@ -119,7 +119,7 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase ); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\History::UPDATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/tags/DeleteTagTest.php b/tests/api/controllers/tags/DeleteTagTest.php index e0787ce2..a1e419cd 100644 --- a/tests/api/controllers/tags/DeleteTagTest.php +++ b/tests/api/controllers/tags/DeleteTagTest.php @@ -37,7 +37,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase protected $linkDB; /** - * @var \History instance. + * @var \Shaarli\History instance. */ protected $history; @@ -62,7 +62,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->linkDB = new \LinkDB(self::$testDatastore, true, false); $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \History(self::$testHistory); + $this->history = new \Shaarli\History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = $this->linkDB; @@ -103,12 +103,12 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase // 2 links affected $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\History::UPDATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); $historyEntry = $this->history->getHistory()[1]; - $this->assertEquals(\History::UPDATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); @@ -137,7 +137,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->assertTrue($tags[strtolower($tagName)] > 0); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\History::UPDATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/tags/PutTagTest.php b/tests/api/controllers/tags/PutTagTest.php index 38017243..c45fa722 100644 --- a/tests/api/controllers/tags/PutTagTest.php +++ b/tests/api/controllers/tags/PutTagTest.php @@ -33,7 +33,7 @@ class PutTagTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \History instance. + * @var \Shaarli\History instance. */ protected $history; @@ -68,7 +68,7 @@ class PutTagTest extends \PHPUnit_Framework_TestCase $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \History(self::$testHistory); + $this->history = new \Shaarli\History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; @@ -113,12 +113,12 @@ class PutTagTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2, $tags[$newName]); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\History::UPDATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); $historyEntry = $this->history->getHistory()[1]; - $this->assertEquals(\History::UPDATED, $historyEntry['event']); + $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/utils/ReferenceHistory.php b/tests/utils/ReferenceHistory.php index 75cbb326..f19cdf2f 100644 --- a/tests/utils/ReferenceHistory.php +++ b/tests/utils/ReferenceHistory.php @@ -1,5 +1,7 @@ Date: Sun, 2 Dec 2018 23:31:40 +0100 Subject: namespacing: \Shaarli\Exceptions\IOException Signed-off-by: VirtualTam --- tests/FileUtilsTest.php | 8 +++++--- tests/LinkDBTest.php | 4 +++- tests/config/ConfigJsonTest.php | 4 ++-- 3 files changed, 10 insertions(+), 6 deletions(-) (limited to 'tests') diff --git a/tests/FileUtilsTest.php b/tests/FileUtilsTest.php index d764e495..9596dba9 100644 --- a/tests/FileUtilsTest.php +++ b/tests/FileUtilsTest.php @@ -1,5 +1,7 @@ Date: Mon, 3 Dec 2018 00:08:04 +0100 Subject: namespacing: \Shaarli\Feed\{Cache,CachedPage,FeedBuilder} Signed-off-by: VirtualTam --- tests/CacheTest.php | 91 --------------- tests/CachedPageTest.php | 121 -------------------- tests/FeedBuilderTest.php | 245 ---------------------------------------- tests/LinkDBTest.php | 4 +- tests/feed/CacheTest.php | 92 +++++++++++++++ tests/feed/CachedPageTest.php | 120 ++++++++++++++++++++ tests/feed/FeedBuilderTest.php | 250 +++++++++++++++++++++++++++++++++++++++++ 7 files changed, 463 insertions(+), 460 deletions(-) delete mode 100644 tests/CacheTest.php delete mode 100644 tests/CachedPageTest.php delete mode 100644 tests/FeedBuilderTest.php create mode 100644 tests/feed/CacheTest.php create mode 100644 tests/feed/CachedPageTest.php create mode 100644 tests/feed/FeedBuilderTest.php (limited to 'tests') diff --git a/tests/CacheTest.php b/tests/CacheTest.php deleted file mode 100644 index f60fad91..00000000 --- a/tests/CacheTest.php +++ /dev/null @@ -1,91 +0,0 @@ -assertFileNotExists(self::$testCacheDir.'/'.$page.'.cache'); - } - - $this->assertFileExists(self::$testCacheDir.'/intru.der'); - } - - /** - * Purge cached pages - missing directory - */ - public function testPurgeCachedPagesMissingDir() - { - $oldlog = ini_get('error_log'); - ini_set('error_log', '/dev/null'); - $this->assertEquals( - 'Cannot purge sandbox/dummycache_missing: no directory', - purgeCachedPages(self::$testCacheDir.'_missing') - ); - ini_set('error_log', $oldlog); - } - - /** - * Purge cached pages and session cache - */ - public function testInvalidateCaches() - { - $this->assertArrayNotHasKey('tags', $_SESSION); - $_SESSION['tags'] = array('goodbye', 'cruel', 'world'); - - invalidateCaches(self::$testCacheDir); - foreach (self::$pages as $page) { - $this->assertFileNotExists(self::$testCacheDir.'/'.$page.'.cache'); - } - - $this->assertArrayNotHasKey('tags', $_SESSION); - } -} diff --git a/tests/CachedPageTest.php b/tests/CachedPageTest.php deleted file mode 100644 index 51565cd6..00000000 --- a/tests/CachedPageTest.php +++ /dev/null @@ -1,121 +0,0 @@ -assertFileNotExists(self::$filename); - $page->cache('

Some content

'); - $this->assertFileExists(self::$filename); - $this->assertEquals( - '

Some content

', - file_get_contents(self::$filename) - ); - } - - /** - * "Cache" a page's content - the page is not to be cached - */ - public function testShouldNotCache() - { - $page = new CachedPage(self::$testCacheDir, self::$url, false); - - $this->assertFileNotExists(self::$filename); - $page->cache('

Some content

'); - $this->assertFileNotExists(self::$filename); - } - - /** - * Return a page's cached content - */ - public function testCachedVersion() - { - $page = new CachedPage(self::$testCacheDir, self::$url, true); - - $this->assertFileNotExists(self::$filename); - $page->cache('

Some content

'); - $this->assertFileExists(self::$filename); - $this->assertEquals( - '

Some content

', - $page->cachedVersion() - ); - } - - /** - * Return a page's cached content - the file does not exist - */ - public function testCachedVersionNoFile() - { - $page = new CachedPage(self::$testCacheDir, self::$url, true); - - $this->assertFileNotExists(self::$filename); - $this->assertEquals( - null, - $page->cachedVersion() - ); - } - - /** - * Return a page's cached content - the page is not to be cached - */ - public function testNoCachedVersion() - { - $page = new CachedPage(self::$testCacheDir, self::$url, false); - - $this->assertFileNotExists(self::$filename); - $this->assertEquals( - null, - $page->cachedVersion() - ); - } -} diff --git a/tests/FeedBuilderTest.php b/tests/FeedBuilderTest.php deleted file mode 100644 index 4ca58e5a..00000000 --- a/tests/FeedBuilderTest.php +++ /dev/null @@ -1,245 +0,0 @@ -write(self::$testDatastore); - self::$linkDB = new LinkDB(self::$testDatastore, true, false); - self::$serverInfo = array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/index.php', - 'REQUEST_URI' => '/index.php?do=feed', - ); - } - - /** - * Test GetTypeLanguage(). - */ - public function testGetTypeLanguage() - { - $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_ATOM, null, null, false); - $feedBuilder->setLocale(self::$LOCALE); - $this->assertEquals(self::$ATOM_LANGUAGUE, $feedBuilder->getTypeLanguage()); - $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_RSS, null, null, false); - $feedBuilder->setLocale(self::$LOCALE); - $this->assertEquals(self::$RSS_LANGUAGE, $feedBuilder->getTypeLanguage()); - $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_ATOM, null, null, false); - $this->assertEquals('en', $feedBuilder->getTypeLanguage()); - $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_RSS, null, null, false); - $this->assertEquals('en-en', $feedBuilder->getTypeLanguage()); - } - - /** - * Test buildData with RSS feed. - */ - public function testRSSBuildData() - { - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_RSS, self::$serverInfo, null, false); - $feedBuilder->setLocale(self::$LOCALE); - $data = $feedBuilder->buildData(); - // Test headers (RSS) - $this->assertEquals(self::$RSS_LANGUAGE, $data['language']); - $this->assertRegExp('/Wed, 03 Aug 2016 09:30:33 \+\d{4}/', $data['last_update']); - $this->assertEquals(true, $data['show_dates']); - $this->assertEquals('http://host.tld/index.php?do=feed', $data['self_link']); - $this->assertEquals('http://host.tld/', $data['index_url']); - $this->assertFalse($data['usepermalinks']); - $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); - - // Test first not pinned link (note link) - $link = $data['links'][array_keys($data['links'])[2]]; - $this->assertEquals(41, $link['id']); - $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); - $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); - $this->assertEquals('http://host.tld/?WDWyig', $link['url']); - $this->assertRegExp('/Tue, 10 Mar 2015 11:46:51 \+\d{4}/', $link['pub_iso_date']); - $pub = DateTime::createFromFormat(DateTime::RSS, $link['pub_iso_date']); - $up = DateTime::createFromFormat(DateTime::ATOM, $link['up_iso_date']); - $this->assertEquals($pub, $up); - $this->assertContains('Stallman has a beard', $link['description']); - $this->assertContains('Permalink', $link['description']); - $this->assertContains('http://host.tld/?WDWyig', $link['description']); - $this->assertEquals(1, count($link['taglist'])); - $this->assertEquals('sTuff', $link['taglist'][0]); - - // Test URL with external link. - $this->assertEquals('https://static.fsf.org/nosvn/faif-2.0.pdf', $data['links'][8]['url']); - - // Test multitags. - $this->assertEquals(5, count($data['links'][6]['taglist'])); - $this->assertEquals('css', $data['links'][6]['taglist'][0]); - - // Test update date - $this->assertRegExp('/2016-08-03T09:30:33\+\d{2}:\d{2}/', $data['links'][8]['up_iso_date']); - } - - /** - * Test buildData with ATOM feed (test only specific to ATOM). - */ - public function testAtomBuildData() - { - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, false); - $feedBuilder->setLocale(self::$LOCALE); - $data = $feedBuilder->buildData(); - $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); - $this->assertRegExp('/2016-08-03T09:30:33\+\d{2}:\d{2}/', $data['last_update']); - $link = $data['links'][array_keys($data['links'])[2]]; - $this->assertRegExp('/2015-03-10T11:46:51\+\d{2}:\d{2}/', $link['pub_iso_date']); - $this->assertRegExp('/2016-08-03T09:30:33\+\d{2}:\d{2}/', $data['links'][8]['up_iso_date']); - } - - /** - * Test buildData with search criteria. - */ - public function testBuildDataFiltered() - { - $criteria = array( - 'searchtags' => 'stuff', - 'searchterm' => 'beard', - ); - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, $criteria, false); - $feedBuilder->setLocale(self::$LOCALE); - $data = $feedBuilder->buildData(); - $this->assertEquals(1, count($data['links'])); - $link = array_shift($data['links']); - $this->assertEquals(41, $link['id']); - $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); - } - - /** - * Test buildData with nb limit. - */ - public function testBuildDataCount() - { - $criteria = array( - 'nb' => '3', - ); - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, $criteria, false); - $feedBuilder->setLocale(self::$LOCALE); - $data = $feedBuilder->buildData(); - $this->assertEquals(3, count($data['links'])); - $link = $data['links'][array_keys($data['links'])[2]]; - $this->assertEquals(41, $link['id']); - $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); - } - - /** - * Test buildData with permalinks on. - */ - public function testBuildDataPermalinks() - { - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, false); - $feedBuilder->setLocale(self::$LOCALE); - $feedBuilder->setUsePermalinks(true); - $data = $feedBuilder->buildData(); - $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); - $this->assertTrue($data['usepermalinks']); - // First link is a permalink - $link = $data['links'][array_keys($data['links'])[2]]; - $this->assertEquals(41, $link['id']); - $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); - $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); - $this->assertEquals('http://host.tld/?WDWyig', $link['url']); - $this->assertContains('Direct link', $link['description']); - $this->assertContains('http://host.tld/?WDWyig', $link['description']); - // Second link is a direct link - $link = $data['links'][array_keys($data['links'])[3]]; - $this->assertEquals(8, $link['id']); - $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114633'), $link['created']); - $this->assertEquals('http://host.tld/?RttfEw', $link['guid']); - $this->assertEquals('https://static.fsf.org/nosvn/faif-2.0.pdf', $link['url']); - $this->assertContains('Direct link', $link['description']); - $this->assertContains('https://static.fsf.org/nosvn/faif-2.0.pdf', $link['description']); - } - - /** - * Test buildData with hide dates settings. - */ - public function testBuildDataHideDates() - { - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, false); - $feedBuilder->setLocale(self::$LOCALE); - $feedBuilder->setHideDates(true); - $data = $feedBuilder->buildData(); - $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); - $this->assertFalse($data['show_dates']); - - // Show dates while logged in - $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, true); - $feedBuilder->setLocale(self::$LOCALE); - $feedBuilder->setHideDates(true); - $data = $feedBuilder->buildData(); - $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); - $this->assertTrue($data['show_dates']); - } - - /** - * Test buildData when Shaarli is served from a subdirectory - */ - public function testBuildDataServerSubdir() - { - $serverInfo = array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '8080', - 'SCRIPT_NAME' => '/~user/shaarli/index.php', - 'REQUEST_URI' => '/~user/shaarli/index.php?do=feed', - ); - $feedBuilder = new FeedBuilder( - self::$linkDB, - FeedBuilder::$FEED_ATOM, - $serverInfo, - null, - false - ); - $feedBuilder->setLocale(self::$LOCALE); - $data = $feedBuilder->buildData(); - - $this->assertEquals( - 'http://host.tld:8080/~user/shaarli/index.php?do=feed', - $data['self_link'] - ); - - // Test first link (note link) - $link = $data['links'][array_keys($data['links'])[2]]; - $this->assertEquals('http://host.tld:8080/~user/shaarli/?WDWyig', $link['guid']); - $this->assertEquals('http://host.tld:8080/~user/shaarli/?WDWyig', $link['url']); - $this->assertContains('http://host.tld:8080/~user/shaarli/?addtag=hashtag', $link['description']); - } -} diff --git a/tests/LinkDBTest.php b/tests/LinkDBTest.php index 9b2f35e6..737a2247 100644 --- a/tests/LinkDBTest.php +++ b/tests/LinkDBTest.php @@ -3,9 +3,7 @@ * Link datastore tests */ -use Shaarli\Exceptions\IOException; - -require_once 'application/Cache.php'; +require_once 'application/feed/Cache.php'; require_once 'application/FileUtils.php'; require_once 'application/LinkDB.php'; require_once 'application/Utils.php'; diff --git a/tests/feed/CacheTest.php b/tests/feed/CacheTest.php new file mode 100644 index 00000000..c0a9f26f --- /dev/null +++ b/tests/feed/CacheTest.php @@ -0,0 +1,92 @@ +assertFileNotExists(self::$testCacheDir . '/' . $page . '.cache'); + } + + $this->assertFileExists(self::$testCacheDir . '/intru.der'); + } + + /** + * Purge cached pages - missing directory + */ + public function testPurgeCachedPagesMissingDir() + { + $oldlog = ini_get('error_log'); + ini_set('error_log', '/dev/null'); + $this->assertEquals( + 'Cannot purge sandbox/dummycache_missing: no directory', + purgeCachedPages(self::$testCacheDir . '_missing') + ); + ini_set('error_log', $oldlog); + } + + /** + * Purge cached pages and session cache + */ + public function testInvalidateCaches() + { + $this->assertArrayNotHasKey('tags', $_SESSION); + $_SESSION['tags'] = array('goodbye', 'cruel', 'world'); + + invalidateCaches(self::$testCacheDir); + foreach (self::$pages as $page) { + $this->assertFileNotExists(self::$testCacheDir . '/' . $page . '.cache'); + } + + $this->assertArrayNotHasKey('tags', $_SESSION); + } +} diff --git a/tests/feed/CachedPageTest.php b/tests/feed/CachedPageTest.php new file mode 100644 index 00000000..0bcc1442 --- /dev/null +++ b/tests/feed/CachedPageTest.php @@ -0,0 +1,120 @@ +assertFileNotExists(self::$filename); + $page->cache('

Some content

'); + $this->assertFileExists(self::$filename); + $this->assertEquals( + '

Some content

', + file_get_contents(self::$filename) + ); + } + + /** + * "Cache" a page's content - the page is not to be cached + */ + public function testShouldNotCache() + { + $page = new CachedPage(self::$testCacheDir, self::$url, false); + + $this->assertFileNotExists(self::$filename); + $page->cache('

Some content

'); + $this->assertFileNotExists(self::$filename); + } + + /** + * Return a page's cached content + */ + public function testCachedVersion() + { + $page = new CachedPage(self::$testCacheDir, self::$url, true); + + $this->assertFileNotExists(self::$filename); + $page->cache('

Some content

'); + $this->assertFileExists(self::$filename); + $this->assertEquals( + '

Some content

', + $page->cachedVersion() + ); + } + + /** + * Return a page's cached content - the file does not exist + */ + public function testCachedVersionNoFile() + { + $page = new CachedPage(self::$testCacheDir, self::$url, true); + + $this->assertFileNotExists(self::$filename); + $this->assertEquals( + null, + $page->cachedVersion() + ); + } + + /** + * Return a page's cached content - the page is not to be cached + */ + public function testNoCachedVersion() + { + $page = new CachedPage(self::$testCacheDir, self::$url, false); + + $this->assertFileNotExists(self::$filename); + $this->assertEquals( + null, + $page->cachedVersion() + ); + } +} diff --git a/tests/feed/FeedBuilderTest.php b/tests/feed/FeedBuilderTest.php new file mode 100644 index 00000000..1fdbc60e --- /dev/null +++ b/tests/feed/FeedBuilderTest.php @@ -0,0 +1,250 @@ +write(self::$testDatastore); + self::$linkDB = new LinkDB(self::$testDatastore, true, false); + self::$serverInfo = array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/index.php', + 'REQUEST_URI' => '/index.php?do=feed', + ); + } + + /** + * Test GetTypeLanguage(). + */ + public function testGetTypeLanguage() + { + $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_ATOM, null, null, false); + $feedBuilder->setLocale(self::$LOCALE); + $this->assertEquals(self::$ATOM_LANGUAGUE, $feedBuilder->getTypeLanguage()); + $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_RSS, null, null, false); + $feedBuilder->setLocale(self::$LOCALE); + $this->assertEquals(self::$RSS_LANGUAGE, $feedBuilder->getTypeLanguage()); + $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_ATOM, null, null, false); + $this->assertEquals('en', $feedBuilder->getTypeLanguage()); + $feedBuilder = new FeedBuilder(null, FeedBuilder::$FEED_RSS, null, null, false); + $this->assertEquals('en-en', $feedBuilder->getTypeLanguage()); + } + + /** + * Test buildData with RSS feed. + */ + public function testRSSBuildData() + { + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_RSS, self::$serverInfo, null, false); + $feedBuilder->setLocale(self::$LOCALE); + $data = $feedBuilder->buildData(); + // Test headers (RSS) + $this->assertEquals(self::$RSS_LANGUAGE, $data['language']); + $this->assertRegExp('/Wed, 03 Aug 2016 09:30:33 \+\d{4}/', $data['last_update']); + $this->assertEquals(true, $data['show_dates']); + $this->assertEquals('http://host.tld/index.php?do=feed', $data['self_link']); + $this->assertEquals('http://host.tld/', $data['index_url']); + $this->assertFalse($data['usepermalinks']); + $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); + + // Test first not pinned link (note link) + $link = $data['links'][array_keys($data['links'])[2]]; + $this->assertEquals(41, $link['id']); + $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); + $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); + $this->assertEquals('http://host.tld/?WDWyig', $link['url']); + $this->assertRegExp('/Tue, 10 Mar 2015 11:46:51 \+\d{4}/', $link['pub_iso_date']); + $pub = DateTime::createFromFormat(DateTime::RSS, $link['pub_iso_date']); + $up = DateTime::createFromFormat(DateTime::ATOM, $link['up_iso_date']); + $this->assertEquals($pub, $up); + $this->assertContains('Stallman has a beard', $link['description']); + $this->assertContains('Permalink', $link['description']); + $this->assertContains('http://host.tld/?WDWyig', $link['description']); + $this->assertEquals(1, count($link['taglist'])); + $this->assertEquals('sTuff', $link['taglist'][0]); + + // Test URL with external link. + $this->assertEquals('https://static.fsf.org/nosvn/faif-2.0.pdf', $data['links'][8]['url']); + + // Test multitags. + $this->assertEquals(5, count($data['links'][6]['taglist'])); + $this->assertEquals('css', $data['links'][6]['taglist'][0]); + + // Test update date + $this->assertRegExp('/2016-08-03T09:30:33\+\d{2}:\d{2}/', $data['links'][8]['up_iso_date']); + } + + /** + * Test buildData with ATOM feed (test only specific to ATOM). + */ + public function testAtomBuildData() + { + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, false); + $feedBuilder->setLocale(self::$LOCALE); + $data = $feedBuilder->buildData(); + $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); + $this->assertRegExp('/2016-08-03T09:30:33\+\d{2}:\d{2}/', $data['last_update']); + $link = $data['links'][array_keys($data['links'])[2]]; + $this->assertRegExp('/2015-03-10T11:46:51\+\d{2}:\d{2}/', $link['pub_iso_date']); + $this->assertRegExp('/2016-08-03T09:30:33\+\d{2}:\d{2}/', $data['links'][8]['up_iso_date']); + } + + /** + * Test buildData with search criteria. + */ + public function testBuildDataFiltered() + { + $criteria = array( + 'searchtags' => 'stuff', + 'searchterm' => 'beard', + ); + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, $criteria, false); + $feedBuilder->setLocale(self::$LOCALE); + $data = $feedBuilder->buildData(); + $this->assertEquals(1, count($data['links'])); + $link = array_shift($data['links']); + $this->assertEquals(41, $link['id']); + $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); + } + + /** + * Test buildData with nb limit. + */ + public function testBuildDataCount() + { + $criteria = array( + 'nb' => '3', + ); + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, $criteria, false); + $feedBuilder->setLocale(self::$LOCALE); + $data = $feedBuilder->buildData(); + $this->assertEquals(3, count($data['links'])); + $link = $data['links'][array_keys($data['links'])[2]]; + $this->assertEquals(41, $link['id']); + $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); + } + + /** + * Test buildData with permalinks on. + */ + public function testBuildDataPermalinks() + { + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, false); + $feedBuilder->setLocale(self::$LOCALE); + $feedBuilder->setUsePermalinks(true); + $data = $feedBuilder->buildData(); + $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); + $this->assertTrue($data['usepermalinks']); + // First link is a permalink + $link = $data['links'][array_keys($data['links'])[2]]; + $this->assertEquals(41, $link['id']); + $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); + $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); + $this->assertEquals('http://host.tld/?WDWyig', $link['url']); + $this->assertContains('Direct link', $link['description']); + $this->assertContains('http://host.tld/?WDWyig', $link['description']); + // Second link is a direct link + $link = $data['links'][array_keys($data['links'])[3]]; + $this->assertEquals(8, $link['id']); + $this->assertEquals(DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114633'), $link['created']); + $this->assertEquals('http://host.tld/?RttfEw', $link['guid']); + $this->assertEquals('https://static.fsf.org/nosvn/faif-2.0.pdf', $link['url']); + $this->assertContains('Direct link', $link['description']); + $this->assertContains('https://static.fsf.org/nosvn/faif-2.0.pdf', $link['description']); + } + + /** + * Test buildData with hide dates settings. + */ + public function testBuildDataHideDates() + { + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, false); + $feedBuilder->setLocale(self::$LOCALE); + $feedBuilder->setHideDates(true); + $data = $feedBuilder->buildData(); + $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); + $this->assertFalse($data['show_dates']); + + // Show dates while logged in + $feedBuilder = new FeedBuilder(self::$linkDB, FeedBuilder::$FEED_ATOM, self::$serverInfo, null, true); + $feedBuilder->setLocale(self::$LOCALE); + $feedBuilder->setHideDates(true); + $data = $feedBuilder->buildData(); + $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); + $this->assertTrue($data['show_dates']); + } + + /** + * Test buildData when Shaarli is served from a subdirectory + */ + public function testBuildDataServerSubdir() + { + $serverInfo = array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '8080', + 'SCRIPT_NAME' => '/~user/shaarli/index.php', + 'REQUEST_URI' => '/~user/shaarli/index.php?do=feed', + ); + $feedBuilder = new FeedBuilder( + self::$linkDB, + FeedBuilder::$FEED_ATOM, + $serverInfo, + null, + false + ); + $feedBuilder->setLocale(self::$LOCALE); + $data = $feedBuilder->buildData(); + + $this->assertEquals( + 'http://host.tld:8080/~user/shaarli/index.php?do=feed', + $data['self_link'] + ); + + // Test first link (note link) + $link = $data['links'][array_keys($data['links'])[2]]; + $this->assertEquals('http://host.tld:8080/~user/shaarli/?WDWyig', $link['guid']); + $this->assertEquals('http://host.tld:8080/~user/shaarli/?WDWyig', $link['url']); + $this->assertContains('http://host.tld:8080/~user/shaarli/?addtag=hashtag', $link['description']); + } +} -- cgit v1.2.3 From 00af48d9d20af1ce51c8ad42fe354fafc9ceb8a3 Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 00:16:10 +0100 Subject: namespacing: \Shaarli\Http\Base64Url Signed-off-by: VirtualTam --- tests/api/ApiUtilsTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'tests') diff --git a/tests/api/ApiUtilsTest.php b/tests/api/ApiUtilsTest.php index df4e189a..a1b623d8 100644 --- a/tests/api/ApiUtilsTest.php +++ b/tests/api/ApiUtilsTest.php @@ -2,7 +2,7 @@ namespace Shaarli\Api; -use Shaarli\Base64Url; +use Shaarli\Http\Base64Url; /** * Class ApiUtilsTest -- cgit v1.2.3 From fb1b182fbf0ee5afed586f77eec84d7a906831ef Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 00:23:35 +0100 Subject: namespacing: \Shaarli\Http\Url Signed-off-by: VirtualTam --- tests/Url/UrlTest.php | 200 ------------------------------------------------ tests/http/UrlTest.php | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+), 200 deletions(-) delete mode 100644 tests/Url/UrlTest.php create mode 100644 tests/http/UrlTest.php (limited to 'tests') diff --git a/tests/Url/UrlTest.php b/tests/Url/UrlTest.php deleted file mode 100644 index db229ce0..00000000 --- a/tests/Url/UrlTest.php +++ /dev/null @@ -1,200 +0,0 @@ -cleanup(); - $this->assertEquals(self::$baseUrl, $url->toString()); - } - - /** - * Instantiate an empty URL - */ - public function testEmptyConstruct() - { - $url = new Url(''); - $this->assertEquals('', $url->toString()); - } - - /** - * Instantiate a URL - */ - public function testConstruct() - { - $ref = 'http://username:password@hostname:9090/path' - .'?arg1=value1&arg2=value2#anchor'; - $url = new Url($ref); - $this->assertEquals($ref, $url->toString()); - } - - /** - * URL cleanup - nothing to do - */ - public function testNoCleanup() - { - // URL with no query nor fragment - $this->assertUrlIsCleaned(); - - // URL with no annoying elements - $ref = self::$baseUrl.'?p1=val1&p2=1234#edit'; - $url = new Url($ref); - $this->assertEquals($ref, $url->cleanup()); - } - - /** - * URL cleanup - annoying fragment - */ - public function testCleanupFragment() - { - $this->assertUrlIsCleaned('', '#tk.rss_all'); - $this->assertUrlIsCleaned('', '#xtor=RSS-'); - $this->assertUrlIsCleaned('', '#xtor=RSS-U3ht0tkc4b'); - } - - /** - * URL cleanup - single annoying query parameter - */ - public function testCleanupSingleQueryParam() - { - $this->assertUrlIsCleaned('?action_object_map=junk'); - $this->assertUrlIsCleaned('?action_ref_map=Cr4p!'); - $this->assertUrlIsCleaned('?action_type_map=g4R84g3'); - - $this->assertUrlIsCleaned('?fb_stuff=v41u3'); - $this->assertUrlIsCleaned('?fb=71m3w4573'); - - $this->assertUrlIsCleaned('?utm_campaign=zomg'); - $this->assertUrlIsCleaned('?utm_medium=numnum'); - $this->assertUrlIsCleaned('?utm_source=c0d3'); - $this->assertUrlIsCleaned('?utm_term=1n4l'); - - $this->assertUrlIsCleaned('?xtor=some-url'); - $this->assertUrlIsCleaned('?PHPSESSID=012345678910111213'); - } - - /** - * URL cleanup - multiple annoying query parameters - */ - public function testCleanupMultipleQueryParams() - { - $this->assertUrlIsCleaned('?xtor=some-url&fb=som3th1ng'); - $this->assertUrlIsCleaned( - '?fb=stuff&utm_campaign=zomg&utm_medium=numnum&utm_source=c0d3' - ); - } - - /** - * URL cleanup - multiple annoying query parameters, annoying fragment - */ - public function testCleanupMultipleQueryParamsAndFragment() - { - $this->assertUrlIsCleaned('?xtor=some-url&fb=som3th1ng', '#tk.rss_all'); - } - - /** - * Nominal case - the URL contains both useful and annoying parameters - */ - public function testCleanupMixedContent() - { - // ditch annoying query params and fragment, keep useful params - $url = new Url( - self::$baseUrl - .'?fb=zomg&my=stuff&utm_medium=numnum&is=kept#tk.rss_all' - ); - $this->assertEquals(self::$baseUrl.'?my=stuff&is=kept', $url->cleanup()); - - - // ditch annoying query params, keep useful params and fragment - $url = new Url( - self::$baseUrl - .'?fb=zomg&my=stuff&utm_medium=numnum&is=kept#again' - ); - $this->assertEquals( - self::$baseUrl.'?my=stuff&is=kept#again', - $url->cleanup() - ); - - // test firefox reader url - $url = new Url( - 'about://reader?url=' . urlencode(self::$baseUrl .'?my=stuff&is=kept') - ); - $this->assertEquals(self::$baseUrl.'?my=stuff&is=kept', $url->cleanup()); - } - - /** - * Test default http scheme. - */ - public function testDefaultScheme() - { - $url = new Url(self::$baseUrl); - $this->assertEquals('http', $url->getScheme()); - $url = new Url('domain.tld'); - $this->assertEquals('http', $url->getScheme()); - $url = new Url('ssh://domain.tld'); - $this->assertEquals('ssh', $url->getScheme()); - $url = new Url('ftp://domain.tld'); - $this->assertEquals('ftp', $url->getScheme()); - $url = new Url('git://domain.tld/push?pull=clone#checkout'); - $this->assertEquals('git', $url->getScheme()); - } - - /** - * Test add trailing slash. - */ - public function testAddTrailingSlash() - { - $strOn = 'http://randomstr.com/test/'; - $strOff = 'http://randomstr.com/test'; - $this->assertEquals($strOn, add_trailing_slash($strOn)); - $this->assertEquals($strOn, add_trailing_slash($strOff)); - } - - /** - * Test valid HTTP url. - */ - public function testUrlIsHttp() - { - $url = new Url(self::$baseUrl); - $this->assertTrue($url->isHttp()); - } - - /** - * Test non HTTP url. - */ - public function testUrlIsNotHttp() - { - $url = new Url('ftp://save.tld/mysave'); - $this->assertFalse($url->isHttp()); - } - - /** - * Test International Domain Name to ASCII conversion - */ - public function testIdnToAscii() - { - $ind = 'http://www.académie-française.fr/'; - $expected = 'http://www.xn--acadmie-franaise-npb1a.fr/'; - $url = new Url($ind); - $this->assertEquals($expected, $url->idnToAscii()); - - $notInd = 'http://www.academie-francaise.fr/'; - $url = new Url($notInd); - $this->assertEquals($notInd, $url->idnToAscii()); - } -} diff --git a/tests/http/UrlTest.php b/tests/http/UrlTest.php new file mode 100644 index 00000000..011b416d --- /dev/null +++ b/tests/http/UrlTest.php @@ -0,0 +1,201 @@ +cleanup(); + $this->assertEquals(self::$baseUrl, $url->toString()); + } + + /** + * Instantiate an empty URL + */ + public function testEmptyConstruct() + { + $url = new Url(''); + $this->assertEquals('', $url->toString()); + } + + /** + * Instantiate a URL + */ + public function testConstruct() + { + $ref = 'http://username:password@hostname:9090/path' + . '?arg1=value1&arg2=value2#anchor'; + $url = new Url($ref); + $this->assertEquals($ref, $url->toString()); + } + + /** + * URL cleanup - nothing to do + */ + public function testNoCleanup() + { + // URL with no query nor fragment + $this->assertUrlIsCleaned(); + + // URL with no annoying elements + $ref = self::$baseUrl . '?p1=val1&p2=1234#edit'; + $url = new Url($ref); + $this->assertEquals($ref, $url->cleanup()); + } + + /** + * URL cleanup - annoying fragment + */ + public function testCleanupFragment() + { + $this->assertUrlIsCleaned('', '#tk.rss_all'); + $this->assertUrlIsCleaned('', '#xtor=RSS-'); + $this->assertUrlIsCleaned('', '#xtor=RSS-U3ht0tkc4b'); + } + + /** + * URL cleanup - single annoying query parameter + */ + public function testCleanupSingleQueryParam() + { + $this->assertUrlIsCleaned('?action_object_map=junk'); + $this->assertUrlIsCleaned('?action_ref_map=Cr4p!'); + $this->assertUrlIsCleaned('?action_type_map=g4R84g3'); + + $this->assertUrlIsCleaned('?fb_stuff=v41u3'); + $this->assertUrlIsCleaned('?fb=71m3w4573'); + + $this->assertUrlIsCleaned('?utm_campaign=zomg'); + $this->assertUrlIsCleaned('?utm_medium=numnum'); + $this->assertUrlIsCleaned('?utm_source=c0d3'); + $this->assertUrlIsCleaned('?utm_term=1n4l'); + + $this->assertUrlIsCleaned('?xtor=some-url'); + $this->assertUrlIsCleaned('?PHPSESSID=012345678910111213'); + } + + /** + * URL cleanup - multiple annoying query parameters + */ + public function testCleanupMultipleQueryParams() + { + $this->assertUrlIsCleaned('?xtor=some-url&fb=som3th1ng'); + $this->assertUrlIsCleaned( + '?fb=stuff&utm_campaign=zomg&utm_medium=numnum&utm_source=c0d3' + ); + } + + /** + * URL cleanup - multiple annoying query parameters, annoying fragment + */ + public function testCleanupMultipleQueryParamsAndFragment() + { + $this->assertUrlIsCleaned('?xtor=some-url&fb=som3th1ng', '#tk.rss_all'); + } + + /** + * Nominal case - the URL contains both useful and annoying parameters + */ + public function testCleanupMixedContent() + { + // ditch annoying query params and fragment, keep useful params + $url = new Url( + self::$baseUrl + . '?fb=zomg&my=stuff&utm_medium=numnum&is=kept#tk.rss_all' + ); + $this->assertEquals(self::$baseUrl . '?my=stuff&is=kept', $url->cleanup()); + + + // ditch annoying query params, keep useful params and fragment + $url = new Url( + self::$baseUrl + . '?fb=zomg&my=stuff&utm_medium=numnum&is=kept#again' + ); + $this->assertEquals( + self::$baseUrl . '?my=stuff&is=kept#again', + $url->cleanup() + ); + + // test firefox reader url + $url = new Url( + 'about://reader?url=' . urlencode(self::$baseUrl . '?my=stuff&is=kept') + ); + $this->assertEquals(self::$baseUrl . '?my=stuff&is=kept', $url->cleanup()); + } + + /** + * Test default http scheme. + */ + public function testDefaultScheme() + { + $url = new Url(self::$baseUrl); + $this->assertEquals('http', $url->getScheme()); + $url = new Url('domain.tld'); + $this->assertEquals('http', $url->getScheme()); + $url = new Url('ssh://domain.tld'); + $this->assertEquals('ssh', $url->getScheme()); + $url = new Url('ftp://domain.tld'); + $this->assertEquals('ftp', $url->getScheme()); + $url = new Url('git://domain.tld/push?pull=clone#checkout'); + $this->assertEquals('git', $url->getScheme()); + } + + /** + * Test add trailing slash. + */ + public function testAddTrailingSlash() + { + $strOn = 'http://randomstr.com/test/'; + $strOff = 'http://randomstr.com/test'; + $this->assertEquals($strOn, add_trailing_slash($strOn)); + $this->assertEquals($strOn, add_trailing_slash($strOff)); + } + + /** + * Test valid HTTP url. + */ + public function testUrlIsHttp() + { + $url = new Url(self::$baseUrl); + $this->assertTrue($url->isHttp()); + } + + /** + * Test non HTTP url. + */ + public function testUrlIsNotHttp() + { + $url = new Url('ftp://save.tld/mysave'); + $this->assertFalse($url->isHttp()); + } + + /** + * Test International Domain Name to ASCII conversion + */ + public function testIdnToAscii() + { + $ind = 'http://www.académie-française.fr/'; + $expected = 'http://www.xn--acadmie-franaise-npb1a.fr/'; + $url = new Url($ind); + $this->assertEquals($expected, $url->idnToAscii()); + + $notInd = 'http://www.academie-francaise.fr/'; + $url = new Url($notInd); + $this->assertEquals($notInd, $url->idnToAscii()); + } +} -- cgit v1.2.3 From 51753e403fa69c0ce124ede27d300477e3e799ca Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 00:34:53 +0100 Subject: namespacing: move HTTP utilities along \Shaarli\Http\ classes Signed-off-by: VirtualTam --- tests/HttpUtils/ClientIpIdTest.php | 52 ----- tests/HttpUtils/GetHttpUrlTest.php | 65 ------- tests/HttpUtils/GetIpAdressFromProxyTest.php | 59 ------ tests/HttpUtils/IndexUrlTest.php | 72 ------- tests/HttpUtils/IsHttpsTest.php | 36 ---- tests/HttpUtils/PageUrlTest.php | 76 -------- tests/HttpUtils/ServerUrlTest.php | 221 --------------------- tests/Url/CleanupUrlTest.php | 109 ----------- tests/Url/GetUrlSchemeTest.php | 30 --- tests/Url/UnparseUrlTest.php | 30 --- tests/Url/WhitelistProtocolsTest.php | 63 ------ tests/http/HttpUtils/ClientIpIdTest.php | 54 ++++++ tests/http/HttpUtils/GetHttpUrlTest.php | 67 +++++++ tests/http/HttpUtils/GetIpAdressFromProxyTest.php | 61 ++++++ tests/http/HttpUtils/IndexUrlTest.php | 74 +++++++ tests/http/HttpUtils/IsHttpsTest.php | 39 ++++ tests/http/HttpUtils/PageUrlTest.php | 78 ++++++++ tests/http/HttpUtils/ServerUrlTest.php | 223 ++++++++++++++++++++++ tests/http/UrlTest.php | 2 +- tests/http/UrlUtils/CleanupUrlTest.php | 111 +++++++++++ tests/http/UrlUtils/GetUrlSchemeTest.php | 32 ++++ tests/http/UrlUtils/UnparseUrlTest.php | 32 ++++ tests/http/UrlUtils/WhitelistProtocolsTest.php | 63 ++++++ 23 files changed, 835 insertions(+), 814 deletions(-) delete mode 100644 tests/HttpUtils/ClientIpIdTest.php delete mode 100644 tests/HttpUtils/GetHttpUrlTest.php delete mode 100644 tests/HttpUtils/GetIpAdressFromProxyTest.php delete mode 100644 tests/HttpUtils/IndexUrlTest.php delete mode 100644 tests/HttpUtils/IsHttpsTest.php delete mode 100644 tests/HttpUtils/PageUrlTest.php delete mode 100644 tests/HttpUtils/ServerUrlTest.php delete mode 100644 tests/Url/CleanupUrlTest.php delete mode 100644 tests/Url/GetUrlSchemeTest.php delete mode 100644 tests/Url/UnparseUrlTest.php delete mode 100644 tests/Url/WhitelistProtocolsTest.php create mode 100644 tests/http/HttpUtils/ClientIpIdTest.php create mode 100644 tests/http/HttpUtils/GetHttpUrlTest.php create mode 100644 tests/http/HttpUtils/GetIpAdressFromProxyTest.php create mode 100644 tests/http/HttpUtils/IndexUrlTest.php create mode 100644 tests/http/HttpUtils/IsHttpsTest.php create mode 100644 tests/http/HttpUtils/PageUrlTest.php create mode 100644 tests/http/HttpUtils/ServerUrlTest.php create mode 100644 tests/http/UrlUtils/CleanupUrlTest.php create mode 100644 tests/http/UrlUtils/GetUrlSchemeTest.php create mode 100644 tests/http/UrlUtils/UnparseUrlTest.php create mode 100644 tests/http/UrlUtils/WhitelistProtocolsTest.php (limited to 'tests') diff --git a/tests/HttpUtils/ClientIpIdTest.php b/tests/HttpUtils/ClientIpIdTest.php deleted file mode 100644 index c15ac5cc..00000000 --- a/tests/HttpUtils/ClientIpIdTest.php +++ /dev/null @@ -1,52 +0,0 @@ -assertEquals( - '10.1.167.42', - client_ip_id(['REMOTE_ADDR' => '10.1.167.42']) - ); - } - - /** - * Get a remote client ID based on its IP and proxy information (1) - */ - public function testClientIpIdRemoteForwarded() - { - $this->assertEquals( - '10.1.167.42_127.0.1.47', - client_ip_id([ - 'REMOTE_ADDR' => '10.1.167.42', - 'HTTP_X_FORWARDED_FOR' => '127.0.1.47' - ]) - ); - } - - /** - * Get a remote client ID based on its IP and proxy information (2) - */ - public function testClientIpIdRemoteForwardedClient() - { - $this->assertEquals( - '10.1.167.42_10.1.167.56_127.0.1.47', - client_ip_id([ - 'REMOTE_ADDR' => '10.1.167.42', - 'HTTP_X_FORWARDED_FOR' => '10.1.167.56', - 'HTTP_CLIENT_IP' => '127.0.1.47' - ]) - ); - } -} diff --git a/tests/HttpUtils/GetHttpUrlTest.php b/tests/HttpUtils/GetHttpUrlTest.php deleted file mode 100644 index ea53de5f..00000000 --- a/tests/HttpUtils/GetHttpUrlTest.php +++ /dev/null @@ -1,65 +0,0 @@ -assertEquals('Invalid HTTP Url', $headers[0]); - $this->assertFalse($content); - - // Non HTTP - list($headers, $content) = get_http_response('ftp://save.tld/mysave', 1); - $this->assertEquals('Invalid HTTP Url', $headers[0]); - $this->assertFalse($content); - } - - /** - * Get an invalid remote URL - */ - public function testGetInvalidRemoteUrl() - { - list($headers, $content) = @get_http_response('http://non.existent', 1); - $this->assertFalse($headers); - $this->assertFalse($content); - } - - /** - * Test getAbsoluteUrl with relative target URL. - */ - public function testGetAbsoluteUrlWithRelative() - { - $origin = 'http://non.existent/blabla/?test'; - $target = '/stuff.php'; - - $expected = 'http://non.existent/stuff.php'; - $this->assertEquals($expected, getAbsoluteUrl($origin, $target)); - - $target = 'stuff.php'; - $expected = 'http://non.existent/blabla/stuff.php'; - $this->assertEquals($expected, getAbsoluteUrl($origin, $target)); - } - - /** - * Test getAbsoluteUrl with absolute target URL. - */ - public function testGetAbsoluteUrlWithAbsolute() - { - $origin = 'http://non.existent/blabla/?test'; - $target = 'http://other.url/stuff.php'; - - $this->assertEquals($target, getAbsoluteUrl($origin, $target)); - } -} diff --git a/tests/HttpUtils/GetIpAdressFromProxyTest.php b/tests/HttpUtils/GetIpAdressFromProxyTest.php deleted file mode 100644 index 7af5bd9d..00000000 --- a/tests/HttpUtils/GetIpAdressFromProxyTest.php +++ /dev/null @@ -1,59 +0,0 @@ -assertFalse(getIpAddressFromProxy(array(), array())); - } - - /** - * Test with a single IP in proxy header. - */ - public function testWithOneForwardedIp() - { - $ip = '1.1.1.1'; - $server = array('HTTP_X_FORWARDED_FOR' => $ip); - $this->assertEquals($ip, getIpAddressFromProxy($server, array())); - } - - /** - * Test with a multiple IPs in proxy header. - */ - public function testWithMultipleForwardedIp() - { - $ip = '1.1.1.1'; - $ip2 = '2.2.2.2'; - - $server = array('HTTP_X_FORWARDED_FOR' => $ip .','. $ip2); - $this->assertEquals($ip2, getIpAddressFromProxy($server, array())); - - $server = array('HTTP_X_FORWARDED_FOR' => $ip .' , '. $ip2); - $this->assertEquals($ip2, getIpAddressFromProxy($server, array())); - } - - /** - * Test with a trusted IP address. - */ - public function testWithTrustedIp() - { - $ip = '1.1.1.1'; - $ip2 = '2.2.2.2'; - - $server = array('HTTP_X_FORWARDED_FOR' => $ip); - $this->assertFalse(getIpAddressFromProxy($server, array($ip))); - - $server = array('HTTP_X_FORWARDED_FOR' => $ip .','. $ip2); - $this->assertEquals($ip2, getIpAddressFromProxy($server, array($ip))); - $this->assertFalse(getIpAddressFromProxy($server, array($ip, $ip2))); - } -} diff --git a/tests/HttpUtils/IndexUrlTest.php b/tests/HttpUtils/IndexUrlTest.php deleted file mode 100644 index 337dcab0..00000000 --- a/tests/HttpUtils/IndexUrlTest.php +++ /dev/null @@ -1,72 +0,0 @@ -assertEquals( - 'http://host.tld/', - index_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/index.php' - ) - ) - ); - - $this->assertEquals( - 'http://host.tld/admin/', - index_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/admin/index.php' - ) - ) - ); - } - - /** - * The resource is != "index.php" - */ - public function testOtherResource() - { - $this->assertEquals( - 'http://host.tld/page.php', - page_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/page.php' - ) - ) - ); - - $this->assertEquals( - 'http://host.tld/admin/page.php', - page_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/admin/page.php' - ) - ) - ); - } -} diff --git a/tests/HttpUtils/IsHttpsTest.php b/tests/HttpUtils/IsHttpsTest.php deleted file mode 100644 index 097f2bcf..00000000 --- a/tests/HttpUtils/IsHttpsTest.php +++ /dev/null @@ -1,36 +0,0 @@ -assertTrue(is_https(['HTTPS' => true])); - $this->assertTrue(is_https(['HTTPS' => '1'])); - $this->assertTrue(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => 443])); - $this->assertTrue(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => '443'])); - $this->assertTrue(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => '443,123,456,'])); - } - - /** - * Test is_https with HTTP values. - */ - public function testIsHttpsFalse() - { - $this->assertFalse(is_https([])); - $this->assertFalse(is_https(['HTTPS' => false])); - $this->assertFalse(is_https(['HTTPS' => '0'])); - $this->assertFalse(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => 123])); - $this->assertFalse(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => '123'])); - $this->assertFalse(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => ',123,456,'])); - } -} diff --git a/tests/HttpUtils/PageUrlTest.php b/tests/HttpUtils/PageUrlTest.php deleted file mode 100644 index 4dbbe9cf..00000000 --- a/tests/HttpUtils/PageUrlTest.php +++ /dev/null @@ -1,76 +0,0 @@ -assertEquals( - 'http://host.tld/?p1=v1&p2=v2', - page_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/index.php', - 'QUERY_STRING' => 'p1=v1&p2=v2' - ) - ) - ); - - $this->assertEquals( - 'http://host.tld/admin/?action=edit_tag', - page_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/admin/index.php', - 'QUERY_STRING' => 'action=edit_tag' - ) - ) - ); - } - - /** - * The resource is != "index.php" - */ - public function testOtherResource() - { - $this->assertEquals( - 'http://host.tld/page.php?p1=v1&p2=v2', - page_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/page.php', - 'QUERY_STRING' => 'p1=v1&p2=v2' - ) - ) - ); - - $this->assertEquals( - 'http://host.tld/admin/page.php?action=edit_tag', - page_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'SCRIPT_NAME' => '/admin/page.php', - 'QUERY_STRING' => 'action=edit_tag' - ) - ) - ); - } -} diff --git a/tests/HttpUtils/ServerUrlTest.php b/tests/HttpUtils/ServerUrlTest.php deleted file mode 100644 index 324b827a..00000000 --- a/tests/HttpUtils/ServerUrlTest.php +++ /dev/null @@ -1,221 +0,0 @@ -assertEquals( - 'https://host.tld', - server_url( - array( - 'HTTPS' => 'ON', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '443' - ) - ) - ); - - $this->assertEquals( - 'https://host.tld:8080', - server_url( - array( - 'HTTPS' => 'ON', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '8080' - ) - ) - ); - } - - /** - * Detect a Proxy that sets Forwarded-Host - */ - public function testHttpsProxyForwardedHost() - { - $this->assertEquals( - 'https://host.tld:8080', - server_url( - array( - 'HTTP_X_FORWARDED_PROTO' => 'https', - 'HTTP_X_FORWARDED_PORT' => '8080', - 'HTTP_X_FORWARDED_HOST' => 'host.tld' - ) - ) - ); - - $this->assertEquals( - 'https://host.tld:4974', - server_url( - array( - 'HTTP_X_FORWARDED_PROTO' => 'https, https', - 'HTTP_X_FORWARDED_PORT' => '4974, 80', - 'HTTP_X_FORWARDED_HOST' => 'host.tld, example.com' - ) - ) - ); - } - - /** - * Detect a Proxy with SSL enabled - */ - public function testHttpsProxyForward() - { - $this->assertEquals( - 'https://host.tld:8080', - server_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'https', - 'HTTP_X_FORWARDED_PORT' => '8080' - ) - ) - ); - - $this->assertEquals( - 'https://host.tld', - server_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'https' - ) - ) - ); - - $this->assertEquals( - 'https://host.tld', - server_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'https', - 'HTTP_X_FORWARDED_PORT' => '443' - ) - ) - ); - - $this->assertEquals( - 'https://host.tld:4974', - server_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'https, https', - 'HTTP_X_FORWARDED_PORT' => '4974, 80' - ) - ) - ); - } - - /** - * Detect if the server uses a specific port (!= 80) - */ - public function testPort() - { - // HTTP - $this->assertEquals( - 'http://host.tld:8080', - server_url( - array( - 'HTTPS' => 'OFF', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '8080' - ) - ) - ); - - // HTTPS - $this->assertEquals( - 'https://host.tld:8080', - server_url( - array( - 'HTTPS' => 'ON', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '8080' - ) - ) - ); - } - - /** - * HTTP server on port 80 - */ - public function testStandardHttpPort() - { - $this->assertEquals( - 'http://host.tld', - server_url( - array( - 'HTTPS' => 'OFF', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80' - ) - ) - ); - } - - /** - * HTTPS server on port 443 - */ - public function testStandardHttpsPort() - { - $this->assertEquals( - 'https://host.tld', - server_url( - array( - 'HTTPS' => 'ON', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '443' - ) - ) - ); - } - - /** - * Misconfigured server (see #1022): Proxy HTTP but 443 - */ - public function testHttpWithPort433() - { - $this->assertEquals( - 'https://host.tld', - server_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'http', - 'HTTP_X_FORWARDED_PORT' => '443' - ) - ) - ); - - $this->assertEquals( - 'https://host.tld', - server_url( - array( - 'HTTPS' => 'Off', - 'SERVER_NAME' => 'host.tld', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'https, http', - 'HTTP_X_FORWARDED_PORT' => '443, 80' - ) - ) - ); - } -} diff --git a/tests/Url/CleanupUrlTest.php b/tests/Url/CleanupUrlTest.php deleted file mode 100644 index 24791948..00000000 --- a/tests/Url/CleanupUrlTest.php +++ /dev/null @@ -1,109 +0,0 @@ -assertEquals('', cleanup_url('')); - } - - /** - * Clean an already cleaned URL - */ - public function testCleanupUrlAlreadyClean() - { - $this->assertEquals($this->ref, cleanup_url($this->ref)); - $this->ref2 = $this->ref.'/path/to/dir/'; - $this->assertEquals($this->ref2, cleanup_url($this->ref2)); - } - - /** - * Clean URL fragments - */ - public function testCleanupUrlFragment() - { - $this->assertEquals($this->ref, cleanup_url($this->ref.'#tk.rss_all')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'#xtor=RSS-')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'#xtor=RSS-U3ht0tkc4b')); - } - - /** - * Clean URL query - single annoying parameter - */ - public function testCleanupUrlQuerySingle() - { - $this->assertEquals($this->ref, cleanup_url($this->ref.'?action_object_map=junk')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?action_ref_map=Cr4p!')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?action_type_map=g4R84g3')); - - $this->assertEquals($this->ref, cleanup_url($this->ref.'?fb_stuff=v41u3')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?fb=71m3w4573')); - - $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_campaign=zomg')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_medium=numnum')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_source=c0d3')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_term=1n4l')); - - $this->assertEquals($this->ref, cleanup_url($this->ref.'?xtor=some-url')); - - $this->assertEquals($this->ref, cleanup_url($this->ref.'?campaign_name=junk')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?campaign_start=junk')); - $this->assertEquals($this->ref, cleanup_url($this->ref.'?campaign_item_index=junk')); - } - - /** - * Clean URL query - multiple annoying parameters - */ - public function testCleanupUrlQueryMultiple() - { - $this->assertEquals($this->ref, cleanup_url($this->ref.'?xtor=some-url&fb=som3th1ng')); - - $this->assertEquals($this->ref, cleanup_url( - $this->ref.'?fb=stuff&utm_campaign=zomg&utm_medium=numnum&utm_source=c0d3' - )); - - $this->assertEquals($this->ref, cleanup_url( - $this->ref.'?campaign_start=zomg&campaign_name=numnum' - )); - } - - /** - * Clean URL query - multiple annoying parameters and fragment - */ - public function testCleanupUrlQueryFragment() - { - $this->assertEquals($this->ref, cleanup_url( - $this->ref.'?xtor=some-url&fb=som3th1ng#tk.rss_all' - )); - - // ditch annoying query params and fragment, keep useful params - $this->assertEquals( - $this->ref.'?my=stuff&is=kept', - cleanup_url( - $this->ref.'?fb=zomg&my=stuff&utm_medium=numnum&is=kept#tk.rss_all' - ) - ); - - // ditch annoying query params, keep useful params and fragment - $this->assertEquals( - $this->ref.'?my=stuff&is=kept#again', - cleanup_url( - $this->ref.'?fb=zomg&my=stuff&utm_medium=numnum&is=kept#again' - ) - ); - } -} diff --git a/tests/Url/GetUrlSchemeTest.php b/tests/Url/GetUrlSchemeTest.php deleted file mode 100644 index 18b932d6..00000000 --- a/tests/Url/GetUrlSchemeTest.php +++ /dev/null @@ -1,30 +0,0 @@ -assertEquals('', get_url_scheme('')); - } - - /** - * Get normal scheme of Url - */ - public function testGetUrlScheme() - { - $this->assertEquals('http', get_url_scheme('http://domain.tld:3000')); - $this->assertEquals('https', get_url_scheme('https://domain.tld:3000')); - $this->assertEquals('http', get_url_scheme('domain.tld')); - $this->assertEquals('ssh', get_url_scheme('ssh://domain.tld')); - $this->assertEquals('ftp', get_url_scheme('ftp://domain.tld')); - $this->assertEquals('git', get_url_scheme('git://domain.tld/push?pull=clone#checkout')); - } -} diff --git a/tests/Url/UnparseUrlTest.php b/tests/Url/UnparseUrlTest.php deleted file mode 100644 index e314b484..00000000 --- a/tests/Url/UnparseUrlTest.php +++ /dev/null @@ -1,30 +0,0 @@ -assertEquals('', unparse_url(array())); - } - - /** - * Rebuild a full-featured URL - */ - public function testUnparseFull() - { - $ref = 'http://username:password@hostname:9090/path' - .'?arg1=value1&arg2=value2#anchor'; - $this->assertEquals($ref, unparse_url(parse_url($ref))); - } -} diff --git a/tests/Url/WhitelistProtocolsTest.php b/tests/Url/WhitelistProtocolsTest.php deleted file mode 100644 index a3156804..00000000 --- a/tests/Url/WhitelistProtocolsTest.php +++ /dev/null @@ -1,63 +0,0 @@ -assertEquals($url, whitelist_protocols($url, $whitelist)); - $url = '/path.jpg'; - $this->assertEquals($url, whitelist_protocols($url, $whitelist)); - } - - /** - * Test whitelist_protocols() on a note (relative URL). - */ - public function testWhitelistProtocolMissing() - { - $whitelist = ['ftp', 'magnet']; - $url = 'test.tld/path/?query=value#hash'; - $this->assertEquals('http://'. $url, whitelist_protocols($url, $whitelist)); - } - - /** - * Test whitelist_protocols() with allowed protocols. - */ - public function testWhitelistAllowedProtocol() - { - $whitelist = ['ftp', 'magnet']; - $url = 'http://test.tld/path/?query=value#hash'; - $this->assertEquals($url, whitelist_protocols($url, $whitelist)); - $url = 'https://test.tld/path/?query=value#hash'; - $this->assertEquals($url, whitelist_protocols($url, $whitelist)); - $url = 'ftp://test.tld/path/?query=value#hash'; - $this->assertEquals($url, whitelist_protocols($url, $whitelist)); - $url = 'magnet:test.tld/path/?query=value#hash'; - $this->assertEquals($url, whitelist_protocols($url, $whitelist)); - } - - /** - * Test whitelist_protocols() with allowed protocols. - */ - public function testWhitelistDisallowedProtocol() - { - $whitelist = ['ftp', 'magnet']; - $url = 'javascript:alert("xss");'; - $this->assertEquals('http://alert("xss");', whitelist_protocols($url, $whitelist)); - $url = 'other://test.tld/path/?query=value#hash'; - $this->assertEquals('http://test.tld/path/?query=value#hash', whitelist_protocols($url, $whitelist)); - } -} diff --git a/tests/http/HttpUtils/ClientIpIdTest.php b/tests/http/HttpUtils/ClientIpIdTest.php new file mode 100644 index 00000000..982e57e0 --- /dev/null +++ b/tests/http/HttpUtils/ClientIpIdTest.php @@ -0,0 +1,54 @@ +assertEquals( + '10.1.167.42', + client_ip_id(['REMOTE_ADDR' => '10.1.167.42']) + ); + } + + /** + * Get a remote client ID based on its IP and proxy information (1) + */ + public function testClientIpIdRemoteForwarded() + { + $this->assertEquals( + '10.1.167.42_127.0.1.47', + client_ip_id([ + 'REMOTE_ADDR' => '10.1.167.42', + 'HTTP_X_FORWARDED_FOR' => '127.0.1.47' + ]) + ); + } + + /** + * Get a remote client ID based on its IP and proxy information (2) + */ + public function testClientIpIdRemoteForwardedClient() + { + $this->assertEquals( + '10.1.167.42_10.1.167.56_127.0.1.47', + client_ip_id([ + 'REMOTE_ADDR' => '10.1.167.42', + 'HTTP_X_FORWARDED_FOR' => '10.1.167.56', + 'HTTP_CLIENT_IP' => '127.0.1.47' + ]) + ); + } +} diff --git a/tests/http/HttpUtils/GetHttpUrlTest.php b/tests/http/HttpUtils/GetHttpUrlTest.php new file mode 100644 index 00000000..3dc5bc9b --- /dev/null +++ b/tests/http/HttpUtils/GetHttpUrlTest.php @@ -0,0 +1,67 @@ +assertEquals('Invalid HTTP UrlUtils', $headers[0]); + $this->assertFalse($content); + + // Non HTTP + list($headers, $content) = get_http_response('ftp://save.tld/mysave', 1); + $this->assertEquals('Invalid HTTP UrlUtils', $headers[0]); + $this->assertFalse($content); + } + + /** + * Get an invalid remote URL + */ + public function testGetInvalidRemoteUrl() + { + list($headers, $content) = @get_http_response('http://non.existent', 1); + $this->assertFalse($headers); + $this->assertFalse($content); + } + + /** + * Test getAbsoluteUrl with relative target URL. + */ + public function testGetAbsoluteUrlWithRelative() + { + $origin = 'http://non.existent/blabla/?test'; + $target = '/stuff.php'; + + $expected = 'http://non.existent/stuff.php'; + $this->assertEquals($expected, getAbsoluteUrl($origin, $target)); + + $target = 'stuff.php'; + $expected = 'http://non.existent/blabla/stuff.php'; + $this->assertEquals($expected, getAbsoluteUrl($origin, $target)); + } + + /** + * Test getAbsoluteUrl with absolute target URL. + */ + public function testGetAbsoluteUrlWithAbsolute() + { + $origin = 'http://non.existent/blabla/?test'; + $target = 'http://other.url/stuff.php'; + + $this->assertEquals($target, getAbsoluteUrl($origin, $target)); + } +} diff --git a/tests/http/HttpUtils/GetIpAdressFromProxyTest.php b/tests/http/HttpUtils/GetIpAdressFromProxyTest.php new file mode 100644 index 00000000..fe3a639e --- /dev/null +++ b/tests/http/HttpUtils/GetIpAdressFromProxyTest.php @@ -0,0 +1,61 @@ +assertFalse(getIpAddressFromProxy(array(), array())); + } + + /** + * Test with a single IP in proxy header. + */ + public function testWithOneForwardedIp() + { + $ip = '1.1.1.1'; + $server = array('HTTP_X_FORWARDED_FOR' => $ip); + $this->assertEquals($ip, getIpAddressFromProxy($server, array())); + } + + /** + * Test with a multiple IPs in proxy header. + */ + public function testWithMultipleForwardedIp() + { + $ip = '1.1.1.1'; + $ip2 = '2.2.2.2'; + + $server = array('HTTP_X_FORWARDED_FOR' => $ip .','. $ip2); + $this->assertEquals($ip2, getIpAddressFromProxy($server, array())); + + $server = array('HTTP_X_FORWARDED_FOR' => $ip .' , '. $ip2); + $this->assertEquals($ip2, getIpAddressFromProxy($server, array())); + } + + /** + * Test with a trusted IP address. + */ + public function testWithTrustedIp() + { + $ip = '1.1.1.1'; + $ip2 = '2.2.2.2'; + + $server = array('HTTP_X_FORWARDED_FOR' => $ip); + $this->assertFalse(getIpAddressFromProxy($server, array($ip))); + + $server = array('HTTP_X_FORWARDED_FOR' => $ip .','. $ip2); + $this->assertEquals($ip2, getIpAddressFromProxy($server, array($ip))); + $this->assertFalse(getIpAddressFromProxy($server, array($ip, $ip2))); + } +} diff --git a/tests/http/HttpUtils/IndexUrlTest.php b/tests/http/HttpUtils/IndexUrlTest.php new file mode 100644 index 00000000..bcbe59cb --- /dev/null +++ b/tests/http/HttpUtils/IndexUrlTest.php @@ -0,0 +1,74 @@ +assertEquals( + 'http://host.tld/', + index_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/index.php' + ) + ) + ); + + $this->assertEquals( + 'http://host.tld/admin/', + index_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/admin/index.php' + ) + ) + ); + } + + /** + * The resource is != "index.php" + */ + public function testOtherResource() + { + $this->assertEquals( + 'http://host.tld/page.php', + page_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/page.php' + ) + ) + ); + + $this->assertEquals( + 'http://host.tld/admin/page.php', + page_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/admin/page.php' + ) + ) + ); + } +} diff --git a/tests/http/HttpUtils/IsHttpsTest.php b/tests/http/HttpUtils/IsHttpsTest.php new file mode 100644 index 00000000..348956c6 --- /dev/null +++ b/tests/http/HttpUtils/IsHttpsTest.php @@ -0,0 +1,39 @@ +assertTrue(is_https(['HTTPS' => true])); + $this->assertTrue(is_https(['HTTPS' => '1'])); + $this->assertTrue(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => 443])); + $this->assertTrue(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => '443'])); + $this->assertTrue(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => '443,123,456,'])); + } + + /** + * Test is_https with HTTP values. + */ + public function testIsHttpsFalse() + { + $this->assertFalse(is_https([])); + $this->assertFalse(is_https(['HTTPS' => false])); + $this->assertFalse(is_https(['HTTPS' => '0'])); + $this->assertFalse(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => 123])); + $this->assertFalse(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => '123'])); + $this->assertFalse(is_https(['HTTPS' => false, 'HTTP_X_FORWARDED_PORT' => ',123,456,'])); + } +} diff --git a/tests/http/HttpUtils/PageUrlTest.php b/tests/http/HttpUtils/PageUrlTest.php new file mode 100644 index 00000000..f1991716 --- /dev/null +++ b/tests/http/HttpUtils/PageUrlTest.php @@ -0,0 +1,78 @@ +assertEquals( + 'http://host.tld/?p1=v1&p2=v2', + page_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/index.php', + 'QUERY_STRING' => 'p1=v1&p2=v2' + ) + ) + ); + + $this->assertEquals( + 'http://host.tld/admin/?action=edit_tag', + page_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/admin/index.php', + 'QUERY_STRING' => 'action=edit_tag' + ) + ) + ); + } + + /** + * The resource is != "index.php" + */ + public function testOtherResource() + { + $this->assertEquals( + 'http://host.tld/page.php?p1=v1&p2=v2', + page_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/page.php', + 'QUERY_STRING' => 'p1=v1&p2=v2' + ) + ) + ); + + $this->assertEquals( + 'http://host.tld/admin/page.php?action=edit_tag', + page_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'SCRIPT_NAME' => '/admin/page.php', + 'QUERY_STRING' => 'action=edit_tag' + ) + ) + ); + } +} diff --git a/tests/http/HttpUtils/ServerUrlTest.php b/tests/http/HttpUtils/ServerUrlTest.php new file mode 100644 index 00000000..9caf1049 --- /dev/null +++ b/tests/http/HttpUtils/ServerUrlTest.php @@ -0,0 +1,223 @@ +assertEquals( + 'https://host.tld', + server_url( + array( + 'HTTPS' => 'ON', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '443' + ) + ) + ); + + $this->assertEquals( + 'https://host.tld:8080', + server_url( + array( + 'HTTPS' => 'ON', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '8080' + ) + ) + ); + } + + /** + * Detect a Proxy that sets Forwarded-Host + */ + public function testHttpsProxyForwardedHost() + { + $this->assertEquals( + 'https://host.tld:8080', + server_url( + array( + 'HTTP_X_FORWARDED_PROTO' => 'https', + 'HTTP_X_FORWARDED_PORT' => '8080', + 'HTTP_X_FORWARDED_HOST' => 'host.tld' + ) + ) + ); + + $this->assertEquals( + 'https://host.tld:4974', + server_url( + array( + 'HTTP_X_FORWARDED_PROTO' => 'https, https', + 'HTTP_X_FORWARDED_PORT' => '4974, 80', + 'HTTP_X_FORWARDED_HOST' => 'host.tld, example.com' + ) + ) + ); + } + + /** + * Detect a Proxy with SSL enabled + */ + public function testHttpsProxyForward() + { + $this->assertEquals( + 'https://host.tld:8080', + server_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'HTTP_X_FORWARDED_PROTO' => 'https', + 'HTTP_X_FORWARDED_PORT' => '8080' + ) + ) + ); + + $this->assertEquals( + 'https://host.tld', + server_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'HTTP_X_FORWARDED_PROTO' => 'https' + ) + ) + ); + + $this->assertEquals( + 'https://host.tld', + server_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'HTTP_X_FORWARDED_PROTO' => 'https', + 'HTTP_X_FORWARDED_PORT' => '443' + ) + ) + ); + + $this->assertEquals( + 'https://host.tld:4974', + server_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'HTTP_X_FORWARDED_PROTO' => 'https, https', + 'HTTP_X_FORWARDED_PORT' => '4974, 80' + ) + ) + ); + } + + /** + * Detect if the server uses a specific port (!= 80) + */ + public function testPort() + { + // HTTP + $this->assertEquals( + 'http://host.tld:8080', + server_url( + array( + 'HTTPS' => 'OFF', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '8080' + ) + ) + ); + + // HTTPS + $this->assertEquals( + 'https://host.tld:8080', + server_url( + array( + 'HTTPS' => 'ON', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '8080' + ) + ) + ); + } + + /** + * HTTP server on port 80 + */ + public function testStandardHttpPort() + { + $this->assertEquals( + 'http://host.tld', + server_url( + array( + 'HTTPS' => 'OFF', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80' + ) + ) + ); + } + + /** + * HTTPS server on port 443 + */ + public function testStandardHttpsPort() + { + $this->assertEquals( + 'https://host.tld', + server_url( + array( + 'HTTPS' => 'ON', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '443' + ) + ) + ); + } + + /** + * Misconfigured server (see #1022): Proxy HTTP but 443 + */ + public function testHttpWithPort433() + { + $this->assertEquals( + 'https://host.tld', + server_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'HTTP_X_FORWARDED_PROTO' => 'http', + 'HTTP_X_FORWARDED_PORT' => '443' + ) + ) + ); + + $this->assertEquals( + 'https://host.tld', + server_url( + array( + 'HTTPS' => 'Off', + 'SERVER_NAME' => 'host.tld', + 'SERVER_PORT' => '80', + 'HTTP_X_FORWARDED_PROTO' => 'https, http', + 'HTTP_X_FORWARDED_PORT' => '443, 80' + ) + ) + ); + } +} diff --git a/tests/http/UrlTest.php b/tests/http/UrlTest.php index 011b416d..342b78a4 100644 --- a/tests/http/UrlTest.php +++ b/tests/http/UrlTest.php @@ -1,6 +1,6 @@ assertEquals('', cleanup_url('')); + } + + /** + * Clean an already cleaned URL + */ + public function testCleanupUrlAlreadyClean() + { + $this->assertEquals($this->ref, cleanup_url($this->ref)); + $this->ref2 = $this->ref.'/path/to/dir/'; + $this->assertEquals($this->ref2, cleanup_url($this->ref2)); + } + + /** + * Clean URL fragments + */ + public function testCleanupUrlFragment() + { + $this->assertEquals($this->ref, cleanup_url($this->ref.'#tk.rss_all')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'#xtor=RSS-')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'#xtor=RSS-U3ht0tkc4b')); + } + + /** + * Clean URL query - single annoying parameter + */ + public function testCleanupUrlQuerySingle() + { + $this->assertEquals($this->ref, cleanup_url($this->ref.'?action_object_map=junk')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?action_ref_map=Cr4p!')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?action_type_map=g4R84g3')); + + $this->assertEquals($this->ref, cleanup_url($this->ref.'?fb_stuff=v41u3')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?fb=71m3w4573')); + + $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_campaign=zomg')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_medium=numnum')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_source=c0d3')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?utm_term=1n4l')); + + $this->assertEquals($this->ref, cleanup_url($this->ref.'?xtor=some-url')); + + $this->assertEquals($this->ref, cleanup_url($this->ref.'?campaign_name=junk')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?campaign_start=junk')); + $this->assertEquals($this->ref, cleanup_url($this->ref.'?campaign_item_index=junk')); + } + + /** + * Clean URL query - multiple annoying parameters + */ + public function testCleanupUrlQueryMultiple() + { + $this->assertEquals($this->ref, cleanup_url($this->ref.'?xtor=some-url&fb=som3th1ng')); + + $this->assertEquals($this->ref, cleanup_url( + $this->ref.'?fb=stuff&utm_campaign=zomg&utm_medium=numnum&utm_source=c0d3' + )); + + $this->assertEquals($this->ref, cleanup_url( + $this->ref.'?campaign_start=zomg&campaign_name=numnum' + )); + } + + /** + * Clean URL query - multiple annoying parameters and fragment + */ + public function testCleanupUrlQueryFragment() + { + $this->assertEquals($this->ref, cleanup_url( + $this->ref.'?xtor=some-url&fb=som3th1ng#tk.rss_all' + )); + + // ditch annoying query params and fragment, keep useful params + $this->assertEquals( + $this->ref.'?my=stuff&is=kept', + cleanup_url( + $this->ref.'?fb=zomg&my=stuff&utm_medium=numnum&is=kept#tk.rss_all' + ) + ); + + // ditch annoying query params, keep useful params and fragment + $this->assertEquals( + $this->ref.'?my=stuff&is=kept#again', + cleanup_url( + $this->ref.'?fb=zomg&my=stuff&utm_medium=numnum&is=kept#again' + ) + ); + } +} diff --git a/tests/http/UrlUtils/GetUrlSchemeTest.php b/tests/http/UrlUtils/GetUrlSchemeTest.php new file mode 100644 index 00000000..2b97f7be --- /dev/null +++ b/tests/http/UrlUtils/GetUrlSchemeTest.php @@ -0,0 +1,32 @@ +assertEquals('', get_url_scheme('')); + } + + /** + * Get normal scheme of UrlUtils + */ + public function testGetUrlScheme() + { + $this->assertEquals('http', get_url_scheme('http://domain.tld:3000')); + $this->assertEquals('https', get_url_scheme('https://domain.tld:3000')); + $this->assertEquals('http', get_url_scheme('domain.tld')); + $this->assertEquals('ssh', get_url_scheme('ssh://domain.tld')); + $this->assertEquals('ftp', get_url_scheme('ftp://domain.tld')); + $this->assertEquals('git', get_url_scheme('git://domain.tld/push?pull=clone#checkout')); + } +} diff --git a/tests/http/UrlUtils/UnparseUrlTest.php b/tests/http/UrlUtils/UnparseUrlTest.php new file mode 100644 index 00000000..040d8c54 --- /dev/null +++ b/tests/http/UrlUtils/UnparseUrlTest.php @@ -0,0 +1,32 @@ +assertEquals('', unparse_url(array())); + } + + /** + * Rebuild a full-featured URL + */ + public function testUnparseFull() + { + $ref = 'http://username:password@hostname:9090/path' + .'?arg1=value1&arg2=value2#anchor'; + $this->assertEquals($ref, unparse_url(parse_url($ref))); + } +} diff --git a/tests/http/UrlUtils/WhitelistProtocolsTest.php b/tests/http/UrlUtils/WhitelistProtocolsTest.php new file mode 100644 index 00000000..69512dbd --- /dev/null +++ b/tests/http/UrlUtils/WhitelistProtocolsTest.php @@ -0,0 +1,63 @@ +assertEquals($url, whitelist_protocols($url, $whitelist)); + $url = '/path.jpg'; + $this->assertEquals($url, whitelist_protocols($url, $whitelist)); + } + + /** + * Test whitelist_protocols() on a note (relative URL). + */ + public function testWhitelistProtocolMissing() + { + $whitelist = ['ftp', 'magnet']; + $url = 'test.tld/path/?query=value#hash'; + $this->assertEquals('http://'. $url, whitelist_protocols($url, $whitelist)); + } + + /** + * Test whitelist_protocols() with allowed protocols. + */ + public function testWhitelistAllowedProtocol() + { + $whitelist = ['ftp', 'magnet']; + $url = 'http://test.tld/path/?query=value#hash'; + $this->assertEquals($url, whitelist_protocols($url, $whitelist)); + $url = 'https://test.tld/path/?query=value#hash'; + $this->assertEquals($url, whitelist_protocols($url, $whitelist)); + $url = 'ftp://test.tld/path/?query=value#hash'; + $this->assertEquals($url, whitelist_protocols($url, $whitelist)); + $url = 'magnet:test.tld/path/?query=value#hash'; + $this->assertEquals($url, whitelist_protocols($url, $whitelist)); + } + + /** + * Test whitelist_protocols() with allowed protocols. + */ + public function testWhitelistDisallowedProtocol() + { + $whitelist = ['ftp', 'magnet']; + $url = 'javascript:alert("xss");'; + $this->assertEquals('http://alert("xss");', whitelist_protocols($url, $whitelist)); + $url = 'other://test.tld/path/?query=value#hash'; + $this->assertEquals('http://test.tld/path/?query=value#hash', whitelist_protocols($url, $whitelist)); + } +} -- cgit v1.2.3 From 8c0f19c7971e1a4534347ce9d6d82a0a45799711 Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 00:46:04 +0100 Subject: namespacing: \Shaarli\Render\{PageBuilder,ThemeUtils} Signed-off-by: VirtualTam --- tests/ThemeUtilsTest.php | 55 ----------------------------------------- tests/render/ThemeUtilsTest.php | 55 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 55 deletions(-) delete mode 100644 tests/ThemeUtilsTest.php create mode 100644 tests/render/ThemeUtilsTest.php (limited to 'tests') diff --git a/tests/ThemeUtilsTest.php b/tests/ThemeUtilsTest.php deleted file mode 100644 index e44564be..00000000 --- a/tests/ThemeUtilsTest.php +++ /dev/null @@ -1,55 +0,0 @@ -assertTrue(in_array($theme, $themes)); - } - $this->assertFalse(in_array('supertheme', $res)); - - foreach ($themes as $theme) { - rmdir('sandbox/tpl/'. $theme); - } - unlink('sandbox/tpl/supertheme'); - rmdir('sandbox/tpl'); - } - - /** - * Test getThemes() without any theme dir. - */ - public function testGetThemesEmpty() - { - mkdir('sandbox/tpl/', 0755, true); - $this->assertEquals([], ThemeUtils::getThemes('sandbox/tpl/')); - rmdir('sandbox/tpl/'); - } - - /** - * Test getThemes() with an invalid path. - */ - public function testGetThemesInvalid() - { - $this->assertEquals([], ThemeUtils::getThemes('nope')); - } -} diff --git a/tests/render/ThemeUtilsTest.php b/tests/render/ThemeUtilsTest.php new file mode 100644 index 00000000..6159a1bd --- /dev/null +++ b/tests/render/ThemeUtilsTest.php @@ -0,0 +1,55 @@ +assertTrue(in_array($theme, $themes)); + } + $this->assertFalse(in_array('supertheme', $res)); + + foreach ($themes as $theme) { + rmdir('sandbox/tpl/'. $theme); + } + unlink('sandbox/tpl/supertheme'); + rmdir('sandbox/tpl'); + } + + /** + * Test getThemes() without any theme dir. + */ + public function testGetThemesEmpty() + { + mkdir('sandbox/tpl/', 0755, true); + $this->assertEquals([], ThemeUtils::getThemes('sandbox/tpl/')); + rmdir('sandbox/tpl/'); + } + + /** + * Test getThemes() with an invalid path. + */ + public function testGetThemesInvalid() + { + $this->assertEquals([], ThemeUtils::getThemes('nope')); + } +} -- cgit v1.2.3 From a0c4dbd91c41b9ecdd5176c1ac33b55e240d2392 Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 00:59:21 +0100 Subject: namespacing: \Shaarli\FileUtils Signed-off-by: VirtualTam --- tests/FileUtilsTest.php | 6 +++--- tests/HistoryTest.php | 1 - tests/utils/ReferenceHistory.php | 1 + 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'tests') diff --git a/tests/FileUtilsTest.php b/tests/FileUtilsTest.php index 9596dba9..57719175 100644 --- a/tests/FileUtilsTest.php +++ b/tests/FileUtilsTest.php @@ -1,15 +1,15 @@ Date: Mon, 3 Dec 2018 01:10:39 +0100 Subject: namespacing: \Shaarli\Bookmark\LinkDB Signed-off-by: VirtualTam --- tests/LinkDBTest.php | 647 -------------------- tests/LinkFilterTest.php | 2 + tests/NetscapeBookmarkUtils/BookmarkExportTest.php | 2 + tests/NetscapeBookmarkUtils/BookmarkImportTest.php | 1 + tests/Updater/DummyUpdater.php | 2 + tests/Updater/UpdaterTest.php | 2 + tests/api/controllers/info/InfoTest.php | 2 +- tests/api/controllers/links/DeleteLinkTest.php | 6 +- tests/api/controllers/links/GetLinkIdTest.php | 4 +- tests/api/controllers/links/GetLinksTest.php | 6 +- tests/api/controllers/links/PostLinkTest.php | 6 +- tests/api/controllers/links/PutLinkTest.php | 6 +- tests/api/controllers/tags/DeleteTagTest.php | 8 +- tests/api/controllers/tags/GetTagNameTest.php | 2 +- tests/api/controllers/tags/GetTagsTest.php | 4 +- tests/api/controllers/tags/PutTagTest.php | 4 +- tests/bookmark/LinkDBTest.php | 653 +++++++++++++++++++++ tests/feed/FeedBuilderTest.php | 4 +- tests/http/UrlTest.php | 1 - tests/plugins/PluginIssoTest.php | 2 + tests/utils/ReferenceLinkDB.php | 3 + 21 files changed, 692 insertions(+), 675 deletions(-) delete mode 100644 tests/LinkDBTest.php create mode 100644 tests/bookmark/LinkDBTest.php (limited to 'tests') diff --git a/tests/LinkDBTest.php b/tests/LinkDBTest.php deleted file mode 100644 index 737a2247..00000000 --- a/tests/LinkDBTest.php +++ /dev/null @@ -1,647 +0,0 @@ -write(self::$testDatastore); - - self::$publicLinkDB = new LinkDB(self::$testDatastore, false, false); - self::$privateLinkDB = new LinkDB(self::$testDatastore, true, false); - } - - /** - * Resets test data for each test - */ - protected function setUp() - { - if (file_exists(self::$testDatastore)) { - unlink(self::$testDatastore); - } - } - - /** - * Allows to test LinkDB's private methods - * - * @see - * https://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html - * http://stackoverflow.com/a/2798203 - */ - protected static function getMethod($name) - { - $class = new ReflectionClass('LinkDB'); - $method = $class->getMethod($name); - $method->setAccessible(true); - return $method; - } - - /** - * Instantiate LinkDB objects - logged in user - */ - public function testConstructLoggedIn() - { - new LinkDB(self::$testDatastore, true, false); - $this->assertFileExists(self::$testDatastore); - } - - /** - * Instantiate LinkDB objects - logged out or public instance - */ - public function testConstructLoggedOut() - { - new LinkDB(self::$testDatastore, false, false); - $this->assertFileExists(self::$testDatastore); - } - - /** - * Attempt to instantiate a LinkDB whereas the datastore is not writable - * - * @expectedException Shaarli\Exceptions\IOException - * @expectedExceptionMessageRegExp /Error accessing "null"/ - */ - public function testConstructDatastoreNotWriteable() - { - new LinkDB('null/store.db', false, false); - } - - /** - * The DB doesn't exist, ensure it is created with dummy content - */ - public function testCheckDBNew() - { - $linkDB = new LinkDB(self::$testDatastore, false, false); - unlink(self::$testDatastore); - $this->assertFileNotExists(self::$testDatastore); - - $checkDB = self::getMethod('check'); - $checkDB->invokeArgs($linkDB, array()); - $this->assertFileExists(self::$testDatastore); - - // ensure the correct data has been written - $this->assertGreaterThan(0, filesize(self::$testDatastore)); - } - - /** - * The DB exists, don't do anything - */ - public function testCheckDBLoad() - { - $linkDB = new LinkDB(self::$testDatastore, false, false); - $datastoreSize = filesize(self::$testDatastore); - $this->assertGreaterThan(0, $datastoreSize); - - $checkDB = self::getMethod('check'); - $checkDB->invokeArgs($linkDB, array()); - - // ensure the datastore is left unmodified - $this->assertEquals( - $datastoreSize, - filesize(self::$testDatastore) - ); - } - - /** - * Load an empty DB - */ - public function testReadEmptyDB() - { - file_put_contents(self::$testDatastore, ''); - $emptyDB = new LinkDB(self::$testDatastore, false, false); - $this->assertEquals(0, sizeof($emptyDB)); - $this->assertEquals(0, count($emptyDB)); - } - - /** - * Load public links from the DB - */ - public function testReadPublicDB() - { - $this->assertEquals( - self::$refDB->countPublicLinks(), - sizeof(self::$publicLinkDB) - ); - } - - /** - * Load public and private links from the DB - */ - public function testReadPrivateDB() - { - $this->assertEquals( - self::$refDB->countLinks(), - sizeof(self::$privateLinkDB) - ); - } - - /** - * Save the links to the DB - */ - public function testSave() - { - $testDB = new LinkDB(self::$testDatastore, true, false); - $dbSize = sizeof($testDB); - - $link = array( - 'id' => 42, - 'title'=>'an additional link', - 'url'=>'http://dum.my', - 'description'=>'One more', - 'private'=>0, - 'created'=> DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150518_190000'), - 'tags'=>'unit test' - ); - $testDB[$link['id']] = $link; - $testDB->save('tests'); - - $testDB = new LinkDB(self::$testDatastore, true, false); - $this->assertEquals($dbSize + 1, sizeof($testDB)); - } - - /** - * Count existing links - */ - public function testCount() - { - $this->assertEquals( - self::$refDB->countPublicLinks(), - self::$publicLinkDB->count() - ); - $this->assertEquals( - self::$refDB->countLinks(), - self::$privateLinkDB->count() - ); - } - - /** - * Count existing links - public links hidden - */ - public function testCountHiddenPublic() - { - $linkDB = new LinkDB(self::$testDatastore, false, true); - - $this->assertEquals( - 0, - $linkDB->count() - ); - $this->assertEquals( - 0, - $linkDB->count() - ); - } - - /** - * List the days for which links have been posted - */ - public function testDays() - { - $this->assertEquals( - array('20100309', '20100310', '20121206', '20121207', '20130614', '20150310'), - self::$publicLinkDB->days() - ); - - $this->assertEquals( - array('20100309', '20100310', '20121206', '20121207', '20130614', '20141125', '20150310'), - self::$privateLinkDB->days() - ); - } - - /** - * The URL corresponds to an existing entry in the DB - */ - public function testGetKnownLinkFromURL() - { - $link = self::$publicLinkDB->getLinkFromUrl('http://mediagoblin.org/'); - - $this->assertNotEquals(false, $link); - $this->assertContains( - 'A free software media publishing platform', - $link['description'] - ); - } - - /** - * The URL is not in the DB - */ - public function testGetUnknownLinkFromURL() - { - $this->assertEquals( - false, - self::$publicLinkDB->getLinkFromUrl('http://dev.null') - ); - } - - /** - * Lists all tags - */ - public function testAllTags() - { - $this->assertEquals( - array( - 'web' => 3, - 'cartoon' => 2, - 'gnu' => 2, - 'dev' => 1, - 'samba' => 1, - 'media' => 1, - 'software' => 1, - 'stallman' => 1, - 'free' => 1, - '-exclude' => 1, - 'hashtag' => 2, - // The DB contains a link with `sTuff` and another one with `stuff` tag. - // They need to be grouped with the first case found - order by date DESC: `sTuff`. - 'sTuff' => 2, - 'ut' => 1, - ), - self::$publicLinkDB->linksCountPerTag() - ); - - $this->assertEquals( - array( - 'web' => 4, - 'cartoon' => 3, - 'gnu' => 2, - 'dev' => 2, - 'samba' => 1, - 'media' => 1, - 'software' => 1, - 'stallman' => 1, - 'free' => 1, - 'html' => 1, - 'w3c' => 1, - 'css' => 1, - 'Mercurial' => 1, - 'sTuff' => 2, - '-exclude' => 1, - '.hidden' => 1, - 'hashtag' => 2, - 'tag1' => 1, - 'tag2' => 1, - 'tag3' => 1, - 'tag4' => 1, - 'ut' => 1, - ), - self::$privateLinkDB->linksCountPerTag() - ); - $this->assertEquals( - array( - 'web' => 4, - 'cartoon' => 2, - 'gnu' => 1, - 'dev' => 1, - 'samba' => 1, - 'media' => 1, - 'html' => 1, - 'w3c' => 1, - 'css' => 1, - 'Mercurial' => 1, - '.hidden' => 1, - 'hashtag' => 1, - ), - self::$privateLinkDB->linksCountPerTag(['web']) - ); - $this->assertEquals( - array( - 'web' => 1, - 'html' => 1, - 'w3c' => 1, - 'css' => 1, - 'Mercurial' => 1, - ), - self::$privateLinkDB->linksCountPerTag(['web'], 'private') - ); - } - - /** - * Test real_url without redirector. - */ - public function testLinkRealUrlWithoutRedirector() - { - $db = new LinkDB(self::$testDatastore, false, false); - foreach ($db as $link) { - $this->assertEquals($link['url'], $link['real_url']); - } - } - - /** - * Test real_url with redirector. - */ - public function testLinkRealUrlWithRedirector() - { - $redirector = 'http://redirector.to?'; - $db = new LinkDB(self::$testDatastore, false, false, $redirector); - foreach ($db as $link) { - $this->assertStringStartsWith($redirector, $link['real_url']); - $this->assertNotFalse(strpos($link['real_url'], urlencode('://'))); - } - - $db = new LinkDB(self::$testDatastore, false, false, $redirector, false); - foreach ($db as $link) { - $this->assertStringStartsWith($redirector, $link['real_url']); - $this->assertFalse(strpos($link['real_url'], urlencode('://'))); - } - } - - /** - * Test filter with string. - */ - public function testFilterString() - { - $tags = 'dev cartoon'; - $request = array('searchtags' => $tags); - $this->assertEquals( - 2, - count(self::$privateLinkDB->filterSearch($request, true, false)) - ); - } - - /** - * Test filter with string. - */ - public function testFilterArray() - { - $tags = array('dev', 'cartoon'); - $request = array('searchtags' => $tags); - $this->assertEquals( - 2, - count(self::$privateLinkDB->filterSearch($request, true, false)) - ); - } - - /** - * Test hidden tags feature: - * tags starting with a dot '.' are only visible when logged in. - */ - public function testHiddenTags() - { - $tags = '.hidden'; - $request = array('searchtags' => $tags); - $this->assertEquals( - 1, - count(self::$privateLinkDB->filterSearch($request, true, false)) - ); - - $this->assertEquals( - 0, - count(self::$publicLinkDB->filterSearch($request, true, false)) - ); - } - - /** - * Test filterHash() with a valid smallhash. - */ - public function testFilterHashValid() - { - $request = smallHash('20150310_114651'); - $this->assertEquals( - 1, - count(self::$publicLinkDB->filterHash($request)) - ); - $request = smallHash('20150310_114633' . 8); - $this->assertEquals( - 1, - count(self::$publicLinkDB->filterHash($request)) - ); - } - - /** - * Test filterHash() with an invalid smallhash. - * - * @expectedException LinkNotFoundException - */ - public function testFilterHashInValid1() - { - $request = 'blabla'; - self::$publicLinkDB->filterHash($request); - } - - /** - * Test filterHash() with an empty smallhash. - * - * @expectedException LinkNotFoundException - */ - public function testFilterHashInValid() - { - self::$publicLinkDB->filterHash(''); - } - - /** - * Test reorder with asc/desc parameter. - */ - public function testReorderLinksDesc() - { - self::$privateLinkDB->reorder('ASC'); - $stickyIds = [11, 10]; - $standardIds = [42, 4, 9, 1, 0, 7, 6, 8, 41]; - $linkIds = array_merge($stickyIds, $standardIds); - $cpt = 0; - foreach (self::$privateLinkDB as $key => $value) { - $this->assertEquals($linkIds[$cpt++], $key); - } - self::$privateLinkDB->reorder('DESC'); - $linkIds = array_merge(array_reverse($stickyIds), array_reverse($standardIds)); - $cpt = 0; - foreach (self::$privateLinkDB as $key => $value) { - $this->assertEquals($linkIds[$cpt++], $key); - } - } - - /** - * Test rename tag with a valid value present in multiple links - */ - public function testRenameTagMultiple() - { - self::$refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $res = $linkDB->renameTag('cartoon', 'Taz'); - $this->assertEquals(3, count($res)); - $this->assertContains(' Taz ', $linkDB[4]['tags']); - $this->assertContains(' Taz ', $linkDB[1]['tags']); - $this->assertContains(' Taz ', $linkDB[0]['tags']); - } - - /** - * Test rename tag with a valid value - */ - public function testRenameTagCaseSensitive() - { - self::$refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false, ''); - - $res = $linkDB->renameTag('sTuff', 'Taz'); - $this->assertEquals(1, count($res)); - $this->assertEquals('Taz', $linkDB[41]['tags']); - } - - /** - * Test rename tag with invalid values - */ - public function testRenameTagInvalid() - { - $linkDB = new LinkDB(self::$testDatastore, false, false); - - $this->assertFalse($linkDB->renameTag('', 'test')); - $this->assertFalse($linkDB->renameTag('', '')); - // tag non existent - $this->assertEquals([], $linkDB->renameTag('test', '')); - $this->assertEquals([], $linkDB->renameTag('test', 'retest')); - } - - /** - * Test delete tag with a valid value - */ - public function testDeleteTag() - { - self::$refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $res = $linkDB->renameTag('cartoon', null); - $this->assertEquals(3, count($res)); - $this->assertNotContains('cartoon', $linkDB[4]['tags']); - } - - /** - * Test linksCountPerTag all tags without filter. - * Equal occurrences should be sorted alphabetically. - */ - public function testCountLinkPerTagAllNoFilter() - { - $expected = [ - 'web' => 4, - 'cartoon' => 3, - 'dev' => 2, - 'gnu' => 2, - 'hashtag' => 2, - 'sTuff' => 2, - '-exclude' => 1, - '.hidden' => 1, - 'Mercurial' => 1, - 'css' => 1, - 'free' => 1, - 'html' => 1, - 'media' => 1, - 'samba' => 1, - 'software' => 1, - 'stallman' => 1, - 'tag1' => 1, - 'tag2' => 1, - 'tag3' => 1, - 'tag4' => 1, - 'ut' => 1, - 'w3c' => 1, - ]; - $tags = self::$privateLinkDB->linksCountPerTag(); - - $this->assertEquals($expected, $tags, var_export($tags, true)); - } - - /** - * Test linksCountPerTag all tags with filter. - * Equal occurrences should be sorted alphabetically. - */ - public function testCountLinkPerTagAllWithFilter() - { - $expected = [ - 'gnu' => 2, - 'hashtag' => 2, - '-exclude' => 1, - '.hidden' => 1, - 'free' => 1, - 'media' => 1, - 'software' => 1, - 'stallman' => 1, - 'stuff' => 1, - 'web' => 1, - ]; - $tags = self::$privateLinkDB->linksCountPerTag(['gnu']); - - $this->assertEquals($expected, $tags, var_export($tags, true)); - } - - /** - * Test linksCountPerTag public tags with filter. - * Equal occurrences should be sorted alphabetically. - */ - public function testCountLinkPerTagPublicWithFilter() - { - $expected = [ - 'gnu' => 2, - 'hashtag' => 2, - '-exclude' => 1, - '.hidden' => 1, - 'free' => 1, - 'media' => 1, - 'software' => 1, - 'stallman' => 1, - 'stuff' => 1, - 'web' => 1, - ]; - $tags = self::$privateLinkDB->linksCountPerTag(['gnu'], 'public'); - - $this->assertEquals($expected, $tags, var_export($tags, true)); - } - - /** - * Test linksCountPerTag public tags with filter. - * Equal occurrences should be sorted alphabetically. - */ - public function testCountLinkPerTagPrivateWithFilter() - { - $expected = [ - 'cartoon' => 1, - 'dev' => 1, - 'tag1' => 1, - 'tag2' => 1, - 'tag3' => 1, - 'tag4' => 1, - ]; - $tags = self::$privateLinkDB->linksCountPerTag(['dev'], 'private'); - - $this->assertEquals($expected, $tags, var_export($tags, true)); - } -} diff --git a/tests/LinkFilterTest.php b/tests/LinkFilterTest.php index eb54c359..db28b1c4 100644 --- a/tests/LinkFilterTest.php +++ b/tests/LinkFilterTest.php @@ -1,5 +1,7 @@ container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['history'] = null; $this->controller = new Info($this->container); diff --git a/tests/api/controllers/links/DeleteLinkTest.php b/tests/api/controllers/links/DeleteLinkTest.php index 07371e7a..adca9a4e 100644 --- a/tests/api/controllers/links/DeleteLinkTest.php +++ b/tests/api/controllers/links/DeleteLinkTest.php @@ -32,7 +32,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \LinkDB instance. + * @var \Shaarli\Bookmark\LinkDB instance. */ protected $linkDB; @@ -59,7 +59,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase $this->conf = new ConfigManager('tests/utils/config/configJson'); $this->refDB = new \ReferenceLinkDB(); $this->refDB->write(self::$testDatastore); - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); $this->history = new \Shaarli\History(self::$testHistory); @@ -96,7 +96,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase $this->assertEquals(204, $response->getStatusCode()); $this->assertEmpty((string) $response->getBody()); - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->assertFalse(isset($this->linkDB[$id])); $historyEntry = $this->history->getHistory()[0]; diff --git a/tests/api/controllers/links/GetLinkIdTest.php b/tests/api/controllers/links/GetLinkIdTest.php index 57528d5a..bf58000b 100644 --- a/tests/api/controllers/links/GetLinkIdTest.php +++ b/tests/api/controllers/links/GetLinkIdTest.php @@ -61,7 +61,7 @@ class GetLinkIdTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['history'] = null; $this->controller = new Links($this->container); @@ -108,7 +108,7 @@ class GetLinkIdTest extends \PHPUnit_Framework_TestCase $this->assertEquals('sTuff', $data['tags'][0]); $this->assertEquals(false, $data['private']); $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20150310_114651')->format(\DateTime::ATOM), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20150310_114651')->format(\DateTime::ATOM), $data['created'] ); $this->assertEmpty($data['updated']); diff --git a/tests/api/controllers/links/GetLinksTest.php b/tests/api/controllers/links/GetLinksTest.php index 64f02774..1008d7b2 100644 --- a/tests/api/controllers/links/GetLinksTest.php +++ b/tests/api/controllers/links/GetLinksTest.php @@ -60,7 +60,7 @@ class GetLinksTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['history'] = null; $this->controller = new Links($this->container); @@ -114,7 +114,7 @@ class GetLinksTest extends \PHPUnit_Framework_TestCase $this->assertEquals('sTuff', $first['tags'][0]); $this->assertEquals(false, $first['private']); $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20150310_114651')->format(\DateTime::ATOM), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20150310_114651')->format(\DateTime::ATOM), $first['created'] ); $this->assertEmpty($first['updated']); @@ -125,7 +125,7 @@ class GetLinksTest extends \PHPUnit_Framework_TestCase // Update date $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20160803_093033')->format(\DateTime::ATOM), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20160803_093033')->format(\DateTime::ATOM), $link['updated'] ); } diff --git a/tests/api/controllers/links/PostLinkTest.php b/tests/api/controllers/links/PostLinkTest.php index a73f443c..ade07eeb 100644 --- a/tests/api/controllers/links/PostLinkTest.php +++ b/tests/api/controllers/links/PostLinkTest.php @@ -74,7 +74,7 @@ class PostLinkTest extends TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['history'] = new \Shaarli\History(self::$testHistory); $this->controller = new Links($this->container); @@ -210,11 +210,11 @@ class PostLinkTest extends TestCase $this->assertEquals(['gnu', 'media', 'web', '.hidden', 'hashtag'], $data['tags']); $this->assertEquals(false, $data['private']); $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130614_184135'), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20130614_184135'), \DateTime::createFromFormat(\DateTime::ATOM, $data['created']) ); $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130615_184230'), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20130615_184230'), \DateTime::createFromFormat(\DateTime::ATOM, $data['updated']) ); } diff --git a/tests/api/controllers/links/PutLinkTest.php b/tests/api/controllers/links/PutLinkTest.php index 3bb4d43f..eb6c7955 100644 --- a/tests/api/controllers/links/PutLinkTest.php +++ b/tests/api/controllers/links/PutLinkTest.php @@ -66,7 +66,7 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['history'] = new \Shaarli\History(self::$testHistory); $this->controller = new Links($this->container); @@ -198,11 +198,11 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase $this->assertEquals(['gnu', 'media', 'web', '.hidden', 'hashtag'], $data['tags']); $this->assertEquals(false, $data['private']); $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130614_184135'), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20130614_184135'), \DateTime::createFromFormat(\DateTime::ATOM, $data['created']) ); $this->assertEquals( - \DateTime::createFromFormat(\LinkDB::LINK_DATE_FORMAT, '20130615_184230'), + \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20130615_184230'), \DateTime::createFromFormat(\DateTime::ATOM, $data['updated']) ); } diff --git a/tests/api/controllers/tags/DeleteTagTest.php b/tests/api/controllers/tags/DeleteTagTest.php index a1e419cd..02803ba2 100644 --- a/tests/api/controllers/tags/DeleteTagTest.php +++ b/tests/api/controllers/tags/DeleteTagTest.php @@ -32,7 +32,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \LinkDB instance. + * @var \Shaarli\Bookmark\LinkDB instance. */ protected $linkDB; @@ -59,7 +59,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->conf = new ConfigManager('tests/utils/config/configJson'); $this->refDB = new \ReferenceLinkDB(); $this->refDB->write(self::$testDatastore); - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); $this->history = new \Shaarli\History(self::$testHistory); @@ -97,7 +97,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->assertEquals(204, $response->getStatusCode()); $this->assertEmpty((string) $response->getBody()); - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $tags = $this->linkDB->linksCountPerTag(); $this->assertFalse(isset($tags[$tagName])); @@ -131,7 +131,7 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->assertEquals(204, $response->getStatusCode()); $this->assertEmpty((string) $response->getBody()); - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $tags = $this->linkDB->linksCountPerTag(); $this->assertFalse(isset($tags[$tagName])); $this->assertTrue($tags[strtolower($tagName)] > 0); diff --git a/tests/api/controllers/tags/GetTagNameTest.php b/tests/api/controllers/tags/GetTagNameTest.php index afac228e..8e0feccd 100644 --- a/tests/api/controllers/tags/GetTagNameTest.php +++ b/tests/api/controllers/tags/GetTagNameTest.php @@ -59,7 +59,7 @@ class GetTagNameTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['history'] = null; $this->controller = new Tags($this->container); diff --git a/tests/api/controllers/tags/GetTagsTest.php b/tests/api/controllers/tags/GetTagsTest.php index 3fab31b0..f071bfa8 100644 --- a/tests/api/controllers/tags/GetTagsTest.php +++ b/tests/api/controllers/tags/GetTagsTest.php @@ -38,7 +38,7 @@ class GetTagsTest extends \PHPUnit_Framework_TestCase protected $container; /** - * @var \LinkDB instance. + * @var \Shaarli\Bookmark\LinkDB instance. */ protected $linkDB; @@ -63,7 +63,7 @@ class GetTagsTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['db'] = $this->linkDB; $this->container['history'] = null; diff --git a/tests/api/controllers/tags/PutTagTest.php b/tests/api/controllers/tags/PutTagTest.php index c45fa722..d8c0fec8 100644 --- a/tests/api/controllers/tags/PutTagTest.php +++ b/tests/api/controllers/tags/PutTagTest.php @@ -43,7 +43,7 @@ class PutTagTest extends \PHPUnit_Framework_TestCase protected $container; /** - * @var \LinkDB instance. + * @var \Shaarli\Bookmark\LinkDB instance. */ protected $linkDB; @@ -72,7 +72,7 @@ class PutTagTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->linkDB = new \LinkDB(self::$testDatastore, true, false); + $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); $this->container['db'] = $this->linkDB; $this->container['history'] = $this->history; diff --git a/tests/bookmark/LinkDBTest.php b/tests/bookmark/LinkDBTest.php new file mode 100644 index 00000000..f18a3155 --- /dev/null +++ b/tests/bookmark/LinkDBTest.php @@ -0,0 +1,653 @@ +write(self::$testDatastore); + + self::$publicLinkDB = new LinkDB(self::$testDatastore, false, false); + self::$privateLinkDB = new LinkDB(self::$testDatastore, true, false); + } + + /** + * Resets test data for each test + */ + protected function setUp() + { + if (file_exists(self::$testDatastore)) { + unlink(self::$testDatastore); + } + } + + /** + * Allows to test LinkDB's private methods + * + * @see + * https://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html + * http://stackoverflow.com/a/2798203 + */ + protected static function getMethod($name) + { + $class = new ReflectionClass('Shaarli\Bookmark\LinkDB'); + $method = $class->getMethod($name); + $method->setAccessible(true); + return $method; + } + + /** + * Instantiate LinkDB objects - logged in user + */ + public function testConstructLoggedIn() + { + new LinkDB(self::$testDatastore, true, false); + $this->assertFileExists(self::$testDatastore); + } + + /** + * Instantiate LinkDB objects - logged out or public instance + */ + public function testConstructLoggedOut() + { + new LinkDB(self::$testDatastore, false, false); + $this->assertFileExists(self::$testDatastore); + } + + /** + * Attempt to instantiate a LinkDB whereas the datastore is not writable + * + * @expectedException Shaarli\Exceptions\IOException + * @expectedExceptionMessageRegExp /Error accessing "null"/ + */ + public function testConstructDatastoreNotWriteable() + { + new LinkDB('null/store.db', false, false); + } + + /** + * The DB doesn't exist, ensure it is created with dummy content + */ + public function testCheckDBNew() + { + $linkDB = new LinkDB(self::$testDatastore, false, false); + unlink(self::$testDatastore); + $this->assertFileNotExists(self::$testDatastore); + + $checkDB = self::getMethod('check'); + $checkDB->invokeArgs($linkDB, array()); + $this->assertFileExists(self::$testDatastore); + + // ensure the correct data has been written + $this->assertGreaterThan(0, filesize(self::$testDatastore)); + } + + /** + * The DB exists, don't do anything + */ + public function testCheckDBLoad() + { + $linkDB = new LinkDB(self::$testDatastore, false, false); + $datastoreSize = filesize(self::$testDatastore); + $this->assertGreaterThan(0, $datastoreSize); + + $checkDB = self::getMethod('check'); + $checkDB->invokeArgs($linkDB, array()); + + // ensure the datastore is left unmodified + $this->assertEquals( + $datastoreSize, + filesize(self::$testDatastore) + ); + } + + /** + * Load an empty DB + */ + public function testReadEmptyDB() + { + file_put_contents(self::$testDatastore, ''); + $emptyDB = new LinkDB(self::$testDatastore, false, false); + $this->assertEquals(0, sizeof($emptyDB)); + $this->assertEquals(0, count($emptyDB)); + } + + /** + * Load public links from the DB + */ + public function testReadPublicDB() + { + $this->assertEquals( + self::$refDB->countPublicLinks(), + sizeof(self::$publicLinkDB) + ); + } + + /** + * Load public and private links from the DB + */ + public function testReadPrivateDB() + { + $this->assertEquals( + self::$refDB->countLinks(), + sizeof(self::$privateLinkDB) + ); + } + + /** + * Save the links to the DB + */ + public function testSave() + { + $testDB = new LinkDB(self::$testDatastore, true, false); + $dbSize = sizeof($testDB); + + $link = array( + 'id' => 42, + 'title' => 'an additional link', + 'url' => 'http://dum.my', + 'description' => 'One more', + 'private' => 0, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150518_190000'), + 'tags' => 'unit test' + ); + $testDB[$link['id']] = $link; + $testDB->save('tests'); + + $testDB = new LinkDB(self::$testDatastore, true, false); + $this->assertEquals($dbSize + 1, sizeof($testDB)); + } + + /** + * Count existing links + */ + public function testCount() + { + $this->assertEquals( + self::$refDB->countPublicLinks(), + self::$publicLinkDB->count() + ); + $this->assertEquals( + self::$refDB->countLinks(), + self::$privateLinkDB->count() + ); + } + + /** + * Count existing links - public links hidden + */ + public function testCountHiddenPublic() + { + $linkDB = new LinkDB(self::$testDatastore, false, true); + + $this->assertEquals( + 0, + $linkDB->count() + ); + $this->assertEquals( + 0, + $linkDB->count() + ); + } + + /** + * List the days for which links have been posted + */ + public function testDays() + { + $this->assertEquals( + array('20100309', '20100310', '20121206', '20121207', '20130614', '20150310'), + self::$publicLinkDB->days() + ); + + $this->assertEquals( + array('20100309', '20100310', '20121206', '20121207', '20130614', '20141125', '20150310'), + self::$privateLinkDB->days() + ); + } + + /** + * The URL corresponds to an existing entry in the DB + */ + public function testGetKnownLinkFromURL() + { + $link = self::$publicLinkDB->getLinkFromUrl('http://mediagoblin.org/'); + + $this->assertNotEquals(false, $link); + $this->assertContains( + 'A free software media publishing platform', + $link['description'] + ); + } + + /** + * The URL is not in the DB + */ + public function testGetUnknownLinkFromURL() + { + $this->assertEquals( + false, + self::$publicLinkDB->getLinkFromUrl('http://dev.null') + ); + } + + /** + * Lists all tags + */ + public function testAllTags() + { + $this->assertEquals( + array( + 'web' => 3, + 'cartoon' => 2, + 'gnu' => 2, + 'dev' => 1, + 'samba' => 1, + 'media' => 1, + 'software' => 1, + 'stallman' => 1, + 'free' => 1, + '-exclude' => 1, + 'hashtag' => 2, + // The DB contains a link with `sTuff` and another one with `stuff` tag. + // They need to be grouped with the first case found - order by date DESC: `sTuff`. + 'sTuff' => 2, + 'ut' => 1, + ), + self::$publicLinkDB->linksCountPerTag() + ); + + $this->assertEquals( + array( + 'web' => 4, + 'cartoon' => 3, + 'gnu' => 2, + 'dev' => 2, + 'samba' => 1, + 'media' => 1, + 'software' => 1, + 'stallman' => 1, + 'free' => 1, + 'html' => 1, + 'w3c' => 1, + 'css' => 1, + 'Mercurial' => 1, + 'sTuff' => 2, + '-exclude' => 1, + '.hidden' => 1, + 'hashtag' => 2, + 'tag1' => 1, + 'tag2' => 1, + 'tag3' => 1, + 'tag4' => 1, + 'ut' => 1, + ), + self::$privateLinkDB->linksCountPerTag() + ); + $this->assertEquals( + array( + 'web' => 4, + 'cartoon' => 2, + 'gnu' => 1, + 'dev' => 1, + 'samba' => 1, + 'media' => 1, + 'html' => 1, + 'w3c' => 1, + 'css' => 1, + 'Mercurial' => 1, + '.hidden' => 1, + 'hashtag' => 1, + ), + self::$privateLinkDB->linksCountPerTag(['web']) + ); + $this->assertEquals( + array( + 'web' => 1, + 'html' => 1, + 'w3c' => 1, + 'css' => 1, + 'Mercurial' => 1, + ), + self::$privateLinkDB->linksCountPerTag(['web'], 'private') + ); + } + + /** + * Test real_url without redirector. + */ + public function testLinkRealUrlWithoutRedirector() + { + $db = new LinkDB(self::$testDatastore, false, false); + foreach ($db as $link) { + $this->assertEquals($link['url'], $link['real_url']); + } + } + + /** + * Test real_url with redirector. + */ + public function testLinkRealUrlWithRedirector() + { + $redirector = 'http://redirector.to?'; + $db = new LinkDB(self::$testDatastore, false, false, $redirector); + foreach ($db as $link) { + $this->assertStringStartsWith($redirector, $link['real_url']); + $this->assertNotFalse(strpos($link['real_url'], urlencode('://'))); + } + + $db = new LinkDB(self::$testDatastore, false, false, $redirector, false); + foreach ($db as $link) { + $this->assertStringStartsWith($redirector, $link['real_url']); + $this->assertFalse(strpos($link['real_url'], urlencode('://'))); + } + } + + /** + * Test filter with string. + */ + public function testFilterString() + { + $tags = 'dev cartoon'; + $request = array('searchtags' => $tags); + $this->assertEquals( + 2, + count(self::$privateLinkDB->filterSearch($request, true, false)) + ); + } + + /** + * Test filter with string. + */ + public function testFilterArray() + { + $tags = array('dev', 'cartoon'); + $request = array('searchtags' => $tags); + $this->assertEquals( + 2, + count(self::$privateLinkDB->filterSearch($request, true, false)) + ); + } + + /** + * Test hidden tags feature: + * tags starting with a dot '.' are only visible when logged in. + */ + public function testHiddenTags() + { + $tags = '.hidden'; + $request = array('searchtags' => $tags); + $this->assertEquals( + 1, + count(self::$privateLinkDB->filterSearch($request, true, false)) + ); + + $this->assertEquals( + 0, + count(self::$publicLinkDB->filterSearch($request, true, false)) + ); + } + + /** + * Test filterHash() with a valid smallhash. + */ + public function testFilterHashValid() + { + $request = smallHash('20150310_114651'); + $this->assertEquals( + 1, + count(self::$publicLinkDB->filterHash($request)) + ); + $request = smallHash('20150310_114633' . 8); + $this->assertEquals( + 1, + count(self::$publicLinkDB->filterHash($request)) + ); + } + + /** + * Test filterHash() with an invalid smallhash. + * + * @expectedException LinkNotFoundException + */ + public function testFilterHashInValid1() + { + $request = 'blabla'; + self::$publicLinkDB->filterHash($request); + } + + /** + * Test filterHash() with an empty smallhash. + * + * @expectedException LinkNotFoundException + */ + public function testFilterHashInValid() + { + self::$publicLinkDB->filterHash(''); + } + + /** + * Test reorder with asc/desc parameter. + */ + public function testReorderLinksDesc() + { + self::$privateLinkDB->reorder('ASC'); + $stickyIds = [11, 10]; + $standardIds = [42, 4, 9, 1, 0, 7, 6, 8, 41]; + $linkIds = array_merge($stickyIds, $standardIds); + $cpt = 0; + foreach (self::$privateLinkDB as $key => $value) { + $this->assertEquals($linkIds[$cpt++], $key); + } + self::$privateLinkDB->reorder('DESC'); + $linkIds = array_merge(array_reverse($stickyIds), array_reverse($standardIds)); + $cpt = 0; + foreach (self::$privateLinkDB as $key => $value) { + $this->assertEquals($linkIds[$cpt++], $key); + } + } + + /** + * Test rename tag with a valid value present in multiple links + */ + public function testRenameTagMultiple() + { + self::$refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $res = $linkDB->renameTag('cartoon', 'Taz'); + $this->assertEquals(3, count($res)); + $this->assertContains(' Taz ', $linkDB[4]['tags']); + $this->assertContains(' Taz ', $linkDB[1]['tags']); + $this->assertContains(' Taz ', $linkDB[0]['tags']); + } + + /** + * Test rename tag with a valid value + */ + public function testRenameTagCaseSensitive() + { + self::$refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false, ''); + + $res = $linkDB->renameTag('sTuff', 'Taz'); + $this->assertEquals(1, count($res)); + $this->assertEquals('Taz', $linkDB[41]['tags']); + } + + /** + * Test rename tag with invalid values + */ + public function testRenameTagInvalid() + { + $linkDB = new LinkDB(self::$testDatastore, false, false); + + $this->assertFalse($linkDB->renameTag('', 'test')); + $this->assertFalse($linkDB->renameTag('', '')); + // tag non existent + $this->assertEquals([], $linkDB->renameTag('test', '')); + $this->assertEquals([], $linkDB->renameTag('test', 'retest')); + } + + /** + * Test delete tag with a valid value + */ + public function testDeleteTag() + { + self::$refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $res = $linkDB->renameTag('cartoon', null); + $this->assertEquals(3, count($res)); + $this->assertNotContains('cartoon', $linkDB[4]['tags']); + } + + /** + * Test linksCountPerTag all tags without filter. + * Equal occurrences should be sorted alphabetically. + */ + public function testCountLinkPerTagAllNoFilter() + { + $expected = [ + 'web' => 4, + 'cartoon' => 3, + 'dev' => 2, + 'gnu' => 2, + 'hashtag' => 2, + 'sTuff' => 2, + '-exclude' => 1, + '.hidden' => 1, + 'Mercurial' => 1, + 'css' => 1, + 'free' => 1, + 'html' => 1, + 'media' => 1, + 'samba' => 1, + 'software' => 1, + 'stallman' => 1, + 'tag1' => 1, + 'tag2' => 1, + 'tag3' => 1, + 'tag4' => 1, + 'ut' => 1, + 'w3c' => 1, + ]; + $tags = self::$privateLinkDB->linksCountPerTag(); + + $this->assertEquals($expected, $tags, var_export($tags, true)); + } + + /** + * Test linksCountPerTag all tags with filter. + * Equal occurrences should be sorted alphabetically. + */ + public function testCountLinkPerTagAllWithFilter() + { + $expected = [ + 'gnu' => 2, + 'hashtag' => 2, + '-exclude' => 1, + '.hidden' => 1, + 'free' => 1, + 'media' => 1, + 'software' => 1, + 'stallman' => 1, + 'stuff' => 1, + 'web' => 1, + ]; + $tags = self::$privateLinkDB->linksCountPerTag(['gnu']); + + $this->assertEquals($expected, $tags, var_export($tags, true)); + } + + /** + * Test linksCountPerTag public tags with filter. + * Equal occurrences should be sorted alphabetically. + */ + public function testCountLinkPerTagPublicWithFilter() + { + $expected = [ + 'gnu' => 2, + 'hashtag' => 2, + '-exclude' => 1, + '.hidden' => 1, + 'free' => 1, + 'media' => 1, + 'software' => 1, + 'stallman' => 1, + 'stuff' => 1, + 'web' => 1, + ]; + $tags = self::$privateLinkDB->linksCountPerTag(['gnu'], 'public'); + + $this->assertEquals($expected, $tags, var_export($tags, true)); + } + + /** + * Test linksCountPerTag public tags with filter. + * Equal occurrences should be sorted alphabetically. + */ + public function testCountLinkPerTagPrivateWithFilter() + { + $expected = [ + 'cartoon' => 1, + 'dev' => 1, + 'tag1' => 1, + 'tag2' => 1, + 'tag3' => 1, + 'tag4' => 1, + ]; + $tags = self::$privateLinkDB->linksCountPerTag(['dev'], 'private'); + + $this->assertEquals($expected, $tags, var_export($tags, true)); + } +} diff --git a/tests/feed/FeedBuilderTest.php b/tests/feed/FeedBuilderTest.php index 1fdbc60e..88d1c3ed 100644 --- a/tests/feed/FeedBuilderTest.php +++ b/tests/feed/FeedBuilderTest.php @@ -3,11 +3,9 @@ namespace Shaarli\Feed; use DateTime; -use LinkDB; +use Shaarli\Bookmark\LinkDB; use ReferenceLinkDB; -require_once 'application/LinkDB.php'; - /** * FeedBuilderTest class. * diff --git a/tests/http/UrlTest.php b/tests/http/UrlTest.php index 342b78a4..ae92f73a 100644 --- a/tests/http/UrlTest.php +++ b/tests/http/UrlTest.php @@ -5,7 +5,6 @@ namespace Shaarli\Http; - /** * Unitary tests for URL utilities */ diff --git a/tests/plugins/PluginIssoTest.php b/tests/plugins/PluginIssoTest.php index 2c9efbcd..f5fa1daa 100644 --- a/tests/plugins/PluginIssoTest.php +++ b/tests/plugins/PluginIssoTest.php @@ -1,4 +1,6 @@ Date: Mon, 3 Dec 2018 01:22:45 +0100 Subject: namespacing: \Shaarli\Bookmark\LinkFilter Signed-off-by: VirtualTam --- tests/LinkFilterTest.php | 502 ------------------------------------- tests/bookmark/LinkDBTest.php | 6 +- tests/bookmark/LinkFilterTest.php | 507 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 510 insertions(+), 505 deletions(-) delete mode 100644 tests/LinkFilterTest.php create mode 100644 tests/bookmark/LinkFilterTest.php (limited to 'tests') diff --git a/tests/LinkFilterTest.php b/tests/LinkFilterTest.php deleted file mode 100644 index db28b1c4..00000000 --- a/tests/LinkFilterTest.php +++ /dev/null @@ -1,502 +0,0 @@ -write(self::$testDatastore); - self::$linkDB = new LinkDB(self::$testDatastore, true, false); - self::$linkFilter = new LinkFilter(self::$linkDB); - } - - /** - * Blank filter. - */ - public function testFilter() - { - $this->assertEquals( - self::$refDB->countLinks(), - count(self::$linkFilter->filter('', '')) - ); - - $this->assertEquals( - self::$refDB->countLinks(), - count(self::$linkFilter->filter('', '', 'all')) - ); - - $this->assertEquals( - self::$refDB->countLinks(), - count(self::$linkFilter->filter('', '', 'randomstr')) - ); - - // Private only. - $this->assertEquals( - self::$refDB->countPrivateLinks(), - count(self::$linkFilter->filter('', '', false, 'private')) - ); - - // Public only. - $this->assertEquals( - self::$refDB->countPublicLinks(), - count(self::$linkFilter->filter('', '', false, 'public')) - ); - - $this->assertEquals( - ReferenceLinkDB::$NB_LINKS_TOTAL, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, '')) - ); - - $this->assertEquals( - self::$refDB->countUntaggedLinks(), - count( - self::$linkFilter->filter( - LinkFilter::$FILTER_TAG, - /*$request=*/'', - /*$casesensitive=*/false, - /*$visibility=*/'all', - /*$untaggedonly=*/true - ) - ) - ); - - $this->assertEquals( - ReferenceLinkDB::$NB_LINKS_TOTAL, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, '')) - ); - } - - /** - * Filter links using a tag - */ - public function testFilterOneTag() - { - $this->assertEquals( - 4, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false)) - ); - - $this->assertEquals( - 4, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'all')) - ); - - $this->assertEquals( - 4, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'default-blabla')) - ); - - // Private only. - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'private')) - ); - - // Public only. - $this->assertEquals( - 3, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'public')) - ); - } - - /** - * Filter links using a tag - case-sensitive - */ - public function testFilterCaseSensitiveTag() - { - $this->assertEquals( - 0, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'mercurial', true)) - ); - - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'Mercurial', true)) - ); - } - - /** - * Filter links using a tag combination - */ - public function testFilterMultipleTags() - { - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'dev cartoon', false)) - ); - } - - /** - * Filter links using a non-existent tag - */ - public function testFilterUnknownTag() - { - $this->assertEquals( - 0, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'null', false)) - ); - } - - /** - * Return links for a given day - */ - public function testFilterDay() - { - $this->assertEquals( - 4, - count(self::$linkFilter->filter(LinkFilter::$FILTER_DAY, '20121206')) - ); - } - - /** - * 404 - day not found - */ - public function testFilterUnknownDay() - { - $this->assertEquals( - 0, - count(self::$linkFilter->filter(LinkFilter::$FILTER_DAY, '19700101')) - ); - } - - /** - * Use an invalid date format - * @expectedException Exception - * @expectedExceptionMessageRegExp /Invalid date format/ - */ - public function testFilterInvalidDayWithChars() - { - self::$linkFilter->filter(LinkFilter::$FILTER_DAY, 'Rainy day, dream away'); - } - - /** - * Use an invalid date format - * @expectedException Exception - * @expectedExceptionMessageRegExp /Invalid date format/ - */ - public function testFilterInvalidDayDigits() - { - self::$linkFilter->filter(LinkFilter::$FILTER_DAY, '20'); - } - - /** - * Retrieve a link entry with its hash - */ - public function testFilterSmallHash() - { - $links = self::$linkFilter->filter(LinkFilter::$FILTER_HASH, 'IuWvgA'); - - $this->assertEquals( - 1, - count($links) - ); - - $this->assertEquals( - 'MediaGoblin', - $links[7]['title'] - ); - } - - /** - * No link for this hash - * - * @expectedException LinkNotFoundException - */ - public function testFilterUnknownSmallHash() - { - self::$linkFilter->filter(LinkFilter::$FILTER_HASH, 'Iblaah'); - } - - /** - * Full-text search - no result found. - */ - public function testFilterFullTextNoResult() - { - $this->assertEquals( - 0, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'azertyuiop')) - ); - } - - /** - * Full-text search - result from a link's URL - */ - public function testFilterFullTextURL() - { - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'ars.userfriendly.org')) - ); - - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'ars org')) - ); - } - - /** - * Full-text search - result from a link's title only - */ - public function testFilterFullTextTitle() - { - // use miscellaneous cases - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'userfriendly -')) - ); - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'UserFriendly -')) - ); - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'uSeRFrIendlY -')) - ); - - // use miscellaneous case and offset - $this->assertEquals( - 2, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'RFrIendL')) - ); - } - - /** - * Full-text search - result from the link's description only - */ - public function testFilterFullTextDescription() - { - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'publishing media')) - ); - - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'mercurial w3c')) - ); - - $this->assertEquals( - 3, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, '"free software"')) - ); - } - - /** - * Full-text search - result from the link's tags only - */ - public function testFilterFullTextTags() - { - $this->assertEquals( - 6, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web')) - ); - - $this->assertEquals( - 6, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', 'all')) - ); - - $this->assertEquals( - 6, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', 'bla')) - ); - - // Private only. - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', false, 'private')) - ); - - // Public only. - $this->assertEquals( - 5, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', false, 'public')) - ); - } - - /** - * Full-text search - result set from mixed sources - */ - public function testFilterFullTextMixed() - { - $this->assertEquals( - 3, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'free software')) - ); - } - - /** - * Full-text search - test exclusion with '-'. - */ - public function testExcludeSearch() - { - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'free -gnu')) - ); - - $this->assertEquals( - ReferenceLinkDB::$NB_LINKS_TOTAL - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, '-revolution')) - ); - } - - /** - * Full-text search - test AND, exact terms and exclusion combined, across fields. - */ - public function testMultiSearch() - { - $this->assertEquals( - 2, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TEXT, - '"Free Software " stallman "read this" @website stuff' - )) - ); - - $this->assertEquals( - 1, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TEXT, - '"free software " stallman "read this" -beard @website stuff' - )) - ); - } - - /** - * Full-text search - make sure that exact search won't work across fields. - */ - public function testSearchExactTermMultiFieldsKo() - { - $this->assertEquals( - 0, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TEXT, - '"designer naming"' - )) - ); - - $this->assertEquals( - 0, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TEXT, - '"designernaming"' - )) - ); - } - - /** - * Tag search with exclusion. - */ - public function testTagFilterWithExclusion() - { - $this->assertEquals( - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'gnu -free')) - ); - - $this->assertEquals( - ReferenceLinkDB::$NB_LINKS_TOTAL - 1, - count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, '-free')) - ); - } - - /** - * Test crossed search (terms + tags). - */ - public function testFilterCrossedSearch() - { - $terms = '"Free Software " stallman "read this" @website stuff'; - $tags = 'free'; - $this->assertEquals( - 1, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, - array($tags, $terms) - )) - ); - $this->assertEquals( - 2, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, - array('', $terms) - )) - ); - $this->assertEquals( - 1, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, - array(false, 'PSR-2') - )) - ); - $this->assertEquals( - 1, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, - array($tags, '') - )) - ); - $this->assertEquals( - ReferenceLinkDB::$NB_LINKS_TOTAL, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, - '' - )) - ); - } - - /** - * Filter links by #hashtag. - */ - public function testFilterByHashtag() - { - $hashtag = 'hashtag'; - $this->assertEquals( - 3, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG, - $hashtag - )) - ); - - $hashtag = 'private'; - $this->assertEquals( - 1, - count(self::$linkFilter->filter( - LinkFilter::$FILTER_TAG, - $hashtag, - false, - 'private' - )) - ); - } -} diff --git a/tests/bookmark/LinkDBTest.php b/tests/bookmark/LinkDBTest.php index f18a3155..65409e95 100644 --- a/tests/bookmark/LinkDBTest.php +++ b/tests/bookmark/LinkDBTest.php @@ -6,7 +6,7 @@ namespace Shaarli\Bookmark; use DateTime; -use LinkNotFoundException; +use Shaarli\Bookmark\Exception\LinkNotFoundException; use ReferenceLinkDB; use ReflectionClass; use Shaarli; @@ -457,7 +457,7 @@ class LinkDBTest extends \PHPUnit\Framework\TestCase /** * Test filterHash() with an invalid smallhash. * - * @expectedException LinkNotFoundException + * @expectedException \Shaarli\Bookmark\Exception\LinkNotFoundException */ public function testFilterHashInValid1() { @@ -468,7 +468,7 @@ class LinkDBTest extends \PHPUnit\Framework\TestCase /** * Test filterHash() with an empty smallhash. * - * @expectedException LinkNotFoundException + * @expectedException \Shaarli\Bookmark\Exception\LinkNotFoundException */ public function testFilterHashInValid() { diff --git a/tests/bookmark/LinkFilterTest.php b/tests/bookmark/LinkFilterTest.php new file mode 100644 index 00000000..808f8122 --- /dev/null +++ b/tests/bookmark/LinkFilterTest.php @@ -0,0 +1,507 @@ +write(self::$testDatastore); + self::$linkDB = new LinkDB(self::$testDatastore, true, false); + self::$linkFilter = new LinkFilter(self::$linkDB); + } + + /** + * Blank filter. + */ + public function testFilter() + { + $this->assertEquals( + self::$refDB->countLinks(), + count(self::$linkFilter->filter('', '')) + ); + + $this->assertEquals( + self::$refDB->countLinks(), + count(self::$linkFilter->filter('', '', 'all')) + ); + + $this->assertEquals( + self::$refDB->countLinks(), + count(self::$linkFilter->filter('', '', 'randomstr')) + ); + + // Private only. + $this->assertEquals( + self::$refDB->countPrivateLinks(), + count(self::$linkFilter->filter('', '', false, 'private')) + ); + + // Public only. + $this->assertEquals( + self::$refDB->countPublicLinks(), + count(self::$linkFilter->filter('', '', false, 'public')) + ); + + $this->assertEquals( + ReferenceLinkDB::$NB_LINKS_TOTAL, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, '')) + ); + + $this->assertEquals( + self::$refDB->countUntaggedLinks(), + count( + self::$linkFilter->filter( + LinkFilter::$FILTER_TAG, + /*$request=*/ + '', + /*$casesensitive=*/ + false, + /*$visibility=*/ + 'all', + /*$untaggedonly=*/ + true + ) + ) + ); + + $this->assertEquals( + ReferenceLinkDB::$NB_LINKS_TOTAL, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, '')) + ); + } + + /** + * Filter links using a tag + */ + public function testFilterOneTag() + { + $this->assertEquals( + 4, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false)) + ); + + $this->assertEquals( + 4, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'all')) + ); + + $this->assertEquals( + 4, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'default-blabla')) + ); + + // Private only. + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'private')) + ); + + // Public only. + $this->assertEquals( + 3, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'web', false, 'public')) + ); + } + + /** + * Filter links using a tag - case-sensitive + */ + public function testFilterCaseSensitiveTag() + { + $this->assertEquals( + 0, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'mercurial', true)) + ); + + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'Mercurial', true)) + ); + } + + /** + * Filter links using a tag combination + */ + public function testFilterMultipleTags() + { + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'dev cartoon', false)) + ); + } + + /** + * Filter links using a non-existent tag + */ + public function testFilterUnknownTag() + { + $this->assertEquals( + 0, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'null', false)) + ); + } + + /** + * Return links for a given day + */ + public function testFilterDay() + { + $this->assertEquals( + 4, + count(self::$linkFilter->filter(LinkFilter::$FILTER_DAY, '20121206')) + ); + } + + /** + * 404 - day not found + */ + public function testFilterUnknownDay() + { + $this->assertEquals( + 0, + count(self::$linkFilter->filter(LinkFilter::$FILTER_DAY, '19700101')) + ); + } + + /** + * Use an invalid date format + * @expectedException Exception + * @expectedExceptionMessageRegExp /Invalid date format/ + */ + public function testFilterInvalidDayWithChars() + { + self::$linkFilter->filter(LinkFilter::$FILTER_DAY, 'Rainy day, dream away'); + } + + /** + * Use an invalid date format + * @expectedException Exception + * @expectedExceptionMessageRegExp /Invalid date format/ + */ + public function testFilterInvalidDayDigits() + { + self::$linkFilter->filter(LinkFilter::$FILTER_DAY, '20'); + } + + /** + * Retrieve a link entry with its hash + */ + public function testFilterSmallHash() + { + $links = self::$linkFilter->filter(LinkFilter::$FILTER_HASH, 'IuWvgA'); + + $this->assertEquals( + 1, + count($links) + ); + + $this->assertEquals( + 'MediaGoblin', + $links[7]['title'] + ); + } + + /** + * No link for this hash + * + * @expectedException \Shaarli\Bookmark\Exception\LinkNotFoundException + */ + public function testFilterUnknownSmallHash() + { + self::$linkFilter->filter(LinkFilter::$FILTER_HASH, 'Iblaah'); + } + + /** + * Full-text search - no result found. + */ + public function testFilterFullTextNoResult() + { + $this->assertEquals( + 0, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'azertyuiop')) + ); + } + + /** + * Full-text search - result from a link's URL + */ + public function testFilterFullTextURL() + { + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'ars.userfriendly.org')) + ); + + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'ars org')) + ); + } + + /** + * Full-text search - result from a link's title only + */ + public function testFilterFullTextTitle() + { + // use miscellaneous cases + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'userfriendly -')) + ); + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'UserFriendly -')) + ); + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'uSeRFrIendlY -')) + ); + + // use miscellaneous case and offset + $this->assertEquals( + 2, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'RFrIendL')) + ); + } + + /** + * Full-text search - result from the link's description only + */ + public function testFilterFullTextDescription() + { + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'publishing media')) + ); + + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'mercurial w3c')) + ); + + $this->assertEquals( + 3, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, '"free software"')) + ); + } + + /** + * Full-text search - result from the link's tags only + */ + public function testFilterFullTextTags() + { + $this->assertEquals( + 6, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web')) + ); + + $this->assertEquals( + 6, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', 'all')) + ); + + $this->assertEquals( + 6, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', 'bla')) + ); + + // Private only. + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', false, 'private')) + ); + + // Public only. + $this->assertEquals( + 5, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'web', false, 'public')) + ); + } + + /** + * Full-text search - result set from mixed sources + */ + public function testFilterFullTextMixed() + { + $this->assertEquals( + 3, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'free software')) + ); + } + + /** + * Full-text search - test exclusion with '-'. + */ + public function testExcludeSearch() + { + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, 'free -gnu')) + ); + + $this->assertEquals( + ReferenceLinkDB::$NB_LINKS_TOTAL - 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TEXT, '-revolution')) + ); + } + + /** + * Full-text search - test AND, exact terms and exclusion combined, across fields. + */ + public function testMultiSearch() + { + $this->assertEquals( + 2, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TEXT, + '"Free Software " stallman "read this" @website stuff' + )) + ); + + $this->assertEquals( + 1, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TEXT, + '"free software " stallman "read this" -beard @website stuff' + )) + ); + } + + /** + * Full-text search - make sure that exact search won't work across fields. + */ + public function testSearchExactTermMultiFieldsKo() + { + $this->assertEquals( + 0, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TEXT, + '"designer naming"' + )) + ); + + $this->assertEquals( + 0, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TEXT, + '"designernaming"' + )) + ); + } + + /** + * Tag search with exclusion. + */ + public function testTagFilterWithExclusion() + { + $this->assertEquals( + 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, 'gnu -free')) + ); + + $this->assertEquals( + ReferenceLinkDB::$NB_LINKS_TOTAL - 1, + count(self::$linkFilter->filter(LinkFilter::$FILTER_TAG, '-free')) + ); + } + + /** + * Test crossed search (terms + tags). + */ + public function testFilterCrossedSearch() + { + $terms = '"Free Software " stallman "read this" @website stuff'; + $tags = 'free'; + $this->assertEquals( + 1, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, + array($tags, $terms) + )) + ); + $this->assertEquals( + 2, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, + array('', $terms) + )) + ); + $this->assertEquals( + 1, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, + array(false, 'PSR-2') + )) + ); + $this->assertEquals( + 1, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, + array($tags, '') + )) + ); + $this->assertEquals( + ReferenceLinkDB::$NB_LINKS_TOTAL, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT, + '' + )) + ); + } + + /** + * Filter links by #hashtag. + */ + public function testFilterByHashtag() + { + $hashtag = 'hashtag'; + $this->assertEquals( + 3, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG, + $hashtag + )) + ); + + $hashtag = 'private'; + $this->assertEquals( + 1, + count(self::$linkFilter->filter( + LinkFilter::$FILTER_TAG, + $hashtag, + false, + 'private' + )) + ); + } +} -- cgit v1.2.3 From fe3713d2e5c91e2d07af72b39f321521d3dd470c Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 01:35:14 +0100 Subject: namespacing: move LinkUtils along \Shaarli\Bookmark classes Signed-off-by: VirtualTam --- tests/LinkUtilsTest.php | 421 ----------------------------------- tests/bookmark/LinkUtilsTest.php | 333 +++++++++++++++++++++++++++ tests/plugins/PluginMarkdownTest.php | 1 + tests/utils/CurlUtils.php | 94 ++++++++ 4 files changed, 428 insertions(+), 421 deletions(-) delete mode 100644 tests/LinkUtilsTest.php create mode 100644 tests/bookmark/LinkUtilsTest.php create mode 100644 tests/utils/CurlUtils.php (limited to 'tests') diff --git a/tests/LinkUtilsTest.php b/tests/LinkUtilsTest.php deleted file mode 100644 index 5407159a..00000000 --- a/tests/LinkUtilsTest.php +++ /dev/null @@ -1,421 +0,0 @@ -stuff'. $title .''; - $this->assertEquals($title, html_extract_title($html)); - $html = ''. $title .'blablaanother'; - $this->assertEquals($title, html_extract_title($html)); - } - - /** - * Test html_extract_title() when the title is not found. - */ - public function testHtmlExtractNonExistentTitle() - { - $html = 'stuff'; - $this->assertFalse(html_extract_title($html)); - } - - /** - * Test headers_extract_charset() when the charset is found. - */ - public function testHeadersExtractExistentCharset() - { - $charset = 'x-MacCroatian'; - $headers = 'text/html; charset='. $charset; - $this->assertEquals(strtolower($charset), header_extract_charset($headers)); - } - - /** - * Test headers_extract_charset() when the charset is not found. - */ - public function testHeadersExtractNonExistentCharset() - { - $headers = ''; - $this->assertFalse(header_extract_charset($headers)); - - $headers = 'text/html'; - $this->assertFalse(header_extract_charset($headers)); - } - - /** - * Test html_extract_charset() when the charset is found. - */ - public function testHtmlExtractExistentCharset() - { - $charset = 'x-MacCroatian'; - $html = 'stuff2'; - $this->assertEquals(strtolower($charset), html_extract_charset($html)); - } - - /** - * Test html_extract_charset() when the charset is not found. - */ - public function testHtmlExtractNonExistentCharset() - { - $html = 'stuff'; - $this->assertFalse(html_extract_charset($html)); - $html = 'stuff'; - $this->assertFalse(html_extract_charset($html)); - } - - /** - * Test the download callback with valid value - */ - public function testCurlDownloadCallbackOk() - { - $callback = get_curl_download_callback($charset, $title, 'ut_curl_getinfo_ok'); - $data = [ - 'HTTP/1.1 200 OK', - 'Server: GitHub.com', - 'Date: Sat, 28 Oct 2017 12:01:33 GMT', - 'Content-Type: text/html; charset=utf-8', - 'Status: 200 OK', - 'end' => 'th=device-width">' - .'Refactoring · GitHub' - .'' - .'Refactoring · GitHub' - .'', - 'end' => 'th=device-width">' - .'Refactoring · GitHub' - .'Refactoring · GitHub' - .'http://hello.there/is=someone#here otherstuff'; - $processedText = text2clickable($text, ''); - $this->assertEquals($expectedText, $processedText); - - $text = 'stuff http://hello.there/is=someone#here(please) otherstuff'; - $expectedText = 'stuff ' - .'http://hello.there/is=someone#here(please) otherstuff'; - $processedText = text2clickable($text, ''); - $this->assertEquals($expectedText, $processedText); - - $text = 'stuff http://hello.there/is=someone#here(please)&no otherstuff'; - $expectedText = 'stuff ' - .'http://hello.there/is=someone#here(please)&no otherstuff'; - $processedText = text2clickable($text, ''); - $this->assertEquals($expectedText, $processedText); - } - - /** - * Test text2clickable with a redirector set. - */ - public function testText2clickableWithRedirector() - { - $text = 'stuff http://hello.there/is=someone#here otherstuff'; - $redirector = 'http://redirector.to'; - $expectedText = 'stuff http://hello.there/is=someone#here otherstuff'; - $processedText = text2clickable($text, $redirector); - $this->assertEquals($expectedText, $processedText); - } - - /** - * Test text2clickable a redirector set and without URL encode. - */ - public function testText2clickableWithRedirectorDontEncode() - { - $text = 'stuff http://hello.there/?is=someone&or=something#here otherstuff'; - $redirector = 'http://redirector.to'; - $expectedText = 'stuff http://hello.there/?is=someone&or=something#here otherstuff'; - $processedText = text2clickable($text, $redirector, false); - $this->assertEquals($expectedText, $processedText); - } - - /** - * Test testSpace2nbsp. - */ - public function testSpace2nbsp() - { - $text = ' Are you thrilled by flags ?'. PHP_EOL .' Really?'; - $expectedText = '  Are you   thrilled  by flags   ?'. PHP_EOL .' Really?'; - $processedText = space2nbsp($text); - $this->assertEquals($expectedText, $processedText); - } - - /** - * Test hashtags auto-link. - */ - public function testHashtagAutolink() - { - $index = 'http://domain.tld/'; - $rawDescription = '#hashtag\n - # nothashtag\n - test#nothashtag #hashtag \#nothashtag\n - test #hashtag #hashtag test #hashtag.test\n - #hashtag #hashtag-nothashtag #hashtag_hashtag\n - What is #ашок anyway?\n - カタカナ #カタカナ」カタカナ\n'; - $autolinkedDescription = hashtag_autolink($rawDescription, $index); - - $this->assertContains($this->getHashtagLink('hashtag', $index), $autolinkedDescription); - $this->assertNotContains(' #hashtag', $autolinkedDescription); - $this->assertNotContains('>#nothashtag', $autolinkedDescription); - $this->assertContains($this->getHashtagLink('ашок', $index), $autolinkedDescription); - $this->assertContains($this->getHashtagLink('カタカナ', $index), $autolinkedDescription); - $this->assertContains($this->getHashtagLink('hashtag_hashtag', $index), $autolinkedDescription); - $this->assertNotContains($this->getHashtagLink('hashtag-nothashtag', $index), $autolinkedDescription); - } - - /** - * Test hashtags auto-link without index URL. - */ - public function testHashtagAutolinkNoIndex() - { - $rawDescription = 'blabla #hashtag x#nothashtag'; - $autolinkedDescription = hashtag_autolink($rawDescription); - - $this->assertContains($this->getHashtagLink('hashtag'), $autolinkedDescription); - $this->assertNotContains(' #hashtag', $autolinkedDescription); - $this->assertNotContains('>#nothashtag', $autolinkedDescription); - } - - /** - * Util function to build an hashtag link. - * - * @param string $hashtag Hashtag name. - * @param string $index Index URL. - * - * @return string HTML hashtag link. - */ - private function getHashtagLink($hashtag, $index = '') - { - $hashtagLink = '#$1'; - return str_replace('$1', $hashtag, $hashtagLink); - } -} - -// old style mock: PHPUnit doesn't allow function mock - -/** - * Returns code 200 or html content type. - * - * @param resource $ch cURL resource - * @param int $type cURL info type - * - * @return int|string 200 or 'text/html' - */ -function ut_curl_getinfo_ok($ch, $type) -{ - switch ($type) { - case CURLINFO_RESPONSE_CODE: - return 200; - case CURLINFO_CONTENT_TYPE: - return 'text/html; charset=utf-8'; - } -} - -/** - * Returns code 200 or html content type without charset. - * - * @param resource $ch cURL resource - * @param int $type cURL info type - * - * @return int|string 200 or 'text/html' - */ -function ut_curl_getinfo_no_charset($ch, $type) -{ - switch ($type) { - case CURLINFO_RESPONSE_CODE: - return 200; - case CURLINFO_CONTENT_TYPE: - return 'text/html'; - } -} - -/** - * Invalid response code. - * - * @param resource $ch cURL resource - * @param int $type cURL info type - * - * @return int|string 404 or 'text/html' - */ -function ut_curl_getinfo_rc_ko($ch, $type) -{ - switch ($type) { - case CURLINFO_RESPONSE_CODE: - return 404; - case CURLINFO_CONTENT_TYPE: - return 'text/html; charset=utf-8'; - } -} - -/** - * Invalid content type. - * - * @param resource $ch cURL resource - * @param int $type cURL info type - * - * @return int|string 200 or 'text/plain' - */ -function ut_curl_getinfo_ct_ko($ch, $type) -{ - switch ($type) { - case CURLINFO_RESPONSE_CODE: - return 200; - case CURLINFO_CONTENT_TYPE: - return 'text/plain'; - } -} - -/** - * Invalid response code and content type. - * - * @param resource $ch cURL resource - * @param int $type cURL info type - * - * @return int|string 404 or 'text/plain' - */ -function ut_curl_getinfo_rs_ct_ko($ch, $type) -{ - switch ($type) { - case CURLINFO_RESPONSE_CODE: - return 404; - case CURLINFO_CONTENT_TYPE: - return 'text/plain'; - } -} diff --git a/tests/bookmark/LinkUtilsTest.php b/tests/bookmark/LinkUtilsTest.php new file mode 100644 index 00000000..1b8688e6 --- /dev/null +++ b/tests/bookmark/LinkUtilsTest.php @@ -0,0 +1,333 @@ +stuff' . $title . ''; + $this->assertEquals($title, html_extract_title($html)); + $html = '' . $title . 'blablaanother'; + $this->assertEquals($title, html_extract_title($html)); + } + + /** + * Test html_extract_title() when the title is not found. + */ + public function testHtmlExtractNonExistentTitle() + { + $html = 'stuff'; + $this->assertFalse(html_extract_title($html)); + } + + /** + * Test headers_extract_charset() when the charset is found. + */ + public function testHeadersExtractExistentCharset() + { + $charset = 'x-MacCroatian'; + $headers = 'text/html; charset=' . $charset; + $this->assertEquals(strtolower($charset), header_extract_charset($headers)); + } + + /** + * Test headers_extract_charset() when the charset is not found. + */ + public function testHeadersExtractNonExistentCharset() + { + $headers = ''; + $this->assertFalse(header_extract_charset($headers)); + + $headers = 'text/html'; + $this->assertFalse(header_extract_charset($headers)); + } + + /** + * Test html_extract_charset() when the charset is found. + */ + public function testHtmlExtractExistentCharset() + { + $charset = 'x-MacCroatian'; + $html = 'stuff2'; + $this->assertEquals(strtolower($charset), html_extract_charset($html)); + } + + /** + * Test html_extract_charset() when the charset is not found. + */ + public function testHtmlExtractNonExistentCharset() + { + $html = 'stuff'; + $this->assertFalse(html_extract_charset($html)); + $html = 'stuff'; + $this->assertFalse(html_extract_charset($html)); + } + + /** + * Test the download callback with valid value + */ + public function testCurlDownloadCallbackOk() + { + $callback = get_curl_download_callback($charset, $title, 'ut_curl_getinfo_ok'); + $data = [ + 'HTTP/1.1 200 OK', + 'Server: GitHub.com', + 'Date: Sat, 28 Oct 2017 12:01:33 GMT', + 'Content-Type: text/html; charset=utf-8', + 'Status: 200 OK', + 'end' => 'th=device-width">' + . 'Refactoring · GitHub' + . '' + . 'Refactoring · GitHub' + . '', + 'end' => 'th=device-width">' + . 'Refactoring · GitHub' + . 'Refactoring · GitHub' + . 'http://hello.there/is=someone#here otherstuff'; + $processedText = text2clickable($text, ''); + $this->assertEquals($expectedText, $processedText); + + $text = 'stuff http://hello.there/is=someone#here(please) otherstuff'; + $expectedText = 'stuff ' + . 'http://hello.there/is=someone#here(please) otherstuff'; + $processedText = text2clickable($text, ''); + $this->assertEquals($expectedText, $processedText); + + $text = 'stuff http://hello.there/is=someone#here(please)&no otherstuff'; + $expectedText = 'stuff ' + . 'http://hello.there/is=someone#here(please)&no otherstuff'; + $processedText = text2clickable($text, ''); + $this->assertEquals($expectedText, $processedText); + } + + /** + * Test text2clickable with a redirector set. + */ + public function testText2clickableWithRedirector() + { + $text = 'stuff http://hello.there/is=someone#here otherstuff'; + $redirector = 'http://redirector.to'; + $expectedText = 'stuff http://hello.there/is=someone#here otherstuff'; + $processedText = text2clickable($text, $redirector); + $this->assertEquals($expectedText, $processedText); + } + + /** + * Test text2clickable a redirector set and without URL encode. + */ + public function testText2clickableWithRedirectorDontEncode() + { + $text = 'stuff http://hello.there/?is=someone&or=something#here otherstuff'; + $redirector = 'http://redirector.to'; + $expectedText = 'stuff http://hello.there/?is=someone&or=something#here otherstuff'; + $processedText = text2clickable($text, $redirector, false); + $this->assertEquals($expectedText, $processedText); + } + + /** + * Test testSpace2nbsp. + */ + public function testSpace2nbsp() + { + $text = ' Are you thrilled by flags ?' . PHP_EOL . ' Really?'; + $expectedText = '  Are you   thrilled  by flags   ?' . PHP_EOL . ' Really?'; + $processedText = space2nbsp($text); + $this->assertEquals($expectedText, $processedText); + } + + /** + * Test hashtags auto-link. + */ + public function testHashtagAutolink() + { + $index = 'http://domain.tld/'; + $rawDescription = '#hashtag\n + # nothashtag\n + test#nothashtag #hashtag \#nothashtag\n + test #hashtag #hashtag test #hashtag.test\n + #hashtag #hashtag-nothashtag #hashtag_hashtag\n + What is #ашок anyway?\n + カタカナ #カタカナ」カタカナ\n'; + $autolinkedDescription = hashtag_autolink($rawDescription, $index); + + $this->assertContains($this->getHashtagLink('hashtag', $index), $autolinkedDescription); + $this->assertNotContains(' #hashtag', $autolinkedDescription); + $this->assertNotContains('>#nothashtag', $autolinkedDescription); + $this->assertContains($this->getHashtagLink('ашок', $index), $autolinkedDescription); + $this->assertContains($this->getHashtagLink('カタカナ', $index), $autolinkedDescription); + $this->assertContains($this->getHashtagLink('hashtag_hashtag', $index), $autolinkedDescription); + $this->assertNotContains($this->getHashtagLink('hashtag-nothashtag', $index), $autolinkedDescription); + } + + /** + * Test hashtags auto-link without index URL. + */ + public function testHashtagAutolinkNoIndex() + { + $rawDescription = 'blabla #hashtag x#nothashtag'; + $autolinkedDescription = hashtag_autolink($rawDescription); + + $this->assertContains($this->getHashtagLink('hashtag'), $autolinkedDescription); + $this->assertNotContains(' #hashtag', $autolinkedDescription); + $this->assertNotContains('>#nothashtag', $autolinkedDescription); + } + + /** + * Util function to build an hashtag link. + * + * @param string $hashtag Hashtag name. + * @param string $index Index URL. + * + * @return string HTML hashtag link. + */ + private function getHashtagLink($hashtag, $index = '') + { + $hashtagLink = '#$1'; + return str_replace('$1', $hashtag, $hashtagLink); + } +} diff --git a/tests/plugins/PluginMarkdownTest.php b/tests/plugins/PluginMarkdownTest.php index 44364b05..d6951866 100644 --- a/tests/plugins/PluginMarkdownTest.php +++ b/tests/plugins/PluginMarkdownTest.php @@ -5,6 +5,7 @@ use Shaarli\Config\ConfigManager; * PluginMarkdownTest.php */ +require_once 'application/bookmark/LinkUtils.php'; require_once 'application/Utils.php'; require_once 'plugins/markdown/markdown.php'; diff --git a/tests/utils/CurlUtils.php b/tests/utils/CurlUtils.php new file mode 100644 index 00000000..1cc4907e --- /dev/null +++ b/tests/utils/CurlUtils.php @@ -0,0 +1,94 @@ + Date: Mon, 3 Dec 2018 23:49:20 +0100 Subject: namespacing: \Shaarli\Updater Signed-off-by: VirtualTam --- tests/Updater/DummyUpdater.php | 70 ---- tests/Updater/UpdaterTest.php | 810 -------------------------------------- tests/updater/DummyUpdater.php | 73 ++++ tests/updater/UpdaterTest.php | 815 +++++++++++++++++++++++++++++++++++++++ tests/utils/config/configPhp.php | 2 +- 5 files changed, 889 insertions(+), 881 deletions(-) delete mode 100644 tests/Updater/DummyUpdater.php delete mode 100644 tests/Updater/UpdaterTest.php create mode 100644 tests/updater/DummyUpdater.php create mode 100644 tests/updater/UpdaterTest.php (limited to 'tests') diff --git a/tests/Updater/DummyUpdater.php b/tests/Updater/DummyUpdater.php deleted file mode 100644 index 3c74b4ff..00000000 --- a/tests/Updater/DummyUpdater.php +++ /dev/null @@ -1,70 +0,0 @@ -methods = $class->getMethods(ReflectionMethod::IS_FINAL); - } - - /** - * Update method 1. - * - * @return bool true. - */ - final private function updateMethodDummy1() - { - return true; - } - - /** - * Update method 2. - * - * @return bool true. - */ - final private function updateMethodDummy2() - { - return true; - } - - /** - * Update method 3. - * - * @return bool true. - */ - final private function updateMethodDummy3() - { - return true; - } - - /** - * Update method 4, raise an exception. - * - * @throws Exception error. - */ - final private function updateMethodException() - { - throw new Exception('whatever'); - } -} diff --git a/tests/Updater/UpdaterTest.php b/tests/Updater/UpdaterTest.php deleted file mode 100644 index f910e054..00000000 --- a/tests/Updater/UpdaterTest.php +++ /dev/null @@ -1,810 +0,0 @@ -conf = new ConfigManager(self::$configFile); - } - - /** - * Test read_updates_file with an empty/missing file. - */ - public function testReadEmptyUpdatesFile() - { - $this->assertEquals(array(), read_updates_file('')); - $updatesFile = $this->conf->get('resource.data_dir') . '/updates.txt'; - touch($updatesFile); - $this->assertEquals(array(), read_updates_file($updatesFile)); - unlink($updatesFile); - } - - /** - * Test read/write updates file. - */ - public function testReadWriteUpdatesFile() - { - $updatesFile = $this->conf->get('resource.data_dir') . '/updates.txt'; - $updatesMethods = array('m1', 'm2', 'm3'); - - write_updates_file($updatesFile, $updatesMethods); - $readMethods = read_updates_file($updatesFile); - $this->assertEquals($readMethods, $updatesMethods); - - // Update - $updatesMethods[] = 'm4'; - write_updates_file($updatesFile, $updatesMethods); - $readMethods = read_updates_file($updatesFile); - $this->assertEquals($readMethods, $updatesMethods); - unlink($updatesFile); - } - - /** - * Test errors in write_updates_file(): empty updates file. - * - * @expectedException Exception - * @expectedExceptionMessageRegExp /Updates file path is not set(.*)/ - */ - public function testWriteEmptyUpdatesFile() - { - write_updates_file('', array('test')); - } - - /** - * Test errors in write_updates_file(): not writable updates file. - * - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to write(.*)/ - */ - public function testWriteUpdatesFileNotWritable() - { - $updatesFile = $this->conf->get('resource.data_dir') . '/updates.txt'; - touch($updatesFile); - chmod($updatesFile, 0444); - try { - @write_updates_file($updatesFile, array('test')); - } catch (Exception $e) { - unlink($updatesFile); - throw $e; - } - } - - /** - * Test the update() method, with no update to run. - * 1. Everything already run. - * 2. User is logged out. - */ - public function testNoUpdates() - { - $updates = array( - 'updateMethodDummy1', - 'updateMethodDummy2', - 'updateMethodDummy3', - 'updateMethodException', - ); - $updater = new DummyUpdater($updates, array(), $this->conf, true); - $this->assertEquals(array(), $updater->update()); - - $updater = new DummyUpdater(array(), array(), $this->conf, false); - $this->assertEquals(array(), $updater->update()); - } - - /** - * Test the update() method, with all updates to run (except the failing one). - */ - public function testUpdatesFirstTime() - { - $updates = array('updateMethodException',); - $expectedUpdates = array( - 'updateMethodDummy1', - 'updateMethodDummy2', - 'updateMethodDummy3', - ); - $updater = new DummyUpdater($updates, array(), $this->conf, true); - $this->assertEquals($expectedUpdates, $updater->update()); - } - - /** - * Test the update() method, only one update to run. - */ - public function testOneUpdate() - { - $updates = array( - 'updateMethodDummy1', - 'updateMethodDummy3', - 'updateMethodException', - ); - $expectedUpdate = array('updateMethodDummy2'); - - $updater = new DummyUpdater($updates, array(), $this->conf, true); - $this->assertEquals($expectedUpdate, $updater->update()); - } - - /** - * Test Update failed. - * - * @expectedException UpdaterException - */ - public function testUpdateFailed() - { - $updates = array( - 'updateMethodDummy1', - 'updateMethodDummy2', - 'updateMethodDummy3', - ); - - $updater = new DummyUpdater($updates, array(), $this->conf, true); - $updater->update(); - } - - /** - * Test update mergeDeprecatedConfig: - * 1. init a config file. - * 2. init a options.php file with update value. - * 3. merge. - * 4. check updated value in config file. - */ - public function testUpdateMergeDeprecatedConfig() - { - $this->conf->setConfigFile('tests/utils/config/configPhp'); - $this->conf->reset(); - - $optionsFile = 'tests/Updater/options.php'; - $options = 'conf->setConfigFile('tests/Updater/config'); - - // merge configs - $updater = new Updater(array(), array(), $this->conf, true); - // This writes a new config file in tests/Updater/config.php - $updater->updateMethodMergeDeprecatedConfigFile(); - - // make sure updated field is changed - $this->conf->reload(); - $this->assertTrue($this->conf->get('privacy.default_private_links')); - $this->assertFalse(is_file($optionsFile)); - // Delete the generated file. - unlink($this->conf->getConfigFileExt()); - } - - /** - * Test mergeDeprecatedConfig in without options file. - */ - public function testMergeDeprecatedConfigNoFile() - { - $updater = new Updater(array(), array(), $this->conf, true); - $updater->updateMethodMergeDeprecatedConfigFile(); - - $this->assertEquals('root', $this->conf->get('credentials.login')); - } - - /** - * Test renameDashTags update method. - */ - public function testRenameDashTags() - { - $refDB = new ReferenceLinkDB(); - $refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $this->assertEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); - $updater = new Updater(array(), $linkDB, $this->conf, true); - $updater->updateMethodRenameDashTags(); - $this->assertNotEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); - } - - /** - * Convert old PHP config file to JSON config. - */ - public function testConfigToJson() - { - $configFile = 'tests/utils/config/configPhp'; - $this->conf->setConfigFile($configFile); - $this->conf->reset(); - - // The ConfigIO is initialized with ConfigPhp. - $this->assertTrue($this->conf->getConfigIO() instanceof ConfigPhp); - - $updater = new Updater(array(), array(), $this->conf, false); - $done = $updater->updateMethodConfigToJson(); - $this->assertTrue($done); - - // The ConfigIO has been updated to ConfigJson. - $this->assertTrue($this->conf->getConfigIO() instanceof ConfigJson); - $this->assertTrue(file_exists($this->conf->getConfigFileExt())); - - // Check JSON config data. - $this->conf->reload(); - $this->assertEquals('root', $this->conf->get('credentials.login')); - $this->assertEquals('lala', $this->conf->get('redirector.url')); - $this->assertEquals('data/datastore.php', $this->conf->get('resource.datastore')); - $this->assertEquals('1', $this->conf->get('plugins.WALLABAG_VERSION')); - - rename($configFile . '.save.php', $configFile . '.php'); - unlink($this->conf->getConfigFileExt()); - } - - /** - * Launch config conversion update with an existing JSON file => nothing to do. - */ - public function testConfigToJsonNothingToDo() - { - $filetime = filemtime($this->conf->getConfigFileExt()); - $updater = new Updater(array(), array(), $this->conf, false); - $done = $updater->updateMethodConfigToJson(); - $this->assertTrue($done); - $expected = filemtime($this->conf->getConfigFileExt()); - $this->assertEquals($expected, $filetime); - } - - /** - * Test escapeUnescapedConfig with valid data. - */ - public function testEscapeConfig() - { - $sandbox = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandbox . '.json.php'); - $this->conf = new ConfigManager($sandbox); - $title = ''; - $headerLink = ''; - $redirectorUrl = ''; - $this->conf->set('general.title', $title); - $this->conf->set('general.header_link', $headerLink); - $this->conf->set('redirector.url', $redirectorUrl); - $updater = new Updater(array(), array(), $this->conf, true); - $done = $updater->updateMethodEscapeUnescapedConfig(); - $this->assertTrue($done); - $this->conf->reload(); - $this->assertEquals(escape($title), $this->conf->get('general.title')); - $this->assertEquals(escape($headerLink), $this->conf->get('general.header_link')); - $this->assertEquals(escape($redirectorUrl), $this->conf->get('redirector.url')); - unlink($sandbox . '.json.php'); - } - - /** - * Test updateMethodApiSettings(): create default settings for the API (enabled + secret). - */ - public function testUpdateApiSettings() - { - $confFile = 'sandbox/config'; - copy(self::$configFile .'.json.php', $confFile .'.json.php'); - $conf = new ConfigManager($confFile); - $updater = new Updater(array(), array(), $conf, true); - - $this->assertFalse($conf->exists('api.enabled')); - $this->assertFalse($conf->exists('api.secret')); - $updater->updateMethodApiSettings(); - $conf->reload(); - $this->assertTrue($conf->get('api.enabled')); - $this->assertTrue($conf->exists('api.secret')); - unlink($confFile .'.json.php'); - } - - /** - * Test updateMethodApiSettings(): already set, do nothing. - */ - public function testUpdateApiSettingsNothingToDo() - { - $confFile = 'sandbox/config'; - copy(self::$configFile .'.json.php', $confFile .'.json.php'); - $conf = new ConfigManager($confFile); - $conf->set('api.enabled', false); - $conf->set('api.secret', ''); - $updater = new Updater(array(), array(), $conf, true); - $updater->updateMethodApiSettings(); - $this->assertFalse($conf->get('api.enabled')); - $this->assertEmpty($conf->get('api.secret')); - unlink($confFile .'.json.php'); - } - - /** - * Test updateMethodDatastoreIds(). - */ - public function testDatastoreIds() - { - $links = array( - '20121206_182539' => array( - 'linkdate' => '20121206_182539', - 'title' => 'Geek and Poke', - 'url' => 'http://geek-and-poke.com/', - 'description' => 'desc', - 'tags' => 'dev cartoon tag1 tag2 tag3 tag4 ', - 'updated' => '20121206_190301', - 'private' => false, - ), - '20121206_172539' => array( - 'linkdate' => '20121206_172539', - 'title' => 'UserFriendly - Samba', - 'url' => 'http://ars.userfriendly.org/cartoons/?id=20010306', - 'description' => '', - 'tags' => 'samba cartoon web', - 'private' => false, - ), - '20121206_142300' => array( - 'linkdate' => '20121206_142300', - 'title' => 'UserFriendly - Web Designer', - 'url' => 'http://ars.userfriendly.org/cartoons/?id=20121206', - 'description' => 'Naming conventions... #private', - 'tags' => 'samba cartoon web', - 'private' => true, - ), - ); - $refDB = new ReferenceLinkDB(); - $refDB->setLinks($links); - $refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $checksum = hash_file('sha1', self::$testDatastore); - - $this->conf->set('resource.data_dir', 'sandbox'); - $this->conf->set('resource.datastore', self::$testDatastore); - - $updater = new Updater(array(), $linkDB, $this->conf, true); - $this->assertTrue($updater->updateMethodDatastoreIds()); - - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $backup = glob($this->conf->get('resource.data_dir') . '/datastore.'. date('YmdH') .'*.php'); - $backup = $backup[0]; - - $this->assertFileExists($backup); - $this->assertEquals($checksum, hash_file('sha1', $backup)); - unlink($backup); - - $this->assertEquals(3, count($linkDB)); - $this->assertTrue(isset($linkDB[0])); - $this->assertFalse(isset($linkDB[0]['linkdate'])); - $this->assertEquals(0, $linkDB[0]['id']); - $this->assertEquals('UserFriendly - Web Designer', $linkDB[0]['title']); - $this->assertEquals('http://ars.userfriendly.org/cartoons/?id=20121206', $linkDB[0]['url']); - $this->assertEquals('Naming conventions... #private', $linkDB[0]['description']); - $this->assertEquals('samba cartoon web', $linkDB[0]['tags']); - $this->assertTrue($linkDB[0]['private']); - $this->assertEquals( - DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_142300'), - $linkDB[0]['created'] - ); - - $this->assertTrue(isset($linkDB[1])); - $this->assertFalse(isset($linkDB[1]['linkdate'])); - $this->assertEquals(1, $linkDB[1]['id']); - $this->assertEquals('UserFriendly - Samba', $linkDB[1]['title']); - $this->assertEquals( - DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_172539'), - $linkDB[1]['created'] - ); - - $this->assertTrue(isset($linkDB[2])); - $this->assertFalse(isset($linkDB[2]['linkdate'])); - $this->assertEquals(2, $linkDB[2]['id']); - $this->assertEquals('Geek and Poke', $linkDB[2]['title']); - $this->assertEquals( - DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_182539'), - $linkDB[2]['created'] - ); - $this->assertEquals( - DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_190301'), - $linkDB[2]['updated'] - ); - } - - /** - * Test updateMethodDatastoreIds() with the update already applied: nothing to do. - */ - public function testDatastoreIdsNothingToDo() - { - $refDB = new ReferenceLinkDB(); - $refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $this->conf->set('resource.data_dir', 'sandbox'); - $this->conf->set('resource.datastore', self::$testDatastore); - - $checksum = hash_file('sha1', self::$testDatastore); - $updater = new Updater(array(), $linkDB, $this->conf, true); - $this->assertTrue($updater->updateMethodDatastoreIds()); - $this->assertEquals($checksum, hash_file('sha1', self::$testDatastore)); - } - - /** - * Test defaultTheme update with default settings: nothing to do. - */ - public function testDefaultThemeWithDefaultSettings() - { - $sandbox = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandbox . '.json.php'); - $this->conf = new ConfigManager($sandbox); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodDefaultTheme()); - - $this->assertEquals('tpl/', $this->conf->get('resource.raintpl_tpl')); - $this->assertEquals('default', $this->conf->get('resource.theme')); - $this->conf = new ConfigManager($sandbox); - $this->assertEquals('tpl/', $this->conf->get('resource.raintpl_tpl')); - $this->assertEquals('default', $this->conf->get('resource.theme')); - unlink($sandbox . '.json.php'); - } - - /** - * Test defaultTheme update with a custom theme in a subfolder - */ - public function testDefaultThemeWithCustomTheme() - { - $theme = 'iamanartist'; - $sandbox = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandbox . '.json.php'); - $this->conf = new ConfigManager($sandbox); - mkdir('sandbox/'. $theme); - touch('sandbox/'. $theme .'/linklist.html'); - $this->conf->set('resource.raintpl_tpl', 'sandbox/'. $theme .'/'); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodDefaultTheme()); - - $this->assertEquals('sandbox', $this->conf->get('resource.raintpl_tpl')); - $this->assertEquals($theme, $this->conf->get('resource.theme')); - $this->conf = new ConfigManager($sandbox); - $this->assertEquals('sandbox', $this->conf->get('resource.raintpl_tpl')); - $this->assertEquals($theme, $this->conf->get('resource.theme')); - unlink($sandbox . '.json.php'); - unlink('sandbox/'. $theme .'/linklist.html'); - rmdir('sandbox/'. $theme); - } - - /** - * Test updateMethodEscapeMarkdown with markdown plugin enabled - * => setting markdown_escape set to false. - */ - public function testEscapeMarkdownSettingToFalse() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - - $this->conf->set('general.enabled_plugins', ['markdown']); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodEscapeMarkdown()); - $this->assertFalse($this->conf->get('security.markdown_escape')); - - // reload from file - $this->conf = new ConfigManager($sandboxConf); - $this->assertFalse($this->conf->get('security.markdown_escape')); - } - - - /** - * Test updateMethodEscapeMarkdown with markdown plugin disabled - * => setting markdown_escape set to true. - */ - public function testEscapeMarkdownSettingToTrue() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - - $this->conf->set('general.enabled_plugins', []); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodEscapeMarkdown()); - $this->assertTrue($this->conf->get('security.markdown_escape')); - - // reload from file - $this->conf = new ConfigManager($sandboxConf); - $this->assertTrue($this->conf->get('security.markdown_escape')); - } - - /** - * Test updateMethodEscapeMarkdown with nothing to do (setting already enabled) - */ - public function testEscapeMarkdownSettingNothingToDoEnabled() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $this->conf->set('security.markdown_escape', true); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodEscapeMarkdown()); - $this->assertTrue($this->conf->get('security.markdown_escape')); - } - - /** - * Test updateMethodEscapeMarkdown with nothing to do (setting already disabled) - */ - public function testEscapeMarkdownSettingNothingToDoDisabled() - { - $this->conf->set('security.markdown_escape', false); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodEscapeMarkdown()); - $this->assertFalse($this->conf->get('security.markdown_escape')); - } - - /** - * Test updateMethodPiwikUrl with valid data - */ - public function testUpdatePiwikUrlValid() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $url = 'mypiwik.tld'; - $this->conf->set('plugins.PIWIK_URL', $url); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodPiwikUrl()); - $this->assertEquals('http://'. $url, $this->conf->get('plugins.PIWIK_URL')); - - // reload from file - $this->conf = new ConfigManager($sandboxConf); - $this->assertEquals('http://'. $url, $this->conf->get('plugins.PIWIK_URL')); - } - - /** - * Test updateMethodPiwikUrl without setting - */ - public function testUpdatePiwikUrlEmpty() - { - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodPiwikUrl()); - $this->assertEmpty($this->conf->get('plugins.PIWIK_URL')); - } - - /** - * Test updateMethodPiwikUrl: valid URL, nothing to do - */ - public function testUpdatePiwikUrlNothingToDo() - { - $url = 'https://mypiwik.tld'; - $this->conf->set('plugins.PIWIK_URL', $url); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodPiwikUrl()); - $this->assertEquals($url, $this->conf->get('plugins.PIWIK_URL')); - } - - /** - * Test updateMethodAtomDefault with show_atom set to false - * => update to true. - */ - public function testUpdateMethodAtomDefault() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $this->conf->set('feed.show_atom', false); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodAtomDefault()); - $this->assertTrue($this->conf->get('feed.show_atom')); - // reload from file - $this->conf = new ConfigManager($sandboxConf); - $this->assertTrue($this->conf->get('feed.show_atom')); - } - /** - * Test updateMethodAtomDefault with show_atom not set. - * => nothing to do - */ - public function testUpdateMethodAtomDefaultNoExist() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodAtomDefault()); - $this->assertTrue($this->conf->get('feed.show_atom')); - } - /** - * Test updateMethodAtomDefault with show_atom set to true. - * => nothing to do - */ - public function testUpdateMethodAtomDefaultAlreadyTrue() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $this->conf->set('feed.show_atom', true); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodAtomDefault()); - $this->assertTrue($this->conf->get('feed.show_atom')); - } - - /** - * Test updateMethodDownloadSizeAndTimeoutConf, it should be set if none is already defined. - */ - public function testUpdateMethodDownloadSizeAndTimeoutConf() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); - $this->assertEquals(4194304, $this->conf->get('general.download_max_size')); - $this->assertEquals(30, $this->conf->get('general.download_timeout')); - - $this->conf = new ConfigManager($sandboxConf); - $this->assertEquals(4194304, $this->conf->get('general.download_max_size')); - $this->assertEquals(30, $this->conf->get('general.download_timeout')); - } - - /** - * Test updateMethodDownloadSizeAndTimeoutConf, it shouldn't be set if it is already defined. - */ - public function testUpdateMethodDownloadSizeAndTimeoutConfIgnore() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $this->conf->set('general.download_max_size', 38); - $this->conf->set('general.download_timeout', 70); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); - $this->assertEquals(38, $this->conf->get('general.download_max_size')); - $this->assertEquals(70, $this->conf->get('general.download_timeout')); - } - - /** - * Test updateMethodDownloadSizeAndTimeoutConf, only the maz size should be set here. - */ - public function testUpdateMethodDownloadSizeAndTimeoutConfOnlySize() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $this->conf->set('general.download_max_size', 38); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); - $this->assertEquals(38, $this->conf->get('general.download_max_size')); - $this->assertEquals(30, $this->conf->get('general.download_timeout')); - } - - /** - * Test updateMethodDownloadSizeAndTimeoutConf, only the time out should be set here. - */ - public function testUpdateMethodDownloadSizeAndTimeoutConfOnlyTimeout() - { - $sandboxConf = 'sandbox/config'; - copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); - $this->conf = new ConfigManager($sandboxConf); - $this->conf->set('general.download_timeout', 3); - $updater = new Updater([], [], $this->conf, true); - $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); - $this->assertEquals(4194304, $this->conf->get('general.download_max_size')); - $this->assertEquals(3, $this->conf->get('general.download_timeout')); - } - - /** -<<<<<<< HEAD - * Test updateMethodWebThumbnailer with thumbnails enabled. - */ - public function testUpdateMethodWebThumbnailerEnabled() - { - $this->conf->remove('thumbnails'); - $this->conf->set('thumbnail.enable_thumbnails', true); - $updater = new Updater([], [], $this->conf, true, $_SESSION); - $this->assertTrue($updater->updateMethodWebThumbnailer()); - $this->assertFalse($this->conf->exists('thumbnail')); - $this->assertEquals(\Shaarli\Thumbnailer::MODE_ALL, $this->conf->get('thumbnails.mode')); - $this->assertEquals(125, $this->conf->get('thumbnails.width')); - $this->assertEquals(90, $this->conf->get('thumbnails.height')); - $this->assertContains('You have enabled or changed thumbnails', $_SESSION['warnings'][0]); - } - - /** - * Test updateMethodWebThumbnailer with thumbnails disabled. - */ - public function testUpdateMethodWebThumbnailerDisabled() - { - $this->conf->remove('thumbnails'); - $this->conf->set('thumbnail.enable_thumbnails', false); - $updater = new Updater([], [], $this->conf, true, $_SESSION); - $this->assertTrue($updater->updateMethodWebThumbnailer()); - $this->assertFalse($this->conf->exists('thumbnail')); - $this->assertEquals(Thumbnailer::MODE_NONE, $this->conf->get('thumbnails.mode')); - $this->assertEquals(125, $this->conf->get('thumbnails.width')); - $this->assertEquals(90, $this->conf->get('thumbnails.height')); - $this->assertTrue(empty($_SESSION['warnings'])); - } - - /** - * Test updateMethodWebThumbnailer with thumbnails disabled. - */ - public function testUpdateMethodWebThumbnailerNothingToDo() - { - $updater = new Updater([], [], $this->conf, true, $_SESSION); - $this->assertTrue($updater->updateMethodWebThumbnailer()); - $this->assertFalse($this->conf->exists('thumbnail')); - $this->assertEquals(Thumbnailer::MODE_COMMON, $this->conf->get('thumbnails.mode')); - $this->assertEquals(90, $this->conf->get('thumbnails.width')); - $this->assertEquals(53, $this->conf->get('thumbnails.height')); - $this->assertTrue(empty($_SESSION['warnings'])); - } - - /** - * Test updateMethodSetSticky(). - */ - public function testUpdateStickyValid() - { - $blank = [ - 'id' => 1, - 'url' => 'z', - 'title' => '', - 'description' => '', - 'tags' => '', - 'created' => new DateTime(), - ]; - $links = [ - 1 => ['id' => 1] + $blank, - 2 => ['id' => 2] + $blank, - ]; - $refDB = new ReferenceLinkDB(); - $refDB->setLinks($links); - $refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $updater = new Updater(array(), $linkDB, $this->conf, true); - $this->assertTrue($updater->updateMethodSetSticky()); - - $linkDB = new LinkDB(self::$testDatastore, true, false); - foreach ($linkDB as $link) { - $this->assertFalse($link['sticky']); - } - } - - /** - * Test updateMethodSetSticky(). - */ - public function testUpdateStickyNothingToDo() - { - $blank = [ - 'id' => 1, - 'url' => 'z', - 'title' => '', - 'description' => '', - 'tags' => '', - 'created' => new DateTime(), - ]; - $links = [ - 1 => ['id' => 1, 'sticky' => true] + $blank, - 2 => ['id' => 2] + $blank, - ]; - $refDB = new ReferenceLinkDB(); - $refDB->setLinks($links); - $refDB->write(self::$testDatastore); - $linkDB = new LinkDB(self::$testDatastore, true, false); - - $updater = new Updater(array(), $linkDB, $this->conf, true); - $this->assertTrue($updater->updateMethodSetSticky()); - - $linkDB = new LinkDB(self::$testDatastore, true, false); - $this->assertTrue($linkDB[1]['sticky']); - } -} diff --git a/tests/updater/DummyUpdater.php b/tests/updater/DummyUpdater.php new file mode 100644 index 00000000..9e866f1f --- /dev/null +++ b/tests/updater/DummyUpdater.php @@ -0,0 +1,73 @@ +methods = $class->getMethods(ReflectionMethod::IS_FINAL); + } + + /** + * Update method 1. + * + * @return bool true. + */ + final private function updateMethodDummy1() + { + return true; + } + + /** + * Update method 2. + * + * @return bool true. + */ + final private function updateMethodDummy2() + { + return true; + } + + /** + * Update method 3. + * + * @return bool true. + */ + final private function updateMethodDummy3() + { + return true; + } + + /** + * Update method 4, raise an exception. + * + * @throws Exception error. + */ + final private function updateMethodException() + { + throw new Exception('whatever'); + } +} diff --git a/tests/updater/UpdaterTest.php b/tests/updater/UpdaterTest.php new file mode 100644 index 00000000..d7df5963 --- /dev/null +++ b/tests/updater/UpdaterTest.php @@ -0,0 +1,815 @@ +conf = new ConfigManager(self::$configFile); + } + + /** + * Test read_updates_file with an empty/missing file. + */ + public function testReadEmptyUpdatesFile() + { + $this->assertEquals(array(), read_updates_file('')); + $updatesFile = $this->conf->get('resource.data_dir') . '/updates.txt'; + touch($updatesFile); + $this->assertEquals(array(), read_updates_file($updatesFile)); + unlink($updatesFile); + } + + /** + * Test read/write updates file. + */ + public function testReadWriteUpdatesFile() + { + $updatesFile = $this->conf->get('resource.data_dir') . '/updates.txt'; + $updatesMethods = array('m1', 'm2', 'm3'); + + write_updates_file($updatesFile, $updatesMethods); + $readMethods = read_updates_file($updatesFile); + $this->assertEquals($readMethods, $updatesMethods); + + // Update + $updatesMethods[] = 'm4'; + write_updates_file($updatesFile, $updatesMethods); + $readMethods = read_updates_file($updatesFile); + $this->assertEquals($readMethods, $updatesMethods); + unlink($updatesFile); + } + + /** + * Test errors in write_updates_file(): empty updates file. + * + * @expectedException Exception + * @expectedExceptionMessageRegExp /Updates file path is not set(.*)/ + */ + public function testWriteEmptyUpdatesFile() + { + write_updates_file('', array('test')); + } + + /** + * Test errors in write_updates_file(): not writable updates file. + * + * @expectedException Exception + * @expectedExceptionMessageRegExp /Unable to write(.*)/ + */ + public function testWriteUpdatesFileNotWritable() + { + $updatesFile = $this->conf->get('resource.data_dir') . '/updates.txt'; + touch($updatesFile); + chmod($updatesFile, 0444); + try { + @write_updates_file($updatesFile, array('test')); + } catch (Exception $e) { + unlink($updatesFile); + throw $e; + } + } + + /** + * Test the update() method, with no update to run. + * 1. Everything already run. + * 2. User is logged out. + */ + public function testNoUpdates() + { + $updates = array( + 'updateMethodDummy1', + 'updateMethodDummy2', + 'updateMethodDummy3', + 'updateMethodException', + ); + $updater = new DummyUpdater($updates, array(), $this->conf, true); + $this->assertEquals(array(), $updater->update()); + + $updater = new DummyUpdater(array(), array(), $this->conf, false); + $this->assertEquals(array(), $updater->update()); + } + + /** + * Test the update() method, with all updates to run (except the failing one). + */ + public function testUpdatesFirstTime() + { + $updates = array('updateMethodException',); + $expectedUpdates = array( + 'updateMethodDummy1', + 'updateMethodDummy2', + 'updateMethodDummy3', + ); + $updater = new DummyUpdater($updates, array(), $this->conf, true); + $this->assertEquals($expectedUpdates, $updater->update()); + } + + /** + * Test the update() method, only one update to run. + */ + public function testOneUpdate() + { + $updates = array( + 'updateMethodDummy1', + 'updateMethodDummy3', + 'updateMethodException', + ); + $expectedUpdate = array('updateMethodDummy2'); + + $updater = new DummyUpdater($updates, array(), $this->conf, true); + $this->assertEquals($expectedUpdate, $updater->update()); + } + + /** + * Test Update failed. + * + * @expectedException \Exception + */ + public function testUpdateFailed() + { + $updates = array( + 'updateMethodDummy1', + 'updateMethodDummy2', + 'updateMethodDummy3', + ); + + $updater = new DummyUpdater($updates, array(), $this->conf, true); + $updater->update(); + } + + /** + * Test update mergeDeprecatedConfig: + * 1. init a config file. + * 2. init a options.php file with update value. + * 3. merge. + * 4. check updated value in config file. + */ + public function testUpdateMergeDeprecatedConfig() + { + $this->conf->setConfigFile('tests/utils/config/configPhp'); + $this->conf->reset(); + + $optionsFile = 'tests/updater/options.php'; + $options = 'conf->setConfigFile('tests/updater/config'); + + // merge configs + $updater = new Updater(array(), array(), $this->conf, true); + // This writes a new config file in tests/updater/config.php + $updater->updateMethodMergeDeprecatedConfigFile(); + + // make sure updated field is changed + $this->conf->reload(); + $this->assertTrue($this->conf->get('privacy.default_private_links')); + $this->assertFalse(is_file($optionsFile)); + // Delete the generated file. + unlink($this->conf->getConfigFileExt()); + } + + /** + * Test mergeDeprecatedConfig in without options file. + */ + public function testMergeDeprecatedConfigNoFile() + { + $updater = new Updater(array(), array(), $this->conf, true); + $updater->updateMethodMergeDeprecatedConfigFile(); + + $this->assertEquals('root', $this->conf->get('credentials.login')); + } + + /** + * Test renameDashTags update method. + */ + public function testRenameDashTags() + { + $refDB = new \ReferenceLinkDB(); + $refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $this->assertEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); + $updater = new Updater(array(), $linkDB, $this->conf, true); + $updater->updateMethodRenameDashTags(); + $this->assertNotEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); + } + + /** + * Convert old PHP config file to JSON config. + */ + public function testConfigToJson() + { + $configFile = 'tests/utils/config/configPhp'; + $this->conf->setConfigFile($configFile); + $this->conf->reset(); + + // The ConfigIO is initialized with ConfigPhp. + $this->assertTrue($this->conf->getConfigIO() instanceof ConfigPhp); + + $updater = new Updater(array(), array(), $this->conf, false); + $done = $updater->updateMethodConfigToJson(); + $this->assertTrue($done); + + // The ConfigIO has been updated to ConfigJson. + $this->assertTrue($this->conf->getConfigIO() instanceof ConfigJson); + $this->assertTrue(file_exists($this->conf->getConfigFileExt())); + + // Check JSON config data. + $this->conf->reload(); + $this->assertEquals('root', $this->conf->get('credentials.login')); + $this->assertEquals('lala', $this->conf->get('redirector.url')); + $this->assertEquals('data/datastore.php', $this->conf->get('resource.datastore')); + $this->assertEquals('1', $this->conf->get('plugins.WALLABAG_VERSION')); + + rename($configFile . '.save.php', $configFile . '.php'); + unlink($this->conf->getConfigFileExt()); + } + + /** + * Launch config conversion update with an existing JSON file => nothing to do. + */ + public function testConfigToJsonNothingToDo() + { + $filetime = filemtime($this->conf->getConfigFileExt()); + $updater = new Updater(array(), array(), $this->conf, false); + $done = $updater->updateMethodConfigToJson(); + $this->assertTrue($done); + $expected = filemtime($this->conf->getConfigFileExt()); + $this->assertEquals($expected, $filetime); + } + + /** + * Test escapeUnescapedConfig with valid data. + */ + public function testEscapeConfig() + { + $sandbox = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandbox . '.json.php'); + $this->conf = new ConfigManager($sandbox); + $title = ''; + $headerLink = ''; + $redirectorUrl = ''; + $this->conf->set('general.title', $title); + $this->conf->set('general.header_link', $headerLink); + $this->conf->set('redirector.url', $redirectorUrl); + $updater = new Updater(array(), array(), $this->conf, true); + $done = $updater->updateMethodEscapeUnescapedConfig(); + $this->assertTrue($done); + $this->conf->reload(); + $this->assertEquals(escape($title), $this->conf->get('general.title')); + $this->assertEquals(escape($headerLink), $this->conf->get('general.header_link')); + $this->assertEquals(escape($redirectorUrl), $this->conf->get('redirector.url')); + unlink($sandbox . '.json.php'); + } + + /** + * Test updateMethodApiSettings(): create default settings for the API (enabled + secret). + */ + public function testUpdateApiSettings() + { + $confFile = 'sandbox/config'; + copy(self::$configFile .'.json.php', $confFile .'.json.php'); + $conf = new ConfigManager($confFile); + $updater = new Updater(array(), array(), $conf, true); + + $this->assertFalse($conf->exists('api.enabled')); + $this->assertFalse($conf->exists('api.secret')); + $updater->updateMethodApiSettings(); + $conf->reload(); + $this->assertTrue($conf->get('api.enabled')); + $this->assertTrue($conf->exists('api.secret')); + unlink($confFile .'.json.php'); + } + + /** + * Test updateMethodApiSettings(): already set, do nothing. + */ + public function testUpdateApiSettingsNothingToDo() + { + $confFile = 'sandbox/config'; + copy(self::$configFile .'.json.php', $confFile .'.json.php'); + $conf = new ConfigManager($confFile); + $conf->set('api.enabled', false); + $conf->set('api.secret', ''); + $updater = new Updater(array(), array(), $conf, true); + $updater->updateMethodApiSettings(); + $this->assertFalse($conf->get('api.enabled')); + $this->assertEmpty($conf->get('api.secret')); + unlink($confFile .'.json.php'); + } + + /** + * Test updateMethodDatastoreIds(). + */ + public function testDatastoreIds() + { + $links = array( + '20121206_182539' => array( + 'linkdate' => '20121206_182539', + 'title' => 'Geek and Poke', + 'url' => 'http://geek-and-poke.com/', + 'description' => 'desc', + 'tags' => 'dev cartoon tag1 tag2 tag3 tag4 ', + 'updated' => '20121206_190301', + 'private' => false, + ), + '20121206_172539' => array( + 'linkdate' => '20121206_172539', + 'title' => 'UserFriendly - Samba', + 'url' => 'http://ars.userfriendly.org/cartoons/?id=20010306', + 'description' => '', + 'tags' => 'samba cartoon web', + 'private' => false, + ), + '20121206_142300' => array( + 'linkdate' => '20121206_142300', + 'title' => 'UserFriendly - Web Designer', + 'url' => 'http://ars.userfriendly.org/cartoons/?id=20121206', + 'description' => 'Naming conventions... #private', + 'tags' => 'samba cartoon web', + 'private' => true, + ), + ); + $refDB = new \ReferenceLinkDB(); + $refDB->setLinks($links); + $refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $checksum = hash_file('sha1', self::$testDatastore); + + $this->conf->set('resource.data_dir', 'sandbox'); + $this->conf->set('resource.datastore', self::$testDatastore); + + $updater = new Updater(array(), $linkDB, $this->conf, true); + $this->assertTrue($updater->updateMethodDatastoreIds()); + + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $backup = glob($this->conf->get('resource.data_dir') . '/datastore.'. date('YmdH') .'*.php'); + $backup = $backup[0]; + + $this->assertFileExists($backup); + $this->assertEquals($checksum, hash_file('sha1', $backup)); + unlink($backup); + + $this->assertEquals(3, count($linkDB)); + $this->assertTrue(isset($linkDB[0])); + $this->assertFalse(isset($linkDB[0]['linkdate'])); + $this->assertEquals(0, $linkDB[0]['id']); + $this->assertEquals('UserFriendly - Web Designer', $linkDB[0]['title']); + $this->assertEquals('http://ars.userfriendly.org/cartoons/?id=20121206', $linkDB[0]['url']); + $this->assertEquals('Naming conventions... #private', $linkDB[0]['description']); + $this->assertEquals('samba cartoon web', $linkDB[0]['tags']); + $this->assertTrue($linkDB[0]['private']); + $this->assertEquals( + DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_142300'), + $linkDB[0]['created'] + ); + + $this->assertTrue(isset($linkDB[1])); + $this->assertFalse(isset($linkDB[1]['linkdate'])); + $this->assertEquals(1, $linkDB[1]['id']); + $this->assertEquals('UserFriendly - Samba', $linkDB[1]['title']); + $this->assertEquals( + DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_172539'), + $linkDB[1]['created'] + ); + + $this->assertTrue(isset($linkDB[2])); + $this->assertFalse(isset($linkDB[2]['linkdate'])); + $this->assertEquals(2, $linkDB[2]['id']); + $this->assertEquals('Geek and Poke', $linkDB[2]['title']); + $this->assertEquals( + DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_182539'), + $linkDB[2]['created'] + ); + $this->assertEquals( + DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20121206_190301'), + $linkDB[2]['updated'] + ); + } + + /** + * Test updateMethodDatastoreIds() with the update already applied: nothing to do. + */ + public function testDatastoreIdsNothingToDo() + { + $refDB = new \ReferenceLinkDB(); + $refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $this->conf->set('resource.data_dir', 'sandbox'); + $this->conf->set('resource.datastore', self::$testDatastore); + + $checksum = hash_file('sha1', self::$testDatastore); + $updater = new Updater(array(), $linkDB, $this->conf, true); + $this->assertTrue($updater->updateMethodDatastoreIds()); + $this->assertEquals($checksum, hash_file('sha1', self::$testDatastore)); + } + + /** + * Test defaultTheme update with default settings: nothing to do. + */ + public function testDefaultThemeWithDefaultSettings() + { + $sandbox = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandbox . '.json.php'); + $this->conf = new ConfigManager($sandbox); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodDefaultTheme()); + + $this->assertEquals('tpl/', $this->conf->get('resource.raintpl_tpl')); + $this->assertEquals('default', $this->conf->get('resource.theme')); + $this->conf = new ConfigManager($sandbox); + $this->assertEquals('tpl/', $this->conf->get('resource.raintpl_tpl')); + $this->assertEquals('default', $this->conf->get('resource.theme')); + unlink($sandbox . '.json.php'); + } + + /** + * Test defaultTheme update with a custom theme in a subfolder + */ + public function testDefaultThemeWithCustomTheme() + { + $theme = 'iamanartist'; + $sandbox = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandbox . '.json.php'); + $this->conf = new ConfigManager($sandbox); + mkdir('sandbox/'. $theme); + touch('sandbox/'. $theme .'/linklist.html'); + $this->conf->set('resource.raintpl_tpl', 'sandbox/'. $theme .'/'); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodDefaultTheme()); + + $this->assertEquals('sandbox', $this->conf->get('resource.raintpl_tpl')); + $this->assertEquals($theme, $this->conf->get('resource.theme')); + $this->conf = new ConfigManager($sandbox); + $this->assertEquals('sandbox', $this->conf->get('resource.raintpl_tpl')); + $this->assertEquals($theme, $this->conf->get('resource.theme')); + unlink($sandbox . '.json.php'); + unlink('sandbox/'. $theme .'/linklist.html'); + rmdir('sandbox/'. $theme); + } + + /** + * Test updateMethodEscapeMarkdown with markdown plugin enabled + * => setting markdown_escape set to false. + */ + public function testEscapeMarkdownSettingToFalse() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + + $this->conf->set('general.enabled_plugins', ['markdown']); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodEscapeMarkdown()); + $this->assertFalse($this->conf->get('security.markdown_escape')); + + // reload from file + $this->conf = new ConfigManager($sandboxConf); + $this->assertFalse($this->conf->get('security.markdown_escape')); + } + + + /** + * Test updateMethodEscapeMarkdown with markdown plugin disabled + * => setting markdown_escape set to true. + */ + public function testEscapeMarkdownSettingToTrue() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + + $this->conf->set('general.enabled_plugins', []); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodEscapeMarkdown()); + $this->assertTrue($this->conf->get('security.markdown_escape')); + + // reload from file + $this->conf = new ConfigManager($sandboxConf); + $this->assertTrue($this->conf->get('security.markdown_escape')); + } + + /** + * Test updateMethodEscapeMarkdown with nothing to do (setting already enabled) + */ + public function testEscapeMarkdownSettingNothingToDoEnabled() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $this->conf->set('security.markdown_escape', true); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodEscapeMarkdown()); + $this->assertTrue($this->conf->get('security.markdown_escape')); + } + + /** + * Test updateMethodEscapeMarkdown with nothing to do (setting already disabled) + */ + public function testEscapeMarkdownSettingNothingToDoDisabled() + { + $this->conf->set('security.markdown_escape', false); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodEscapeMarkdown()); + $this->assertFalse($this->conf->get('security.markdown_escape')); + } + + /** + * Test updateMethodPiwikUrl with valid data + */ + public function testUpdatePiwikUrlValid() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $url = 'mypiwik.tld'; + $this->conf->set('plugins.PIWIK_URL', $url); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodPiwikUrl()); + $this->assertEquals('http://'. $url, $this->conf->get('plugins.PIWIK_URL')); + + // reload from file + $this->conf = new ConfigManager($sandboxConf); + $this->assertEquals('http://'. $url, $this->conf->get('plugins.PIWIK_URL')); + } + + /** + * Test updateMethodPiwikUrl without setting + */ + public function testUpdatePiwikUrlEmpty() + { + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodPiwikUrl()); + $this->assertEmpty($this->conf->get('plugins.PIWIK_URL')); + } + + /** + * Test updateMethodPiwikUrl: valid URL, nothing to do + */ + public function testUpdatePiwikUrlNothingToDo() + { + $url = 'https://mypiwik.tld'; + $this->conf->set('plugins.PIWIK_URL', $url); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodPiwikUrl()); + $this->assertEquals($url, $this->conf->get('plugins.PIWIK_URL')); + } + + /** + * Test updateMethodAtomDefault with show_atom set to false + * => update to true. + */ + public function testUpdateMethodAtomDefault() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $this->conf->set('feed.show_atom', false); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodAtomDefault()); + $this->assertTrue($this->conf->get('feed.show_atom')); + // reload from file + $this->conf = new ConfigManager($sandboxConf); + $this->assertTrue($this->conf->get('feed.show_atom')); + } + /** + * Test updateMethodAtomDefault with show_atom not set. + * => nothing to do + */ + public function testUpdateMethodAtomDefaultNoExist() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodAtomDefault()); + $this->assertTrue($this->conf->get('feed.show_atom')); + } + /** + * Test updateMethodAtomDefault with show_atom set to true. + * => nothing to do + */ + public function testUpdateMethodAtomDefaultAlreadyTrue() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $this->conf->set('feed.show_atom', true); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodAtomDefault()); + $this->assertTrue($this->conf->get('feed.show_atom')); + } + + /** + * Test updateMethodDownloadSizeAndTimeoutConf, it should be set if none is already defined. + */ + public function testUpdateMethodDownloadSizeAndTimeoutConf() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); + $this->assertEquals(4194304, $this->conf->get('general.download_max_size')); + $this->assertEquals(30, $this->conf->get('general.download_timeout')); + + $this->conf = new ConfigManager($sandboxConf); + $this->assertEquals(4194304, $this->conf->get('general.download_max_size')); + $this->assertEquals(30, $this->conf->get('general.download_timeout')); + } + + /** + * Test updateMethodDownloadSizeAndTimeoutConf, it shouldn't be set if it is already defined. + */ + public function testUpdateMethodDownloadSizeAndTimeoutConfIgnore() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $this->conf->set('general.download_max_size', 38); + $this->conf->set('general.download_timeout', 70); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); + $this->assertEquals(38, $this->conf->get('general.download_max_size')); + $this->assertEquals(70, $this->conf->get('general.download_timeout')); + } + + /** + * Test updateMethodDownloadSizeAndTimeoutConf, only the maz size should be set here. + */ + public function testUpdateMethodDownloadSizeAndTimeoutConfOnlySize() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $this->conf->set('general.download_max_size', 38); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); + $this->assertEquals(38, $this->conf->get('general.download_max_size')); + $this->assertEquals(30, $this->conf->get('general.download_timeout')); + } + + /** + * Test updateMethodDownloadSizeAndTimeoutConf, only the time out should be set here. + */ + public function testUpdateMethodDownloadSizeAndTimeoutConfOnlyTimeout() + { + $sandboxConf = 'sandbox/config'; + copy(self::$configFile . '.json.php', $sandboxConf . '.json.php'); + $this->conf = new ConfigManager($sandboxConf); + $this->conf->set('general.download_timeout', 3); + $updater = new Updater([], [], $this->conf, true); + $this->assertTrue($updater->updateMethodDownloadSizeAndTimeoutConf()); + $this->assertEquals(4194304, $this->conf->get('general.download_max_size')); + $this->assertEquals(3, $this->conf->get('general.download_timeout')); + } + + /** +<<<<<<< HEAD + * Test updateMethodWebThumbnailer with thumbnails enabled. + */ + public function testUpdateMethodWebThumbnailerEnabled() + { + $this->conf->remove('thumbnails'); + $this->conf->set('thumbnail.enable_thumbnails', true); + $updater = new Updater([], [], $this->conf, true, $_SESSION); + $this->assertTrue($updater->updateMethodWebThumbnailer()); + $this->assertFalse($this->conf->exists('thumbnail')); + $this->assertEquals(\Shaarli\Thumbnailer::MODE_ALL, $this->conf->get('thumbnails.mode')); + $this->assertEquals(125, $this->conf->get('thumbnails.width')); + $this->assertEquals(90, $this->conf->get('thumbnails.height')); + $this->assertContains('You have enabled or changed thumbnails', $_SESSION['warnings'][0]); + } + + /** + * Test updateMethodWebThumbnailer with thumbnails disabled. + */ + public function testUpdateMethodWebThumbnailerDisabled() + { + $this->conf->remove('thumbnails'); + $this->conf->set('thumbnail.enable_thumbnails', false); + $updater = new Updater([], [], $this->conf, true, $_SESSION); + $this->assertTrue($updater->updateMethodWebThumbnailer()); + $this->assertFalse($this->conf->exists('thumbnail')); + $this->assertEquals(Thumbnailer::MODE_NONE, $this->conf->get('thumbnails.mode')); + $this->assertEquals(125, $this->conf->get('thumbnails.width')); + $this->assertEquals(90, $this->conf->get('thumbnails.height')); + $this->assertTrue(empty($_SESSION['warnings'])); + } + + /** + * Test updateMethodWebThumbnailer with thumbnails disabled. + */ + public function testUpdateMethodWebThumbnailerNothingToDo() + { + $updater = new Updater([], [], $this->conf, true, $_SESSION); + $this->assertTrue($updater->updateMethodWebThumbnailer()); + $this->assertFalse($this->conf->exists('thumbnail')); + $this->assertEquals(Thumbnailer::MODE_COMMON, $this->conf->get('thumbnails.mode')); + $this->assertEquals(90, $this->conf->get('thumbnails.width')); + $this->assertEquals(53, $this->conf->get('thumbnails.height')); + $this->assertTrue(empty($_SESSION['warnings'])); + } + + /** + * Test updateMethodSetSticky(). + */ + public function testUpdateStickyValid() + { + $blank = [ + 'id' => 1, + 'url' => 'z', + 'title' => '', + 'description' => '', + 'tags' => '', + 'created' => new DateTime(), + ]; + $links = [ + 1 => ['id' => 1] + $blank, + 2 => ['id' => 2] + $blank, + ]; + $refDB = new \ReferenceLinkDB(); + $refDB->setLinks($links); + $refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $updater = new Updater(array(), $linkDB, $this->conf, true); + $this->assertTrue($updater->updateMethodSetSticky()); + + $linkDB = new LinkDB(self::$testDatastore, true, false); + foreach ($linkDB as $link) { + $this->assertFalse($link['sticky']); + } + } + + /** + * Test updateMethodSetSticky(). + */ + public function testUpdateStickyNothingToDo() + { + $blank = [ + 'id' => 1, + 'url' => 'z', + 'title' => '', + 'description' => '', + 'tags' => '', + 'created' => new DateTime(), + ]; + $links = [ + 1 => ['id' => 1, 'sticky' => true] + $blank, + 2 => ['id' => 2] + $blank, + ]; + $refDB = new \ReferenceLinkDB(); + $refDB->setLinks($links); + $refDB->write(self::$testDatastore); + $linkDB = new LinkDB(self::$testDatastore, true, false); + + $updater = new Updater(array(), $linkDB, $this->conf, true); + $this->assertTrue($updater->updateMethodSetSticky()); + + $linkDB = new LinkDB(self::$testDatastore, true, false); + $this->assertTrue($linkDB[1]['sticky']); + } +} diff --git a/tests/utils/config/configPhp.php b/tests/utils/config/configPhp.php index 34b11fcd..7dc81e22 100644 --- a/tests/utils/config/configPhp.php +++ b/tests/utils/config/configPhp.php @@ -8,7 +8,7 @@ $GLOBALS['titleLink'] = 'titleLink'; $GLOBALS['redirector'] = 'lala'; $GLOBALS['disablesessionprotection'] = false; $GLOBALS['privateLinkByDefault'] = false; -$GLOBALS['config']['DATADIR'] = 'tests/Updater'; +$GLOBALS['config']['DATADIR'] = 'tests/updater'; $GLOBALS['config']['PAGECACHE'] = 'sandbox/pagecache'; $GLOBALS['config']['DATASTORE'] = 'data/datastore.php'; $GLOBALS['plugins']['WALLABAG_VERSION'] = '1'; -- cgit v1.2.3 From 9778a1551ce708b9f421a181806412a05410f1fb Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 23:58:59 +0100 Subject: namespacing: \Shaarli\ApplicationUtils Signed-off-by: VirtualTam --- tests/ApplicationUtilsTest.php | 27 ++++----------------------- tests/utils/FakeApplicationUtils.php | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 23 deletions(-) create mode 100644 tests/utils/FakeApplicationUtils.php (limited to 'tests') diff --git a/tests/ApplicationUtilsTest.php b/tests/ApplicationUtilsTest.php index fe5f84ce..82f8804d 100644 --- a/tests/ApplicationUtilsTest.php +++ b/tests/ApplicationUtilsTest.php @@ -1,33 +1,14 @@ Date: Tue, 4 Dec 2018 00:02:17 +0100 Subject: namespacing: \Shaarli\Router Signed-off-by: VirtualTam --- tests/RouterTest.php | 9 ++------- tests/plugins/PluginAddlinkTest.php | 2 ++ tests/plugins/PluginPlayvideosTest.php | 2 ++ tests/plugins/PluginPubsubhubbubTest.php | 1 + tests/plugins/PluginQrcodeTest.php | 2 ++ 5 files changed, 9 insertions(+), 7 deletions(-) (limited to 'tests') diff --git a/tests/RouterTest.php b/tests/RouterTest.php index abf1bd5f..0cd49bb8 100644 --- a/tests/RouterTest.php +++ b/tests/RouterTest.php @@ -1,15 +1,10 @@ Date: Tue, 4 Dec 2018 00:13:42 +0100 Subject: namespacing: \Shaarli\Netscape\NetscapeBookmarkUtils Signed-off-by: VirtualTam --- tests/NetscapeBookmarkUtils/BookmarkExportTest.php | 136 ----- tests/NetscapeBookmarkUtils/BookmarkImportTest.php | 657 --------------------- tests/NetscapeBookmarkUtils/input/empty.htm | 0 .../input/internet_explorer_encoding.htm | 9 - .../input/lowercase_doctype.htm | 8 - .../NetscapeBookmarkUtils/input/netscape_basic.htm | 11 - .../input/netscape_nested.htm | 31 - tests/NetscapeBookmarkUtils/input/no_doctype.htm | 7 - tests/NetscapeBookmarkUtils/input/same_date.htm | 11 - tests/netscape/BookmarkExportTest.php | 137 +++++ tests/netscape/BookmarkImportTest.php | 657 +++++++++++++++++++++ tests/netscape/input/empty.htm | 0 .../netscape/input/internet_explorer_encoding.htm | 9 + tests/netscape/input/lowercase_doctype.htm | 8 + tests/netscape/input/netscape_basic.htm | 11 + tests/netscape/input/netscape_nested.htm | 31 + tests/netscape/input/no_doctype.htm | 7 + tests/netscape/input/same_date.htm | 11 + 18 files changed, 871 insertions(+), 870 deletions(-) delete mode 100644 tests/NetscapeBookmarkUtils/BookmarkExportTest.php delete mode 100644 tests/NetscapeBookmarkUtils/BookmarkImportTest.php delete mode 100644 tests/NetscapeBookmarkUtils/input/empty.htm delete mode 100644 tests/NetscapeBookmarkUtils/input/internet_explorer_encoding.htm delete mode 100644 tests/NetscapeBookmarkUtils/input/lowercase_doctype.htm delete mode 100644 tests/NetscapeBookmarkUtils/input/netscape_basic.htm delete mode 100644 tests/NetscapeBookmarkUtils/input/netscape_nested.htm delete mode 100644 tests/NetscapeBookmarkUtils/input/no_doctype.htm delete mode 100644 tests/NetscapeBookmarkUtils/input/same_date.htm create mode 100644 tests/netscape/BookmarkExportTest.php create mode 100644 tests/netscape/BookmarkImportTest.php create mode 100644 tests/netscape/input/empty.htm create mode 100644 tests/netscape/input/internet_explorer_encoding.htm create mode 100644 tests/netscape/input/lowercase_doctype.htm create mode 100644 tests/netscape/input/netscape_basic.htm create mode 100644 tests/netscape/input/netscape_nested.htm create mode 100644 tests/netscape/input/no_doctype.htm create mode 100644 tests/netscape/input/same_date.htm (limited to 'tests') diff --git a/tests/NetscapeBookmarkUtils/BookmarkExportTest.php b/tests/NetscapeBookmarkUtils/BookmarkExportTest.php deleted file mode 100644 index adf854c5..00000000 --- a/tests/NetscapeBookmarkUtils/BookmarkExportTest.php +++ /dev/null @@ -1,136 +0,0 @@ -write(self::$testDatastore); - self::$linkDb = new LinkDB(self::$testDatastore, true, false); - } - - /** - * Attempt to export an invalid link selection - * @expectedException Exception - * @expectedExceptionMessageRegExp /Invalid export selection/ - */ - public function testFilterAndFormatInvalid() - { - NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'derp', false, ''); - } - - /** - * Prepare all links for export - */ - public function testFilterAndFormatAll() - { - $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'all', false, ''); - $this->assertEquals(self::$refDb->countLinks(), sizeof($links)); - foreach ($links as $link) { - $date = $link['created']; - $this->assertEquals( - $date->getTimestamp(), - $link['timestamp'] - ); - $this->assertEquals( - str_replace(' ', ',', $link['tags']), - $link['taglist'] - ); - } - } - - /** - * Prepare private links for export - */ - public function testFilterAndFormatPrivate() - { - $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'private', false, ''); - $this->assertEquals(self::$refDb->countPrivateLinks(), sizeof($links)); - foreach ($links as $link) { - $date = $link['created']; - $this->assertEquals( - $date->getTimestamp(), - $link['timestamp'] - ); - $this->assertEquals( - str_replace(' ', ',', $link['tags']), - $link['taglist'] - ); - } - } - - /** - * Prepare public links for export - */ - public function testFilterAndFormatPublic() - { - $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'public', false, ''); - $this->assertEquals(self::$refDb->countPublicLinks(), sizeof($links)); - foreach ($links as $link) { - $date = $link['created']; - $this->assertEquals( - $date->getTimestamp(), - $link['timestamp'] - ); - $this->assertEquals( - str_replace(' ', ',', $link['tags']), - $link['taglist'] - ); - } - } - - /** - * Do not prepend notes with the Shaarli index's URL - */ - public function testFilterAndFormatDoNotPrependNoteUrl() - { - $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'public', false, ''); - $this->assertEquals( - '?WDWyig', - $links[2]['url'] - ); - } - - /** - * Prepend notes with the Shaarli index's URL - */ - public function testFilterAndFormatPrependNoteUrl() - { - $indexUrl = 'http://localhost:7469/shaarli/'; - $links = NetscapeBookmarkUtils::filterAndFormat( - self::$linkDb, - 'public', - true, - $indexUrl - ); - $this->assertEquals( - $indexUrl . '?WDWyig', - $links[2]['url'] - ); - } -} diff --git a/tests/NetscapeBookmarkUtils/BookmarkImportTest.php b/tests/NetscapeBookmarkUtils/BookmarkImportTest.php deleted file mode 100644 index 98c989bc..00000000 --- a/tests/NetscapeBookmarkUtils/BookmarkImportTest.php +++ /dev/null @@ -1,657 +0,0 @@ - array( - 'name' => $filename, - 'tmp_name' => __DIR__ . '/input/' . $filename, - 'size' => filesize(__DIR__ . '/input/' . $filename) - ) - ); -} - - -/** - * Netscape bookmark import - */ -class BookmarkImportTest extends PHPUnit_Framework_TestCase -{ - /** - * @var string datastore to test write operations - */ - protected static $testDatastore = 'sandbox/datastore.php'; - - /** - * @var string History file path - */ - protected static $historyFilePath = 'sandbox/history.php'; - - /** - * @var LinkDB private LinkDB instance - */ - protected $linkDb = null; - - /** - * @var string Dummy page cache - */ - protected $pagecache = 'tests'; - - /** - * @var ConfigManager instance. - */ - protected $conf; - - /** - * @var History instance. - */ - protected $history; - - /** - * @var string Save the current timezone. - */ - protected static $defaultTimeZone; - - public static function setUpBeforeClass() - { - self::$defaultTimeZone = date_default_timezone_get(); - // Timezone without DST for test consistency - date_default_timezone_set('Africa/Nairobi'); - } - - /** - * Resets test data before each test - */ - protected function setUp() - { - if (file_exists(self::$testDatastore)) { - unlink(self::$testDatastore); - } - // start with an empty datastore - file_put_contents(self::$testDatastore, ''); - $this->linkDb = new LinkDB(self::$testDatastore, true, false); - $this->conf = new ConfigManager('tests/utils/config/configJson'); - $this->conf->set('resource.page_cache', $this->pagecache); - $this->history = new History(self::$historyFilePath); - } - - /** - * Delete history file. - */ - public function tearDown() - { - @unlink(self::$historyFilePath); - } - - public static function tearDownAfterClass() - { - date_default_timezone_set(self::$defaultTimeZone); - } - - /** - * Attempt to import bookmarks from an empty file - */ - public function testImportEmptyData() - { - $files = file2array('empty.htm'); - $this->assertEquals( - 'File empty.htm (0 bytes) has an unknown file format.' - .' Nothing was imported.', - NetscapeBookmarkUtils::import(null, $files, null, $this->conf, $this->history) - ); - $this->assertEquals(0, count($this->linkDb)); - } - - /** - * Attempt to import bookmarks from a file with no Doctype - */ - public function testImportNoDoctype() - { - $files = file2array('no_doctype.htm'); - $this->assertEquals( - 'File no_doctype.htm (350 bytes) has an unknown file format. Nothing was imported.', - NetscapeBookmarkUtils::import(null, $files, null, $this->conf, $this->history) - ); - $this->assertEquals(0, count($this->linkDb)); - } - - /** - * Attempt to import bookmarks from a file with a lowercase Doctype - */ - public function testImportLowecaseDoctype() - { - $files = file2array('lowercase_doctype.htm'); - $this->assertStringMatchesFormat( - 'File lowercase_doctype.htm (386 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import(null, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - } - - - /** - * Ensure IE dumps are supported - */ - public function testImportInternetExplorerEncoding() - { - $files = file2array('internet_explorer_encoding.htm'); - $this->assertStringMatchesFormat( - 'File internet_explorer_encoding.htm (356 bytes) was successfully processed in %d seconds:' - .' 1 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(1, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - - $this->assertEquals( - array( - 'id' => 0, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160618_203944'), - 'title' => 'Hg Init a Mercurial tutorial by Joel Spolsky', - 'url' => 'http://hginit.com/', - 'description' => '', - 'private' => 0, - 'tags' => '', - 'shorturl' => 'La37cg', - ), - $this->linkDb->getLinkFromUrl('http://hginit.com/') - ); - } - - /** - * Import bookmarks nested in a folder hierarchy - */ - public function testImportNested() - { - $files = file2array('netscape_nested.htm'); - $this->assertStringMatchesFormat( - 'File netscape_nested.htm (1337 bytes) was successfully processed in %d seconds:' - .' 8 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(8, count($this->linkDb)); - $this->assertEquals(2, count_private($this->linkDb)); - - $this->assertEquals( - array( - 'id' => 0, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235541'), - 'title' => 'Nested 1', - 'url' => 'http://nest.ed/1', - 'description' => '', - 'private' => 0, - 'tags' => 'tag1 tag2', - 'shorturl' => 'KyDNKA', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/1') - ); - $this->assertEquals( - array( - 'id' => 1, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235542'), - 'title' => 'Nested 1-1', - 'url' => 'http://nest.ed/1-1', - 'description' => '', - 'private' => 0, - 'tags' => 'folder1 tag1 tag2', - 'shorturl' => 'T2LnXg', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/1-1') - ); - $this->assertEquals( - array( - 'id' => 2, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235547'), - 'title' => 'Nested 1-2', - 'url' => 'http://nest.ed/1-2', - 'description' => '', - 'private' => 0, - 'tags' => 'folder1 tag3 tag4', - 'shorturl' => '46SZxA', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/1-2') - ); - $this->assertEquals( - array( - 'id' => 3, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160202_202222'), - 'title' => 'Nested 2-1', - 'url' => 'http://nest.ed/2-1', - 'description' => 'First link of the second section', - 'private' => 1, - 'tags' => 'folder2', - 'shorturl' => '4UHOSw', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/2-1') - ); - $this->assertEquals( - array( - 'id' => 4, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160119_230227'), - 'title' => 'Nested 2-2', - 'url' => 'http://nest.ed/2-2', - 'description' => 'Second link of the second section', - 'private' => 1, - 'tags' => 'folder2', - 'shorturl' => 'yfzwbw', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/2-2') - ); - $this->assertEquals( - array( - 'id' => 5, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160202_202222'), - 'title' => 'Nested 3-1', - 'url' => 'http://nest.ed/3-1', - 'description' => '', - 'private' => 0, - 'tags' => 'folder3 folder3-1 tag3', - 'shorturl' => 'UwxIUQ', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/3-1') - ); - $this->assertEquals( - array( - 'id' => 6, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160119_230227'), - 'title' => 'Nested 3-2', - 'url' => 'http://nest.ed/3-2', - 'description' => '', - 'private' => 0, - 'tags' => 'folder3 folder3-1', - 'shorturl' => 'p8dyZg', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/3-2') - ); - $this->assertEquals( - array( - 'id' => 7, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160229_111541'), - 'title' => 'Nested 2', - 'url' => 'http://nest.ed/2', - 'description' => '', - 'private' => 0, - 'tags' => 'tag4', - 'shorturl' => 'Gt3Uug', - ), - $this->linkDb->getLinkFromUrl('http://nest.ed/2') - ); - } - - /** - * Import bookmarks with the default privacy setting (reuse from file) - * - * The $_POST array is not set. - */ - public function testImportDefaultPrivacyNoPost() - { - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history) - ); - - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(1, count_private($this->linkDb)); - - $this->assertEquals( - array( - 'id' => 0, - // Old link - UTC+4 (note that TZ in the import file is ignored). - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20001010_135536'), - 'title' => 'Secret stuff', - 'url' => 'https://private.tld', - 'description' => "Super-secret stuff you're not supposed to know about", - 'private' => 1, - 'tags' => 'private secret', - 'shorturl' => 'EokDtA', - ), - $this->linkDb->getLinkFromUrl('https://private.tld') - ); - $this->assertEquals( - array( - 'id' => 1, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235548'), - 'title' => 'Public stuff', - 'url' => 'http://public.tld', - 'description' => '', - 'private' => 0, - 'tags' => 'public hello world', - 'shorturl' => 'Er9ddA', - ), - $this->linkDb->getLinkFromUrl('http://public.tld') - ); - } - - /** - * Import bookmarks with the default privacy setting (reuse from file) - */ - public function testImportKeepPrivacy() - { - $post = array('privacy' => 'default'); - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(1, count_private($this->linkDb)); - - $this->assertEquals( - array( - 'id' => 0, - // Note that TZ in the import file is ignored. - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20001010_135536'), - 'title' => 'Secret stuff', - 'url' => 'https://private.tld', - 'description' => "Super-secret stuff you're not supposed to know about", - 'private' => 1, - 'tags' => 'private secret', - 'shorturl' => 'EokDtA', - ), - $this->linkDb->getLinkFromUrl('https://private.tld') - ); - $this->assertEquals( - array( - 'id' => 1, - 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235548'), - 'title' => 'Public stuff', - 'url' => 'http://public.tld', - 'description' => '', - 'private' => 0, - 'tags' => 'public hello world', - 'shorturl' => 'Er9ddA', - ), - $this->linkDb->getLinkFromUrl('http://public.tld') - ); - } - - /** - * Import links as public - */ - public function testImportAsPublic() - { - $post = array('privacy' => 'public'); - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - $this->assertEquals( - 0, - $this->linkDb[0]['private'] - ); - $this->assertEquals( - 0, - $this->linkDb[1]['private'] - ); - } - - /** - * Import links as private - */ - public function testImportAsPrivate() - { - $post = array('privacy' => 'private'); - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(2, count_private($this->linkDb)); - $this->assertEquals( - 1, - $this->linkDb['0']['private'] - ); - $this->assertEquals( - 1, - $this->linkDb['1']['private'] - ); - } - - /** - * Overwrite private links so they become public - */ - public function testOverwriteAsPublic() - { - $files = file2array('netscape_basic.htm'); - - // import links as private - $post = array('privacy' => 'private'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(2, count_private($this->linkDb)); - $this->assertEquals( - 1, - $this->linkDb[0]['private'] - ); - $this->assertEquals( - 1, - $this->linkDb[1]['private'] - ); - // re-import as public, enable overwriting - $post = array( - 'privacy' => 'public', - 'overwrite' => 'true' - ); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 2 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - $this->assertEquals( - 0, - $this->linkDb[0]['private'] - ); - $this->assertEquals( - 0, - $this->linkDb[1]['private'] - ); - } - - /** - * Overwrite public links so they become private - */ - public function testOverwriteAsPrivate() - { - $files = file2array('netscape_basic.htm'); - - // import links as public - $post = array('privacy' => 'public'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - $this->assertEquals( - 0, - $this->linkDb['0']['private'] - ); - $this->assertEquals( - 0, - $this->linkDb['1']['private'] - ); - - // re-import as private, enable overwriting - $post = array( - 'privacy' => 'private', - 'overwrite' => 'true' - ); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 2 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(2, count_private($this->linkDb)); - $this->assertEquals( - 1, - $this->linkDb['0']['private'] - ); - $this->assertEquals( - 1, - $this->linkDb['1']['private'] - ); - } - - /** - * Attept to import the same links twice without enabling overwriting - */ - public function testSkipOverwrite() - { - $post = array('privacy' => 'public'); - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - - // re-import as private, DO NOT enable overwriting - $post = array('privacy' => 'private'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 0 links imported, 0 links overwritten, 2 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - } - - /** - * Add user-specified tags to all imported bookmarks - */ - public function testSetDefaultTags() - { - $post = array( - 'privacy' => 'public', - 'default_tags' => 'tag1,tag2 tag3' - ); - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - $this->assertEquals( - 'tag1 tag2 tag3 private secret', - $this->linkDb['0']['tags'] - ); - $this->assertEquals( - 'tag1 tag2 tag3 public hello world', - $this->linkDb['1']['tags'] - ); - } - - /** - * The user-specified tags contain characters to be escaped - */ - public function testSanitizeDefaultTags() - { - $post = array( - 'privacy' => 'public', - 'default_tags' => 'tag1&,tag2 "tag3"' - ); - $files = file2array('netscape_basic.htm'); - $this->assertStringMatchesFormat( - 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' - .' 2 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(2, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - $this->assertEquals( - 'tag1& tag2 "tag3" private secret', - $this->linkDb['0']['tags'] - ); - $this->assertEquals( - 'tag1& tag2 "tag3" public hello world', - $this->linkDb['1']['tags'] - ); - } - - /** - * Ensure each imported bookmark has a unique id - * - * See https://github.com/shaarli/Shaarli/issues/351 - */ - public function testImportSameDate() - { - $files = file2array('same_date.htm'); - $this->assertStringMatchesFormat( - 'File same_date.htm (453 bytes) was successfully processed in %d seconds:' - .' 3 links imported, 0 links overwritten, 0 links skipped.', - NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf, $this->history) - ); - $this->assertEquals(3, count($this->linkDb)); - $this->assertEquals(0, count_private($this->linkDb)); - $this->assertEquals( - 0, - $this->linkDb[0]['id'] - ); - $this->assertEquals( - 1, - $this->linkDb[1]['id'] - ); - $this->assertEquals( - 2, - $this->linkDb[2]['id'] - ); - } - - public function testImportCreateUpdateHistory() - { - $post = [ - 'privacy' => 'public', - 'overwrite' => 'true', - ]; - $files = file2array('netscape_basic.htm'); - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history); - $history = $this->history->getHistory(); - $this->assertEquals(1, count($history)); - $this->assertEquals(History::IMPORT, $history[0]['event']); - $this->assertTrue(new DateTime('-5 seconds') < $history[0]['datetime']); - - // re-import as private, enable overwriting - NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history); - $history = $this->history->getHistory(); - $this->assertEquals(2, count($history)); - $this->assertEquals(History::IMPORT, $history[0]['event']); - $this->assertTrue(new DateTime('-5 seconds') < $history[0]['datetime']); - $this->assertEquals(History::IMPORT, $history[1]['event']); - $this->assertTrue(new DateTime('-5 seconds') < $history[1]['datetime']); - } -} diff --git a/tests/NetscapeBookmarkUtils/input/empty.htm b/tests/NetscapeBookmarkUtils/input/empty.htm deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/NetscapeBookmarkUtils/input/internet_explorer_encoding.htm b/tests/NetscapeBookmarkUtils/input/internet_explorer_encoding.htm deleted file mode 100644 index 18703cf6..00000000 --- a/tests/NetscapeBookmarkUtils/input/internet_explorer_encoding.htm +++ /dev/null @@ -1,9 +0,0 @@ - - -Bookmarks -

Bookmarks

-

-

Hg Init a Mercurial tutorial by Joel Spolsky -

diff --git a/tests/NetscapeBookmarkUtils/input/lowercase_doctype.htm b/tests/NetscapeBookmarkUtils/input/lowercase_doctype.htm deleted file mode 100644 index 8911ad19..00000000 --- a/tests/NetscapeBookmarkUtils/input/lowercase_doctype.htm +++ /dev/null @@ -1,8 +0,0 @@ - -Bookmarks -

Bookmarks

-

-

Secret stuff -
Super-secret stuff you're not supposed to know about -
Public stuff -

diff --git a/tests/NetscapeBookmarkUtils/input/netscape_basic.htm b/tests/NetscapeBookmarkUtils/input/netscape_basic.htm deleted file mode 100644 index affe0cf8..00000000 --- a/tests/NetscapeBookmarkUtils/input/netscape_basic.htm +++ /dev/null @@ -1,11 +0,0 @@ - - -Bookmarks -

Bookmarks

-

-

Secret stuff -
Super-secret stuff you're not supposed to know about -
Public stuff -

diff --git a/tests/NetscapeBookmarkUtils/input/netscape_nested.htm b/tests/NetscapeBookmarkUtils/input/netscape_nested.htm deleted file mode 100644 index b486fe18..00000000 --- a/tests/NetscapeBookmarkUtils/input/netscape_nested.htm +++ /dev/null @@ -1,31 +0,0 @@ - - -Bookmarks -

Bookmarks

-

-

Nested 1 -

Folder1

-

-

Nested 1-1 -
Nested 1-2 -

-

Folder2

-
This second folder contains wonderful links! -

-

Nested 2-1 -
First link of the second section -
Nested 2-2 -
Second link of the second section -

-

Folder3

-

-

Folder3-1

-

-

Nested 3-1 -
Nested 3-2 -

-

-

Nested 2 -

diff --git a/tests/NetscapeBookmarkUtils/input/no_doctype.htm b/tests/NetscapeBookmarkUtils/input/no_doctype.htm deleted file mode 100644 index 766d398b..00000000 --- a/tests/NetscapeBookmarkUtils/input/no_doctype.htm +++ /dev/null @@ -1,7 +0,0 @@ -Bookmarks -

Bookmarks

-

-

Secret stuff -
Super-secret stuff you're not supposed to know about -
Public stuff -

diff --git a/tests/NetscapeBookmarkUtils/input/same_date.htm b/tests/NetscapeBookmarkUtils/input/same_date.htm deleted file mode 100644 index 9d58a582..00000000 --- a/tests/NetscapeBookmarkUtils/input/same_date.htm +++ /dev/null @@ -1,11 +0,0 @@ - - -Bookmarks -

Bookmarks

-

-

Today's first link -
Today's second link -
Today's third link -

diff --git a/tests/netscape/BookmarkExportTest.php b/tests/netscape/BookmarkExportTest.php new file mode 100644 index 00000000..6de9876d --- /dev/null +++ b/tests/netscape/BookmarkExportTest.php @@ -0,0 +1,137 @@ +write(self::$testDatastore); + self::$linkDb = new LinkDB(self::$testDatastore, true, false); + } + + /** + * Attempt to export an invalid link selection + * @expectedException Exception + * @expectedExceptionMessageRegExp /Invalid export selection/ + */ + public function testFilterAndFormatInvalid() + { + NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'derp', false, ''); + } + + /** + * Prepare all links for export + */ + public function testFilterAndFormatAll() + { + $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'all', false, ''); + $this->assertEquals(self::$refDb->countLinks(), sizeof($links)); + foreach ($links as $link) { + $date = $link['created']; + $this->assertEquals( + $date->getTimestamp(), + $link['timestamp'] + ); + $this->assertEquals( + str_replace(' ', ',', $link['tags']), + $link['taglist'] + ); + } + } + + /** + * Prepare private links for export + */ + public function testFilterAndFormatPrivate() + { + $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'private', false, ''); + $this->assertEquals(self::$refDb->countPrivateLinks(), sizeof($links)); + foreach ($links as $link) { + $date = $link['created']; + $this->assertEquals( + $date->getTimestamp(), + $link['timestamp'] + ); + $this->assertEquals( + str_replace(' ', ',', $link['tags']), + $link['taglist'] + ); + } + } + + /** + * Prepare public links for export + */ + public function testFilterAndFormatPublic() + { + $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'public', false, ''); + $this->assertEquals(self::$refDb->countPublicLinks(), sizeof($links)); + foreach ($links as $link) { + $date = $link['created']; + $this->assertEquals( + $date->getTimestamp(), + $link['timestamp'] + ); + $this->assertEquals( + str_replace(' ', ',', $link['tags']), + $link['taglist'] + ); + } + } + + /** + * Do not prepend notes with the Shaarli index's URL + */ + public function testFilterAndFormatDoNotPrependNoteUrl() + { + $links = NetscapeBookmarkUtils::filterAndFormat(self::$linkDb, 'public', false, ''); + $this->assertEquals( + '?WDWyig', + $links[2]['url'] + ); + } + + /** + * Prepend notes with the Shaarli index's URL + */ + public function testFilterAndFormatPrependNoteUrl() + { + $indexUrl = 'http://localhost:7469/shaarli/'; + $links = NetscapeBookmarkUtils::filterAndFormat( + self::$linkDb, + 'public', + true, + $indexUrl + ); + $this->assertEquals( + $indexUrl . '?WDWyig', + $links[2]['url'] + ); + } +} diff --git a/tests/netscape/BookmarkImportTest.php b/tests/netscape/BookmarkImportTest.php new file mode 100644 index 00000000..ccafc161 --- /dev/null +++ b/tests/netscape/BookmarkImportTest.php @@ -0,0 +1,657 @@ + array( + 'name' => $filename, + 'tmp_name' => __DIR__ . '/input/' . $filename, + 'size' => filesize(__DIR__ . '/input/' . $filename) + ) + ); +} + + +/** + * Netscape bookmark import + */ +class BookmarkImportTest extends \PHPUnit\Framework\TestCase +{ + /** + * @var string datastore to test write operations + */ + protected static $testDatastore = 'sandbox/datastore.php'; + + /** + * @var string History file path + */ + protected static $historyFilePath = 'sandbox/history.php'; + + /** + * @var LinkDB private LinkDB instance + */ + protected $linkDb = null; + + /** + * @var string Dummy page cache + */ + protected $pagecache = 'tests'; + + /** + * @var ConfigManager instance. + */ + protected $conf; + + /** + * @var History instance. + */ + protected $history; + + /** + * @var string Save the current timezone. + */ + protected static $defaultTimeZone; + + public static function setUpBeforeClass() + { + self::$defaultTimeZone = date_default_timezone_get(); + // Timezone without DST for test consistency + date_default_timezone_set('Africa/Nairobi'); + } + + /** + * Resets test data before each test + */ + protected function setUp() + { + if (file_exists(self::$testDatastore)) { + unlink(self::$testDatastore); + } + // start with an empty datastore + file_put_contents(self::$testDatastore, ''); + $this->linkDb = new LinkDB(self::$testDatastore, true, false); + $this->conf = new ConfigManager('tests/utils/config/configJson'); + $this->conf->set('resource.page_cache', $this->pagecache); + $this->history = new History(self::$historyFilePath); + } + + /** + * Delete history file. + */ + public function tearDown() + { + @unlink(self::$historyFilePath); + } + + public static function tearDownAfterClass() + { + date_default_timezone_set(self::$defaultTimeZone); + } + + /** + * Attempt to import bookmarks from an empty file + */ + public function testImportEmptyData() + { + $files = file2array('empty.htm'); + $this->assertEquals( + 'File empty.htm (0 bytes) has an unknown file format.' + .' Nothing was imported.', + NetscapeBookmarkUtils::import(null, $files, null, $this->conf, $this->history) + ); + $this->assertEquals(0, count($this->linkDb)); + } + + /** + * Attempt to import bookmarks from a file with no Doctype + */ + public function testImportNoDoctype() + { + $files = file2array('no_doctype.htm'); + $this->assertEquals( + 'File no_doctype.htm (350 bytes) has an unknown file format. Nothing was imported.', + NetscapeBookmarkUtils::import(null, $files, null, $this->conf, $this->history) + ); + $this->assertEquals(0, count($this->linkDb)); + } + + /** + * Attempt to import bookmarks from a file with a lowercase Doctype + */ + public function testImportLowecaseDoctype() + { + $files = file2array('lowercase_doctype.htm'); + $this->assertStringMatchesFormat( + 'File lowercase_doctype.htm (386 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import(null, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + } + + + /** + * Ensure IE dumps are supported + */ + public function testImportInternetExplorerEncoding() + { + $files = file2array('internet_explorer_encoding.htm'); + $this->assertStringMatchesFormat( + 'File internet_explorer_encoding.htm (356 bytes) was successfully processed in %d seconds:' + .' 1 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(1, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + + $this->assertEquals( + array( + 'id' => 0, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160618_203944'), + 'title' => 'Hg Init a Mercurial tutorial by Joel Spolsky', + 'url' => 'http://hginit.com/', + 'description' => '', + 'private' => 0, + 'tags' => '', + 'shorturl' => 'La37cg', + ), + $this->linkDb->getLinkFromUrl('http://hginit.com/') + ); + } + + /** + * Import bookmarks nested in a folder hierarchy + */ + public function testImportNested() + { + $files = file2array('netscape_nested.htm'); + $this->assertStringMatchesFormat( + 'File netscape_nested.htm (1337 bytes) was successfully processed in %d seconds:' + .' 8 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(8, count($this->linkDb)); + $this->assertEquals(2, count_private($this->linkDb)); + + $this->assertEquals( + array( + 'id' => 0, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235541'), + 'title' => 'Nested 1', + 'url' => 'http://nest.ed/1', + 'description' => '', + 'private' => 0, + 'tags' => 'tag1 tag2', + 'shorturl' => 'KyDNKA', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/1') + ); + $this->assertEquals( + array( + 'id' => 1, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235542'), + 'title' => 'Nested 1-1', + 'url' => 'http://nest.ed/1-1', + 'description' => '', + 'private' => 0, + 'tags' => 'folder1 tag1 tag2', + 'shorturl' => 'T2LnXg', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/1-1') + ); + $this->assertEquals( + array( + 'id' => 2, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235547'), + 'title' => 'Nested 1-2', + 'url' => 'http://nest.ed/1-2', + 'description' => '', + 'private' => 0, + 'tags' => 'folder1 tag3 tag4', + 'shorturl' => '46SZxA', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/1-2') + ); + $this->assertEquals( + array( + 'id' => 3, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160202_202222'), + 'title' => 'Nested 2-1', + 'url' => 'http://nest.ed/2-1', + 'description' => 'First link of the second section', + 'private' => 1, + 'tags' => 'folder2', + 'shorturl' => '4UHOSw', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/2-1') + ); + $this->assertEquals( + array( + 'id' => 4, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160119_230227'), + 'title' => 'Nested 2-2', + 'url' => 'http://nest.ed/2-2', + 'description' => 'Second link of the second section', + 'private' => 1, + 'tags' => 'folder2', + 'shorturl' => 'yfzwbw', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/2-2') + ); + $this->assertEquals( + array( + 'id' => 5, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160202_202222'), + 'title' => 'Nested 3-1', + 'url' => 'http://nest.ed/3-1', + 'description' => '', + 'private' => 0, + 'tags' => 'folder3 folder3-1 tag3', + 'shorturl' => 'UwxIUQ', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/3-1') + ); + $this->assertEquals( + array( + 'id' => 6, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160119_230227'), + 'title' => 'Nested 3-2', + 'url' => 'http://nest.ed/3-2', + 'description' => '', + 'private' => 0, + 'tags' => 'folder3 folder3-1', + 'shorturl' => 'p8dyZg', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/3-2') + ); + $this->assertEquals( + array( + 'id' => 7, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160229_111541'), + 'title' => 'Nested 2', + 'url' => 'http://nest.ed/2', + 'description' => '', + 'private' => 0, + 'tags' => 'tag4', + 'shorturl' => 'Gt3Uug', + ), + $this->linkDb->getLinkFromUrl('http://nest.ed/2') + ); + } + + /** + * Import bookmarks with the default privacy setting (reuse from file) + * + * The $_POST array is not set. + */ + public function testImportDefaultPrivacyNoPost() + { + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import([], $files, $this->linkDb, $this->conf, $this->history) + ); + + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(1, count_private($this->linkDb)); + + $this->assertEquals( + array( + 'id' => 0, + // Old link - UTC+4 (note that TZ in the import file is ignored). + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20001010_135536'), + 'title' => 'Secret stuff', + 'url' => 'https://private.tld', + 'description' => "Super-secret stuff you're not supposed to know about", + 'private' => 1, + 'tags' => 'private secret', + 'shorturl' => 'EokDtA', + ), + $this->linkDb->getLinkFromUrl('https://private.tld') + ); + $this->assertEquals( + array( + 'id' => 1, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235548'), + 'title' => 'Public stuff', + 'url' => 'http://public.tld', + 'description' => '', + 'private' => 0, + 'tags' => 'public hello world', + 'shorturl' => 'Er9ddA', + ), + $this->linkDb->getLinkFromUrl('http://public.tld') + ); + } + + /** + * Import bookmarks with the default privacy setting (reuse from file) + */ + public function testImportKeepPrivacy() + { + $post = array('privacy' => 'default'); + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(1, count_private($this->linkDb)); + + $this->assertEquals( + array( + 'id' => 0, + // Note that TZ in the import file is ignored. + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20001010_135536'), + 'title' => 'Secret stuff', + 'url' => 'https://private.tld', + 'description' => "Super-secret stuff you're not supposed to know about", + 'private' => 1, + 'tags' => 'private secret', + 'shorturl' => 'EokDtA', + ), + $this->linkDb->getLinkFromUrl('https://private.tld') + ); + $this->assertEquals( + array( + 'id' => 1, + 'created' => DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160225_235548'), + 'title' => 'Public stuff', + 'url' => 'http://public.tld', + 'description' => '', + 'private' => 0, + 'tags' => 'public hello world', + 'shorturl' => 'Er9ddA', + ), + $this->linkDb->getLinkFromUrl('http://public.tld') + ); + } + + /** + * Import links as public + */ + public function testImportAsPublic() + { + $post = array('privacy' => 'public'); + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + $this->assertEquals( + 0, + $this->linkDb[0]['private'] + ); + $this->assertEquals( + 0, + $this->linkDb[1]['private'] + ); + } + + /** + * Import links as private + */ + public function testImportAsPrivate() + { + $post = array('privacy' => 'private'); + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(2, count_private($this->linkDb)); + $this->assertEquals( + 1, + $this->linkDb['0']['private'] + ); + $this->assertEquals( + 1, + $this->linkDb['1']['private'] + ); + } + + /** + * Overwrite private links so they become public + */ + public function testOverwriteAsPublic() + { + $files = file2array('netscape_basic.htm'); + + // import links as private + $post = array('privacy' => 'private'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(2, count_private($this->linkDb)); + $this->assertEquals( + 1, + $this->linkDb[0]['private'] + ); + $this->assertEquals( + 1, + $this->linkDb[1]['private'] + ); + // re-import as public, enable overwriting + $post = array( + 'privacy' => 'public', + 'overwrite' => 'true' + ); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 2 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + $this->assertEquals( + 0, + $this->linkDb[0]['private'] + ); + $this->assertEquals( + 0, + $this->linkDb[1]['private'] + ); + } + + /** + * Overwrite public links so they become private + */ + public function testOverwriteAsPrivate() + { + $files = file2array('netscape_basic.htm'); + + // import links as public + $post = array('privacy' => 'public'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + $this->assertEquals( + 0, + $this->linkDb['0']['private'] + ); + $this->assertEquals( + 0, + $this->linkDb['1']['private'] + ); + + // re-import as private, enable overwriting + $post = array( + 'privacy' => 'private', + 'overwrite' => 'true' + ); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 2 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(2, count_private($this->linkDb)); + $this->assertEquals( + 1, + $this->linkDb['0']['private'] + ); + $this->assertEquals( + 1, + $this->linkDb['1']['private'] + ); + } + + /** + * Attept to import the same links twice without enabling overwriting + */ + public function testSkipOverwrite() + { + $post = array('privacy' => 'public'); + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + + // re-import as private, DO NOT enable overwriting + $post = array('privacy' => 'private'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 0 links imported, 0 links overwritten, 2 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + } + + /** + * Add user-specified tags to all imported bookmarks + */ + public function testSetDefaultTags() + { + $post = array( + 'privacy' => 'public', + 'default_tags' => 'tag1,tag2 tag3' + ); + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + $this->assertEquals( + 'tag1 tag2 tag3 private secret', + $this->linkDb['0']['tags'] + ); + $this->assertEquals( + 'tag1 tag2 tag3 public hello world', + $this->linkDb['1']['tags'] + ); + } + + /** + * The user-specified tags contain characters to be escaped + */ + public function testSanitizeDefaultTags() + { + $post = array( + 'privacy' => 'public', + 'default_tags' => 'tag1&,tag2 "tag3"' + ); + $files = file2array('netscape_basic.htm'); + $this->assertStringMatchesFormat( + 'File netscape_basic.htm (482 bytes) was successfully processed in %d seconds:' + .' 2 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(2, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + $this->assertEquals( + 'tag1& tag2 "tag3" private secret', + $this->linkDb['0']['tags'] + ); + $this->assertEquals( + 'tag1& tag2 "tag3" public hello world', + $this->linkDb['1']['tags'] + ); + } + + /** + * Ensure each imported bookmark has a unique id + * + * See https://github.com/shaarli/Shaarli/issues/351 + */ + public function testImportSameDate() + { + $files = file2array('same_date.htm'); + $this->assertStringMatchesFormat( + 'File same_date.htm (453 bytes) was successfully processed in %d seconds:' + .' 3 links imported, 0 links overwritten, 0 links skipped.', + NetscapeBookmarkUtils::import(array(), $files, $this->linkDb, $this->conf, $this->history) + ); + $this->assertEquals(3, count($this->linkDb)); + $this->assertEquals(0, count_private($this->linkDb)); + $this->assertEquals( + 0, + $this->linkDb[0]['id'] + ); + $this->assertEquals( + 1, + $this->linkDb[1]['id'] + ); + $this->assertEquals( + 2, + $this->linkDb[2]['id'] + ); + } + + public function testImportCreateUpdateHistory() + { + $post = [ + 'privacy' => 'public', + 'overwrite' => 'true', + ]; + $files = file2array('netscape_basic.htm'); + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history); + $history = $this->history->getHistory(); + $this->assertEquals(1, count($history)); + $this->assertEquals(History::IMPORT, $history[0]['event']); + $this->assertTrue(new DateTime('-5 seconds') < $history[0]['datetime']); + + // re-import as private, enable overwriting + NetscapeBookmarkUtils::import($post, $files, $this->linkDb, $this->conf, $this->history); + $history = $this->history->getHistory(); + $this->assertEquals(2, count($history)); + $this->assertEquals(History::IMPORT, $history[0]['event']); + $this->assertTrue(new DateTime('-5 seconds') < $history[0]['datetime']); + $this->assertEquals(History::IMPORT, $history[1]['event']); + $this->assertTrue(new DateTime('-5 seconds') < $history[1]['datetime']); + } +} diff --git a/tests/netscape/input/empty.htm b/tests/netscape/input/empty.htm new file mode 100644 index 00000000..e69de29b diff --git a/tests/netscape/input/internet_explorer_encoding.htm b/tests/netscape/input/internet_explorer_encoding.htm new file mode 100644 index 00000000..18703cf6 --- /dev/null +++ b/tests/netscape/input/internet_explorer_encoding.htm @@ -0,0 +1,9 @@ + + +Bookmarks +

Bookmarks

+

+

Hg Init a Mercurial tutorial by Joel Spolsky +

diff --git a/tests/netscape/input/lowercase_doctype.htm b/tests/netscape/input/lowercase_doctype.htm new file mode 100644 index 00000000..8911ad19 --- /dev/null +++ b/tests/netscape/input/lowercase_doctype.htm @@ -0,0 +1,8 @@ + +Bookmarks +

Bookmarks

+

+

Secret stuff +
Super-secret stuff you're not supposed to know about +
Public stuff +

diff --git a/tests/netscape/input/netscape_basic.htm b/tests/netscape/input/netscape_basic.htm new file mode 100644 index 00000000..affe0cf8 --- /dev/null +++ b/tests/netscape/input/netscape_basic.htm @@ -0,0 +1,11 @@ + + +Bookmarks +

Bookmarks

+

+

Secret stuff +
Super-secret stuff you're not supposed to know about +
Public stuff +

diff --git a/tests/netscape/input/netscape_nested.htm b/tests/netscape/input/netscape_nested.htm new file mode 100644 index 00000000..b486fe18 --- /dev/null +++ b/tests/netscape/input/netscape_nested.htm @@ -0,0 +1,31 @@ + + +Bookmarks +

Bookmarks

+

+

Nested 1 +

Folder1

+

+

Nested 1-1 +
Nested 1-2 +

+

Folder2

+
This second folder contains wonderful links! +

+

Nested 2-1 +
First link of the second section +
Nested 2-2 +
Second link of the second section +

+

Folder3

+

+

Folder3-1

+

+

Nested 3-1 +
Nested 3-2 +

+

+

Nested 2 +

diff --git a/tests/netscape/input/no_doctype.htm b/tests/netscape/input/no_doctype.htm new file mode 100644 index 00000000..766d398b --- /dev/null +++ b/tests/netscape/input/no_doctype.htm @@ -0,0 +1,7 @@ +Bookmarks +

Bookmarks

+

+

Secret stuff +
Super-secret stuff you're not supposed to know about +
Public stuff +

diff --git a/tests/netscape/input/same_date.htm b/tests/netscape/input/same_date.htm new file mode 100644 index 00000000..9d58a582 --- /dev/null +++ b/tests/netscape/input/same_date.htm @@ -0,0 +1,11 @@ + + +Bookmarks +

Bookmarks

+

+

Today's first link +
Today's second link +
Today's third link +

-- cgit v1.2.3 From e1850388348d4bfdf463a5aa341bc470da79cf32 Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Tue, 4 Dec 2018 00:26:50 +0100 Subject: namespacing: \Shaarli\Plugin\PluginManager Signed-off-by: VirtualTam --- tests/PluginManagerTest.php | 10 +++------- tests/plugins/PluginAddlinkTest.php | 9 ++------- tests/plugins/PluginArchiveorgTest.php | 2 ++ tests/plugins/PluginIssoTest.php | 1 + tests/plugins/PluginMarkdownTest.php | 1 + tests/plugins/PluginPlayvideosTest.php | 1 + tests/plugins/PluginPubsubhubbubTest.php | 1 + tests/plugins/PluginQrcodeTest.php | 1 + tests/plugins/PluginWallabagTest.php | 3 ++- 9 files changed, 14 insertions(+), 15 deletions(-) (limited to 'tests') diff --git a/tests/PluginManagerTest.php b/tests/PluginManagerTest.php index 01de959c..71761ac1 100644 --- a/tests/PluginManagerTest.php +++ b/tests/PluginManagerTest.php @@ -1,16 +1,12 @@ Date: Tue, 4 Dec 2018 23:17:23 +0100 Subject: namespacing: add plugin tests to \Shaarli\Plugin\[...] Signed-off-by: VirtualTam --- tests/plugins/PluginAddlinkTest.php | 1 + tests/plugins/PluginArchiveorgTest.php | 3 ++- tests/plugins/PluginIssoTest.php | 4 +++- tests/plugins/PluginMarkdownTest.php | 4 +++- tests/plugins/PluginPlayvideosTest.php | 4 ++-- tests/plugins/PluginPubsubhubbubTest.php | 5 +++-- tests/plugins/PluginQrcodeTest.php | 5 +++-- tests/plugins/PluginWallabagTest.php | 6 ++---- tests/plugins/WallabagInstanceTest.php | 5 +++-- 9 files changed, 22 insertions(+), 15 deletions(-) (limited to 'tests') diff --git a/tests/plugins/PluginAddlinkTest.php b/tests/plugins/PluginAddlinkTest.php index e0a0107d..d052f8b9 100644 --- a/tests/plugins/PluginAddlinkTest.php +++ b/tests/plugins/PluginAddlinkTest.php @@ -1,4 +1,5 @@ Date: Sat, 12 Jan 2019 23:19:15 +0100 Subject: API: update test regexes to comply with PCRE2 Signed-off-by: VirtualTam --- tests/api/controllers/links/PostLinkTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/api/controllers/links/PostLinkTest.php b/tests/api/controllers/links/PostLinkTest.php index ade07eeb..24e591db 100644 --- a/tests/api/controllers/links/PostLinkTest.php +++ b/tests/api/controllers/links/PostLinkTest.php @@ -121,7 +121,7 @@ class PostLinkTest extends TestCase $data = json_decode((string) $response->getBody(), true); $this->assertEquals(self::NB_FIELDS_LINK, count($data)); $this->assertEquals(43, $data['id']); - $this->assertRegExp('/[\w-_]{6}/', $data['shorturl']); + $this->assertRegExp('/[\w_-]{6}/', $data['shorturl']); $this->assertEquals('http://domain.tld/?' . $data['shorturl'], $data['url']); $this->assertEquals('?' . $data['shorturl'], $data['title']); $this->assertEquals('', $data['description']); @@ -166,7 +166,7 @@ class PostLinkTest extends TestCase $data = json_decode((string) $response->getBody(), true); $this->assertEquals(self::NB_FIELDS_LINK, count($data)); $this->assertEquals(43, $data['id']); - $this->assertRegExp('/[\w-_]{6}/', $data['shorturl']); + $this->assertRegExp('/[\w_-]{6}/', $data['shorturl']); $this->assertEquals('http://' . $link['url'], $data['url']); $this->assertEquals($link['title'], $data['title']); $this->assertEquals($link['description'], $data['description']); -- cgit v1.2.3 From dea72c711ff740b3b829d238fcf85648465143a0 Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Sat, 12 Jan 2019 23:55:38 +0100 Subject: Optimize and cleanup imports Signed-off-by: VirtualTam --- tests/LanguagesTest.php | 2 +- tests/TimeZoneTest.php | 2 +- tests/UtilsTest.php | 2 +- tests/api/ApiMiddlewareTest.php | 3 +-- tests/api/ApiUtilsTest.php | 2 +- tests/api/controllers/history/HistoryTest.php | 28 +++++++++++++------------- tests/api/controllers/info/InfoTest.php | 3 +-- tests/api/controllers/links/DeleteLinkTest.php | 18 +++++++++-------- tests/api/controllers/links/GetLinkIdTest.php | 3 +-- tests/api/controllers/links/GetLinksTest.php | 10 ++++----- tests/api/controllers/links/PostLinkTest.php | 9 +++++---- tests/api/controllers/links/PutLinkTest.php | 11 +++++----- tests/api/controllers/tags/DeleteTagTest.php | 22 +++++++++++--------- tests/api/controllers/tags/GetTagNameTest.php | 6 +++--- tests/api/controllers/tags/GetTagsTest.php | 8 ++++---- tests/api/controllers/tags/PutTagTest.php | 17 ++++++++-------- tests/bookmark/LinkDBTest.php | 1 - tests/config/ConfigJsonTest.php | 2 +- tests/config/ConfigManagerTest.php | 2 +- tests/config/ConfigPhpTest.php | 2 +- tests/config/ConfigPluginTest.php | 2 +- tests/feed/FeedBuilderTest.php | 2 +- tests/languages/fr/LanguagesFrTest.php | 2 +- tests/plugins/WallabagInstanceTest.php | 2 -- tests/render/ThemeUtilsTest.php | 2 +- tests/security/LoginManagerTest.php | 3 ++- tests/security/SessionManagerTest.php | 4 ++-- 27 files changed, 86 insertions(+), 84 deletions(-) (limited to 'tests') diff --git a/tests/LanguagesTest.php b/tests/LanguagesTest.php index 4951e09a..de83f291 100644 --- a/tests/LanguagesTest.php +++ b/tests/LanguagesTest.php @@ -7,7 +7,7 @@ use Shaarli\Config\ConfigManager; /** * Class LanguagesTest. */ -class LanguagesTest extends \PHPUnit_Framework_TestCase +class LanguagesTest extends \PHPUnit\Framework\TestCase { /** * @var string Config file path (without extension). diff --git a/tests/TimeZoneTest.php b/tests/TimeZoneTest.php index 127fdc19..02bf060f 100644 --- a/tests/TimeZoneTest.php +++ b/tests/TimeZoneTest.php @@ -8,7 +8,7 @@ require_once 'application/TimeZone.php'; /** * Unitary tests for timezone utilities */ -class TimeZoneTest extends PHPUnit_Framework_TestCase +class TimeZoneTest extends PHPUnit\Framework\TestCase { /** * @var array of timezones diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index d0abd996..8225d95a 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -10,7 +10,7 @@ require_once 'application/Languages.php'; /** * Unitary tests for Shaarli utilities */ -class UtilsTest extends PHPUnit_Framework_TestCase +class UtilsTest extends PHPUnit\Framework\TestCase { // Log file protected static $testLogFile = 'tests.log'; diff --git a/tests/api/ApiMiddlewareTest.php b/tests/api/ApiMiddlewareTest.php index 23a56b1c..0b9b03f2 100644 --- a/tests/api/ApiMiddlewareTest.php +++ b/tests/api/ApiMiddlewareTest.php @@ -2,7 +2,6 @@ namespace Shaarli\Api; use Shaarli\Config\ConfigManager; - use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; @@ -18,7 +17,7 @@ use Slim\Http\Response; * * @package Api */ -class ApiMiddlewareTest extends \PHPUnit_Framework_TestCase +class ApiMiddlewareTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations diff --git a/tests/api/ApiUtilsTest.php b/tests/api/ApiUtilsTest.php index a1b623d8..ea0ae500 100644 --- a/tests/api/ApiUtilsTest.php +++ b/tests/api/ApiUtilsTest.php @@ -7,7 +7,7 @@ use Shaarli\Http\Base64Url; /** * Class ApiUtilsTest */ -class ApiUtilsTest extends \PHPUnit_Framework_TestCase +class ApiUtilsTest extends \PHPUnit\Framework\TestCase { /** * Force the timezone for ISO datetimes. diff --git a/tests/api/controllers/history/HistoryTest.php b/tests/api/controllers/history/HistoryTest.php index 24efee89..e287f239 100644 --- a/tests/api/controllers/history/HistoryTest.php +++ b/tests/api/controllers/history/HistoryTest.php @@ -1,9 +1,9 @@ container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = true; - $this->container['history'] = new \Shaarli\History(self::$testHistory); + $this->container['history'] = new History(self::$testHistory); - $this->controller = new History($this->container); + $this->controller = new HistoryController($this->container); } /** @@ -78,35 +78,35 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals($this->refHistory->count(), count($data)); - $this->assertEquals(\Shaarli\History::DELETED, $data[0]['event']); + $this->assertEquals(History::DELETED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM), $data[0]['datetime'] ); $this->assertEquals(124, $data[0]['id']); - $this->assertEquals(\Shaarli\History::SETTINGS, $data[1]['event']); + $this->assertEquals(History::SETTINGS, $data[1]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170302_121215')->format(\DateTime::ATOM), $data[1]['datetime'] ); $this->assertNull($data[1]['id']); - $this->assertEquals(\Shaarli\History::UPDATED, $data[2]['event']); + $this->assertEquals(History::UPDATED, $data[2]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170301_121214')->format(\DateTime::ATOM), $data[2]['datetime'] ); $this->assertEquals(123, $data[2]['id']); - $this->assertEquals(\Shaarli\History::CREATED, $data[3]['event']); + $this->assertEquals(History::CREATED, $data[3]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170201_121214')->format(\DateTime::ATOM), $data[3]['datetime'] ); $this->assertEquals(124, $data[3]['id']); - $this->assertEquals(\Shaarli\History::CREATED, $data[4]['event']); + $this->assertEquals(History::CREATED, $data[4]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170101_121212')->format(\DateTime::ATOM), $data[4]['datetime'] @@ -131,7 +131,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\Shaarli\History::DELETED, $data[0]['event']); + $this->assertEquals(History::DELETED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM), $data[0]['datetime'] @@ -156,7 +156,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\Shaarli\History::CREATED, $data[0]['event']); + $this->assertEquals(History::CREATED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170101_121212')->format(\DateTime::ATOM), $data[0]['datetime'] @@ -181,7 +181,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\Shaarli\History::DELETED, $data[0]['event']); + $this->assertEquals(History::DELETED, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170303_121216')->format(\DateTime::ATOM), $data[0]['datetime'] @@ -206,7 +206,7 @@ class HistoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($data)); - $this->assertEquals(\Shaarli\History::SETTINGS, $data[0]['event']); + $this->assertEquals(History::SETTINGS, $data[0]['event']); $this->assertEquals( \DateTime::createFromFormat('Ymd_His', '20170302_121215')->format(\DateTime::ATOM), $data[0]['datetime'] diff --git a/tests/api/controllers/info/InfoTest.php b/tests/api/controllers/info/InfoTest.php index 44a9382e..e70d371b 100644 --- a/tests/api/controllers/info/InfoTest.php +++ b/tests/api/controllers/info/InfoTest.php @@ -2,7 +2,6 @@ namespace Shaarli\Api\Controllers; use Shaarli\Config\ConfigManager; - use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; @@ -15,7 +14,7 @@ use Slim\Http\Response; * * @package Api\Controllers */ -class InfoTest extends \PHPUnit_Framework_TestCase +class InfoTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations diff --git a/tests/api/controllers/links/DeleteLinkTest.php b/tests/api/controllers/links/DeleteLinkTest.php index adca9a4e..90193e28 100644 --- a/tests/api/controllers/links/DeleteLinkTest.php +++ b/tests/api/controllers/links/DeleteLinkTest.php @@ -3,13 +3,15 @@ namespace Shaarli\Api\Controllers; +use Shaarli\Bookmark\LinkDB; use Shaarli\Config\ConfigManager; +use Shaarli\History; use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; use Slim\Http\Response; -class DeleteLinkTest extends \PHPUnit_Framework_TestCase +class DeleteLinkTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations @@ -32,12 +34,12 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \Shaarli\Bookmark\LinkDB instance. + * @var LinkDB instance. */ protected $linkDB; /** - * @var \Shaarli\History instance. + * @var HistoryController instance. */ protected $history; @@ -59,10 +61,10 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase $this->conf = new ConfigManager('tests/utils/config/configJson'); $this->refDB = new \ReferenceLinkDB(); $this->refDB->write(self::$testDatastore); - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \Shaarli\History(self::$testHistory); + $this->history = new History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = $this->linkDB; @@ -96,11 +98,11 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase $this->assertEquals(204, $response->getStatusCode()); $this->assertEmpty((string) $response->getBody()); - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $this->assertFalse(isset($this->linkDB[$id])); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\Shaarli\History::DELETED, $historyEntry['event']); + $this->assertEquals(History::DELETED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); @@ -110,7 +112,7 @@ class DeleteLinkTest extends \PHPUnit_Framework_TestCase /** * Test DELETE link endpoint: reach not existing ID. * - * @expectedException Shaarli\Api\Exceptions\ApiLinkNotFoundException + * @expectedException \Shaarli\Api\Exceptions\ApiLinkNotFoundException */ public function testDeleteLink404() { diff --git a/tests/api/controllers/links/GetLinkIdTest.php b/tests/api/controllers/links/GetLinkIdTest.php index bf58000b..cb9b7f6a 100644 --- a/tests/api/controllers/links/GetLinkIdTest.php +++ b/tests/api/controllers/links/GetLinkIdTest.php @@ -3,7 +3,6 @@ namespace Shaarli\Api\Controllers; use Shaarli\Config\ConfigManager; - use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; @@ -18,7 +17,7 @@ use Slim\Http\Response; * * @package Shaarli\Api\Controllers */ -class GetLinkIdTest extends \PHPUnit_Framework_TestCase +class GetLinkIdTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations diff --git a/tests/api/controllers/links/GetLinksTest.php b/tests/api/controllers/links/GetLinksTest.php index 1008d7b2..711a3152 100644 --- a/tests/api/controllers/links/GetLinksTest.php +++ b/tests/api/controllers/links/GetLinksTest.php @@ -1,8 +1,8 @@ container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new LinkDB(self::$testDatastore, true, false); $this->container['history'] = null; $this->controller = new Links($this->container); @@ -114,7 +114,7 @@ class GetLinksTest extends \PHPUnit_Framework_TestCase $this->assertEquals('sTuff', $first['tags'][0]); $this->assertEquals(false, $first['private']); $this->assertEquals( - \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20150310_114651')->format(\DateTime::ATOM), + \DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20150310_114651')->format(\DateTime::ATOM), $first['created'] ); $this->assertEmpty($first['updated']); @@ -125,7 +125,7 @@ class GetLinksTest extends \PHPUnit_Framework_TestCase // Update date $this->assertEquals( - \DateTime::createFromFormat(\Shaarli\Bookmark\LinkDB::LINK_DATE_FORMAT, '20160803_093033')->format(\DateTime::ATOM), + \DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, '20160803_093033')->format(\DateTime::ATOM), $link['updated'] ); } diff --git a/tests/api/controllers/links/PostLinkTest.php b/tests/api/controllers/links/PostLinkTest.php index 24e591db..d683a984 100644 --- a/tests/api/controllers/links/PostLinkTest.php +++ b/tests/api/controllers/links/PostLinkTest.php @@ -4,6 +4,7 @@ namespace Shaarli\Api\Controllers; use PHPUnit\Framework\TestCase; use Shaarli\Config\ConfigManager; +use Shaarli\History; use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; @@ -40,7 +41,7 @@ class PostLinkTest extends TestCase protected $refDB = null; /** - * @var \Shaarli\History instance. + * @var HistoryController instance. */ protected $history; @@ -70,12 +71,12 @@ class PostLinkTest extends TestCase $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \Shaarli\History(self::$testHistory); + $this->history = new History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); - $this->container['history'] = new \Shaarli\History(self::$testHistory); + $this->container['history'] = new History(self::$testHistory); $this->controller = new Links($this->container); @@ -133,7 +134,7 @@ class PostLinkTest extends TestCase $this->assertEquals('', $data['updated']); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\Shaarli\History::CREATED, $historyEntry['event']); + $this->assertEquals(History::CREATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/links/PutLinkTest.php b/tests/api/controllers/links/PutLinkTest.php index eb6c7955..cd815b66 100644 --- a/tests/api/controllers/links/PutLinkTest.php +++ b/tests/api/controllers/links/PutLinkTest.php @@ -4,12 +4,13 @@ namespace Shaarli\Api\Controllers; use Shaarli\Config\ConfigManager; +use Shaarli\History; use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; use Slim\Http\Response; -class PutLinkTest extends \PHPUnit_Framework_TestCase +class PutLinkTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations @@ -32,7 +33,7 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \Shaarli\History instance. + * @var HistoryController instance. */ protected $history; @@ -62,12 +63,12 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \Shaarli\History(self::$testHistory); + $this->history = new History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); - $this->container['history'] = new \Shaarli\History(self::$testHistory); + $this->container['history'] = new History(self::$testHistory); $this->controller = new Links($this->container); @@ -119,7 +120,7 @@ class PutLinkTest extends \PHPUnit_Framework_TestCase ); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); + $this->assertEquals(History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/tags/DeleteTagTest.php b/tests/api/controllers/tags/DeleteTagTest.php index 02803ba2..84e1d56e 100644 --- a/tests/api/controllers/tags/DeleteTagTest.php +++ b/tests/api/controllers/tags/DeleteTagTest.php @@ -3,13 +3,15 @@ namespace Shaarli\Api\Controllers; +use Shaarli\Bookmark\LinkDB; use Shaarli\Config\ConfigManager; +use Shaarli\History; use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; use Slim\Http\Response; -class DeleteTagTest extends \PHPUnit_Framework_TestCase +class DeleteTagTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations @@ -32,12 +34,12 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase protected $refDB = null; /** - * @var \Shaarli\Bookmark\LinkDB instance. + * @var LinkDB instance. */ protected $linkDB; /** - * @var \Shaarli\History instance. + * @var HistoryController instance. */ protected $history; @@ -59,10 +61,10 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->conf = new ConfigManager('tests/utils/config/configJson'); $this->refDB = new \ReferenceLinkDB(); $this->refDB->write(self::$testDatastore); - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $refHistory = new \ReferenceHistory(); $refHistory->write(self::$testHistory); - $this->history = new \Shaarli\History(self::$testHistory); + $this->history = new History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; $this->container['db'] = $this->linkDB; @@ -97,18 +99,18 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->assertEquals(204, $response->getStatusCode()); $this->assertEmpty((string) $response->getBody()); - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $tags = $this->linkDB->linksCountPerTag(); $this->assertFalse(isset($tags[$tagName])); // 2 links affected $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); + $this->assertEquals(History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); $historyEntry = $this->history->getHistory()[1]; - $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); + $this->assertEquals(History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); @@ -131,13 +133,13 @@ class DeleteTagTest extends \PHPUnit_Framework_TestCase $this->assertEquals(204, $response->getStatusCode()); $this->assertEmpty((string) $response->getBody()); - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $tags = $this->linkDB->linksCountPerTag(); $this->assertFalse(isset($tags[$tagName])); $this->assertTrue($tags[strtolower($tagName)] > 0); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); + $this->assertEquals(History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/api/controllers/tags/GetTagNameTest.php b/tests/api/controllers/tags/GetTagNameTest.php index 8e0feccd..a2525c17 100644 --- a/tests/api/controllers/tags/GetTagNameTest.php +++ b/tests/api/controllers/tags/GetTagNameTest.php @@ -2,8 +2,8 @@ namespace Shaarli\Api\Controllers; +use Shaarli\Bookmark\LinkDB; use Shaarli\Config\ConfigManager; - use Slim\Container; use Slim\Http\Environment; use Slim\Http\Request; @@ -16,7 +16,7 @@ use Slim\Http\Response; * * @package Shaarli\Api\Controllers */ -class GetTagNameTest extends \PHPUnit_Framework_TestCase +class GetTagNameTest extends \PHPUnit\Framework\TestCase { /** * @var string datastore to test write operations @@ -59,7 +59,7 @@ class GetTagNameTest extends \PHPUnit_Framework_TestCase $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->container['db'] = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->container['db'] = new LinkDB(self::$testDatastore, true, false); $this->container['history'] = null; $this->controller = new Tags($this->container); diff --git a/tests/api/controllers/tags/GetTagsTest.php b/tests/api/controllers/tags/GetTagsTest.php index f071bfa8..98628c98 100644 --- a/tests/api/controllers/tags/GetTagsTest.php +++ b/tests/api/controllers/tags/GetTagsTest.php @@ -1,8 +1,8 @@ container = new Container(); $this->container['conf'] = $this->conf; - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $this->container['db'] = $this->linkDB; $this->container['history'] = null; diff --git a/tests/api/controllers/tags/PutTagTest.php b/tests/api/controllers/tags/PutTagTest.php index d8c0fec8..86106fc7 100644 --- a/tests/api/controllers/tags/PutTagTest.php +++ b/tests/api/controllers/tags/PutTagTest.php @@ -1,16 +1,17 @@ write(self::$testHistory); - $this->history = new \Shaarli\History(self::$testHistory); + $this->history = new History(self::$testHistory); $this->container = new Container(); $this->container['conf'] = $this->conf; - $this->linkDB = new \Shaarli\Bookmark\LinkDB(self::$testDatastore, true, false); + $this->linkDB = new LinkDB(self::$testDatastore, true, false); $this->container['db'] = $this->linkDB; $this->container['history'] = $this->history; @@ -113,12 +114,12 @@ class PutTagTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2, $tags[$newName]); $historyEntry = $this->history->getHistory()[0]; - $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); + $this->assertEquals(History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); $historyEntry = $this->history->getHistory()[1]; - $this->assertEquals(\Shaarli\History::UPDATED, $historyEntry['event']); + $this->assertEquals(History::UPDATED, $historyEntry['event']); $this->assertTrue( (new \DateTime())->add(\DateInterval::createFromDateString('-5 seconds')) < $historyEntry['datetime'] ); diff --git a/tests/bookmark/LinkDBTest.php b/tests/bookmark/LinkDBTest.php index 65409e95..ff5c0b97 100644 --- a/tests/bookmark/LinkDBTest.php +++ b/tests/bookmark/LinkDBTest.php @@ -6,7 +6,6 @@ namespace Shaarli\Bookmark; use DateTime; -use Shaarli\Bookmark\Exception\LinkNotFoundException; use ReferenceLinkDB; use ReflectionClass; use Shaarli; diff --git a/tests/config/ConfigJsonTest.php b/tests/config/ConfigJsonTest.php index 99c1ea56..95ad060b 100644 --- a/tests/config/ConfigJsonTest.php +++ b/tests/config/ConfigJsonTest.php @@ -4,7 +4,7 @@ namespace Shaarli\Config; /** * Class ConfigJsonTest */ -class ConfigJsonTest extends \PHPUnit_Framework_TestCase +class ConfigJsonTest extends \PHPUnit\Framework\TestCase { /** * @var ConfigJson diff --git a/tests/config/ConfigManagerTest.php b/tests/config/ConfigManagerTest.php index 4a4e94ac..33830bc9 100644 --- a/tests/config/ConfigManagerTest.php +++ b/tests/config/ConfigManagerTest.php @@ -7,7 +7,7 @@ namespace Shaarli\Config; * Note: it only test the manager with ConfigJson, * ConfigPhp is only a workaround to handle the transition to JSON type. */ -class ConfigManagerTest extends \PHPUnit_Framework_TestCase +class ConfigManagerTest extends \PHPUnit\Framework\TestCase { /** * @var ConfigManager diff --git a/tests/config/ConfigPhpTest.php b/tests/config/ConfigPhpTest.php index be23eea1..67d878ce 100644 --- a/tests/config/ConfigPhpTest.php +++ b/tests/config/ConfigPhpTest.php @@ -4,7 +4,7 @@ namespace Shaarli\Config; /** * Class ConfigPhpTest */ -class ConfigPhpTest extends \PHPUnit_Framework_TestCase +class ConfigPhpTest extends \PHPUnit\Framework\TestCase { /** * @var ConfigPhp diff --git a/tests/config/ConfigPluginTest.php b/tests/config/ConfigPluginTest.php index deb02c9e..d7a70e68 100644 --- a/tests/config/ConfigPluginTest.php +++ b/tests/config/ConfigPluginTest.php @@ -8,7 +8,7 @@ require_once 'application/config/ConfigPlugin.php'; /** * Unitary tests for Shaarli config related functions */ -class ConfigPluginTest extends \PHPUnit_Framework_TestCase +class ConfigPluginTest extends \PHPUnit\Framework\TestCase { /** * Test save_plugin_config with valid data. diff --git a/tests/feed/FeedBuilderTest.php b/tests/feed/FeedBuilderTest.php index 88d1c3ed..b496cb4c 100644 --- a/tests/feed/FeedBuilderTest.php +++ b/tests/feed/FeedBuilderTest.php @@ -3,8 +3,8 @@ namespace Shaarli\Feed; use DateTime; -use Shaarli\Bookmark\LinkDB; use ReferenceLinkDB; +use Shaarli\Bookmark\LinkDB; /** * FeedBuilderTest class. diff --git a/tests/languages/fr/LanguagesFrTest.php b/tests/languages/fr/LanguagesFrTest.php index 38347de1..b8b7ca3a 100644 --- a/tests/languages/fr/LanguagesFrTest.php +++ b/tests/languages/fr/LanguagesFrTest.php @@ -12,7 +12,7 @@ use Shaarli\Config\ConfigManager; * * @package Shaarli */ -class LanguagesFrTest extends \PHPUnit_Framework_TestCase +class LanguagesFrTest extends \PHPUnit\Framework\TestCase { /** * @var string Config file path (without extension). diff --git a/tests/plugins/WallabagInstanceTest.php b/tests/plugins/WallabagInstanceTest.php index bcc01604..a3cd9076 100644 --- a/tests/plugins/WallabagInstanceTest.php +++ b/tests/plugins/WallabagInstanceTest.php @@ -1,8 +1,6 @@