From 485b168a9677d160b0c0426e4f282b9bd0c632c1 Mon Sep 17 00:00:00 2001
From: ArthurHoaro
';
$url = 'https://sub.domain.tld?query=here&for=real#hash';
$description[1] = 'text '. $url .' more text
';
- $description[2] = 'Also, there is an #hashtag added
';
$description[3] = ' A N D KEEP '.
'SPACES !
';
@@ -148,7 +148,7 @@ class BookmarkDefaultFormatterTest extends TestCase
$this->assertEquals($root . $short, $link['url']);
$this->assertEquals($root . $short, $link['real_url']);
$this->assertEquals(
- 'Text '.
+ 'Text '.
'#hashtag more text',
$link['description']
);
diff --git a/tests/formatter/BookmarkMarkdownFormatterTest.php b/tests/formatter/BookmarkMarkdownFormatterTest.php
index f1f12c04..3e72d1ee 100644
--- a/tests/formatter/BookmarkMarkdownFormatterTest.php
+++ b/tests/formatter/BookmarkMarkdownFormatterTest.php
@@ -125,7 +125,7 @@ class BookmarkMarkdownFormatterTest extends TestCase
$description .= 'This a <strong>description</strong>
'. PHP_EOL;
$url = 'https://sub.domain.tld?query=here&for=real#hash';
$description .= 'text '. $url .' more text
'. PHP_EOL;
- $description .= 'Also, there is an #hashtag added
'. PHP_EOL;
+ $description .= 'Also, there is an #hashtag added
'. PHP_EOL;
$description .= 'A N D KEEP SPACES ! ';
$description .= '
'; - $description .= 'Text #hashtag more text'; + $description .= 'Text #hashtag more text'; $description .= '
fsdfs http://link.tld #foobar http://link.tld
http://link.tld #foobar
-next #foo
-Block:
-lorem ipsum #foobar http://link.tld
-#foobar http://link.tld
-Sessions do not seem to work correctly on your server', + $assignedVars['message'] + ); + } + + /** + * Test saving valid data from install form. Also initialize datastore. + */ + public function testSaveInstallValid(): void + { + $providedParameters = [ + 'continent' => 'Europe', + 'city' => 'Berlin', + 'setlogin' => 'bob', + 'setpassword' => 'password', + 'title' => 'Shaarli', + 'language' => 'fr', + 'updateCheck' => true, + 'enableApi' => true, + ]; + + $expectedSettings = [ + 'general.timezone' => 'Europe/Berlin', + 'credentials.login' => 'bob', + 'credentials.salt' => '_NOT_EMPTY', + 'credentials.hash' => '_NOT_EMPTY', + 'general.title' => 'Shaarli', + 'translation.language' => 'en', + 'updates.check_updates' => true, + 'api.enabled' => true, + 'api.secret' => '_NOT_EMPTY', + ]; + + $request = $this->createMock(Request::class); + $request->method('getParam')->willReturnCallback(function (string $key) use ($providedParameters) { + return $providedParameters[$key] ?? null; + }); + $response = new Response(); + + $this->container->conf = $this->createMock(ConfigManager::class); + $this->container->conf + ->method('get') + ->willReturnCallback(function (string $key, $value) { + if ($key === 'credentials.login') { + return 'bob'; + } elseif ($key === 'credentials.salt') { + return 'salt'; + } + + return $value; + }) + ; + $this->container->conf + ->expects(static::exactly(count($expectedSettings))) + ->method('set') + ->willReturnCallback(function (string $key, $value) use ($expectedSettings) { + if ($expectedSettings[$key] ?? null === '_NOT_EMPTY') { + static::assertNotEmpty($value); + } else { + static::assertSame($expectedSettings[$key], $value); + } + }) + ; + $this->container->conf->expects(static::once())->method('write'); + + $this->container->bookmarkService->expects(static::once())->method('count')->willReturn(0); + $this->container->bookmarkService->expects(static::once())->method('initialize'); + + $this->container->sessionManager + ->expects(static::once()) + ->method('setSessionParameter') + ->with(SessionManager::KEY_SUCCESS_MESSAGES) + ; + + $result = $this->controller->save($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/', $result->getHeader('location')[0]); + } + + /** + * Test default settings (timezone and title). + * Also check that bookmarks are not initialized if + */ + public function testSaveInstallDefaultValues(): void + { + $confSettings = []; + + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->conf->method('set')->willReturnCallback(function (string $key, $value) use (&$confSettings) { + $confSettings[$key] = $value; + }); + + $result = $this->controller->save($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/', $result->getHeader('location')[0]); + + static::assertSame('UTC', $confSettings['general.timezone']); + static::assertSame('Shared bookmarks on http://shaarli', $confSettings['general.title']); + } +} diff --git a/tests/render/PageCacheManagerTest.php b/tests/render/PageCacheManagerTest.php index b870e6eb..c258f45f 100644 --- a/tests/render/PageCacheManagerTest.php +++ b/tests/render/PageCacheManagerTest.php @@ -1,15 +1,14 @@ cookie = []; $this->session = []; - $this->sessionManager = new SessionManager($this->session, $this->configManager); - $this->loginManager = new LoginManager($this->configManager, $this->sessionManager); + $this->cookieManager = $this->createMock(CookieManager::class); + $this->cookieManager->method('getCookieParameter')->willReturnCallback(function (string $key) { + return $this->cookie[$key] ?? null; + }); + $this->sessionManager = new SessionManager($this->session, $this->configManager, 'session_path'); + $this->loginManager = new LoginManager($this->configManager, $this->sessionManager, $this->cookieManager); $this->server['REMOTE_ADDR'] = $this->ipAddr; } @@ -193,8 +199,8 @@ class LoginManagerTest extends TestCase $configManager = new \FakeConfigManager([ 'resource.ban_file' => $this->banFile, ]); - $loginManager = new LoginManager($configManager, null); - $loginManager->checkLoginState([], ''); + $loginManager = new LoginManager($configManager, null, $this->cookieManager); + $loginManager->checkLoginState(''); $this->assertFalse($loginManager->isLoggedIn()); } @@ -210,9 +216,9 @@ class LoginManagerTest extends TestCase 'expires_on' => time() + 100, ]; $this->loginManager->generateStaySignedInToken($this->clientIpAddress); - $this->cookie[LoginManager::$STAY_SIGNED_IN_COOKIE] = 'nope'; + $this->cookie[CookieManager::STAY_SIGNED_IN] = 'nope'; - $this->loginManager->checkLoginState($this->cookie, $this->clientIpAddress); + $this->loginManager->checkLoginState($this->clientIpAddress); $this->assertTrue($this->loginManager->isLoggedIn()); $this->assertTrue(empty($this->session['username'])); @@ -224,9 +230,9 @@ class LoginManagerTest extends TestCase public function testCheckLoginStateStaySignedInWithValidToken() { $this->loginManager->generateStaySignedInToken($this->clientIpAddress); - $this->cookie[LoginManager::$STAY_SIGNED_IN_COOKIE] = $this->loginManager->getStaySignedInToken(); + $this->cookie[CookieManager::STAY_SIGNED_IN] = $this->loginManager->getStaySignedInToken(); - $this->loginManager->checkLoginState($this->cookie, $this->clientIpAddress); + $this->loginManager->checkLoginState($this->clientIpAddress); $this->assertTrue($this->loginManager->isLoggedIn()); $this->assertEquals($this->login, $this->session['username']); @@ -241,7 +247,7 @@ class LoginManagerTest extends TestCase $this->loginManager->generateStaySignedInToken($this->clientIpAddress); $this->session['expires_on'] = time() - 100; - $this->loginManager->checkLoginState($this->cookie, $this->clientIpAddress); + $this->loginManager->checkLoginState($this->clientIpAddress); $this->assertFalse($this->loginManager->isLoggedIn()); } @@ -253,7 +259,7 @@ class LoginManagerTest extends TestCase { $this->loginManager->generateStaySignedInToken($this->clientIpAddress); - $this->loginManager->checkLoginState($this->cookie, '10.7.157.98'); + $this->loginManager->checkLoginState('10.7.157.98'); $this->assertFalse($this->loginManager->isLoggedIn()); } diff --git a/tests/security/SessionManagerTest.php b/tests/security/SessionManagerTest.php index d9db775e..60695dcf 100644 --- a/tests/security/SessionManagerTest.php +++ b/tests/security/SessionManagerTest.php @@ -1,12 +1,8 @@ conf = new FakeConfigManager([ + $this->conf = new \FakeConfigManager([ 'credentials.login' => 'johndoe', 'credentials.salt' => 'salt', 'security.session_protection_disabled' => false, ]); $this->session = []; - $this->sessionManager = new SessionManager($this->session, $this->conf); + $this->sessionManager = new SessionManager($this->session, $this->conf, 'session_path'); } /** @@ -69,7 +65,7 @@ class SessionManagerTest extends TestCase $token => 1, ], ]; - $sessionManager = new SessionManager($session, $this->conf); + $sessionManager = new SessionManager($session, $this->conf, 'session_path'); // check and destroy the token $this->assertTrue($sessionManager->checkToken($token)); diff --git a/tests/updater/UpdaterTest.php b/tests/updater/UpdaterTest.php index afc35aec..c801d451 100644 --- a/tests/updater/UpdaterTest.php +++ b/tests/updater/UpdaterTest.php @@ -7,9 +7,6 @@ use Shaarli\Bookmark\BookmarkServiceInterface; use Shaarli\Config\ConfigManager; use Shaarli\History; -require_once 'tests/updater/DummyUpdater.php'; -require_once 'tests/utils/ReferenceLinkDB.php'; -require_once 'inc/rain.tpl.class.php'; /** * Class UpdaterTest. @@ -35,6 +32,9 @@ class UpdaterTest extends \PHPUnit\Framework\TestCase /** @var BookmarkServiceInterface */ protected $bookmarkService; + /** @var \ReferenceLinkDB */ + protected $refDB; + /** @var Updater */ protected $updater; @@ -43,6 +43,9 @@ class UpdaterTest extends \PHPUnit\Framework\TestCase */ public function setUp() { + $this->refDB = new \ReferenceLinkDB(); + $this->refDB->write(self::$testDatastore); + copy('tests/utils/config/configJson.json.php', self::$configFile .'.json.php'); $this->conf = new ConfigManager(self::$configFile); $this->bookmarkService = new BookmarkFileService($this->conf, $this->createMock(History::class), true); @@ -181,9 +184,40 @@ class UpdaterTest extends \PHPUnit\Framework\TestCase public function testUpdateMethodRelativeHomeLinkRename(): void { + $this->updater->setBasePath('/subfolder'); $this->conf->set('general.header_link', '?'); + + $this->updater->updateMethodRelativeHomeLink(); + + static::assertSame('/subfolder/', $this->conf->get('general.header_link')); + } + + public function testUpdateMethodRelativeHomeLinkDoNotRename(): void + { + $this->updater->setBasePath('/subfolder'); + $this->conf->set('general.header_link', '~/my-blog'); + $this->updater->updateMethodRelativeHomeLink(); - static::assertSame(); + static::assertSame('~/my-blog', $this->conf->get('general.header_link')); + } + + public function testUpdateMethodMigrateExistingNotesUrl(): void + { + $this->updater->setBasePath('/subfolder'); + + $this->updater->updateMethodMigrateExistingNotesUrl(); + + static::assertSame($this->refDB->getLinks()[0]->getUrl(), $this->bookmarkService->get(0)->getUrl()); + static::assertSame($this->refDB->getLinks()[1]->getUrl(), $this->bookmarkService->get(1)->getUrl()); + static::assertSame($this->refDB->getLinks()[4]->getUrl(), $this->bookmarkService->get(4)->getUrl()); + static::assertSame($this->refDB->getLinks()[6]->getUrl(), $this->bookmarkService->get(6)->getUrl()); + static::assertSame($this->refDB->getLinks()[7]->getUrl(), $this->bookmarkService->get(7)->getUrl()); + static::assertSame($this->refDB->getLinks()[8]->getUrl(), $this->bookmarkService->get(8)->getUrl()); + static::assertSame($this->refDB->getLinks()[9]->getUrl(), $this->bookmarkService->get(9)->getUrl()); + static::assertSame('/subfolder/shaare/WDWyig', $this->bookmarkService->get(42)->getUrl()); + static::assertSame('/subfolder/shaare/WDWyig', $this->bookmarkService->get(41)->getUrl()); + static::assertSame('/subfolder/shaare/0gCTjQ', $this->bookmarkService->get(10)->getUrl()); + static::assertSame('/subfolder/shaare/PCRizQ', $this->bookmarkService->get(11)->getUrl()); } } -- cgit v1.2.3 From a8c11451e8d885a243c1ad52012093ba8d121e2c Mon Sep 17 00:00:00 2001 From: ArthurHoaroDate: Tue, 21 Jul 2020 20:33:33 +0200 Subject: Process login through Slim controller --- tests/front/ShaarliMiddlewareTest.php | 7 +- .../visitor/FrontControllerMockHelper.php | 1 + .../controller/visitor/LoginControllerTest.php | 278 ++++++++++++++++++++- 3 files changed, 281 insertions(+), 5 deletions(-) (limited to 'tests') diff --git a/tests/front/ShaarliMiddlewareTest.php b/tests/front/ShaarliMiddlewareTest.php index 20090d8b..09bebd04 100644 --- a/tests/front/ShaarliMiddlewareTest.php +++ b/tests/front/ShaarliMiddlewareTest.php @@ -38,6 +38,8 @@ class ShaarliMiddlewareTest extends TestCase $this->container->loginManager = $this->createMock(LoginManager::class); + $this->container->environment = ['REQUEST_URI' => 'http://shaarli/subfolder/path']; + $this->middleware = new ShaarliMiddleware($this->container); } @@ -127,7 +129,10 @@ class ShaarliMiddlewareTest extends TestCase $result = $this->middleware->__invoke($request, $response, $controller); static::assertSame(302, $result->getStatusCode()); - static::assertSame('/subfolder/login', $result->getHeader('location')[0]); + static::assertSame( + '/subfolder/login?returnurl=' . urlencode('http://shaarli/subfolder/path'), + $result->getHeader('location')[0] + ); } /** diff --git a/tests/front/controller/visitor/FrontControllerMockHelper.php b/tests/front/controller/visitor/FrontControllerMockHelper.php index 7f560662..e0bd4ecf 100644 --- a/tests/front/controller/visitor/FrontControllerMockHelper.php +++ b/tests/front/controller/visitor/FrontControllerMockHelper.php @@ -80,6 +80,7 @@ trait FrontControllerMockHelper 'SERVER_NAME' => 'shaarli', 'SERVER_PORT' => '80', 'REQUEST_URI' => '/daily-rss', + 'REMOTE_ADDR' => '1.2.3.4', ]; $this->container->basePath = '/subfolder'; diff --git a/tests/front/controller/visitor/LoginControllerTest.php b/tests/front/controller/visitor/LoginControllerTest.php index e57f44b9..0a21f938 100644 --- a/tests/front/controller/visitor/LoginControllerTest.php +++ b/tests/front/controller/visitor/LoginControllerTest.php @@ -7,6 +7,10 @@ namespace Shaarli\Front\Controller\Visitor; use PHPUnit\Framework\TestCase; use Shaarli\Config\ConfigManager; use Shaarli\Front\Exception\LoginBannedException; +use Shaarli\Front\Exception\WrongTokenException; +use Shaarli\Render\TemplatePage; +use Shaarli\Security\CookieManager; +use Shaarli\Security\SessionManager; use Slim\Http\Request; use Slim\Http\Response; @@ -21,13 +25,25 @@ class LoginControllerTest extends TestCase { $this->createContainer(); + $this->container->cookieManager = $this->createMock(CookieManager::class); + $this->container->sessionManager->method('checkToken')->willReturn(true); + $this->controller = new LoginController($this->container); } + /** + * Test displaying login form with valid parameters. + */ public function testValidControllerInvoke(): void { $request = $this->createMock(Request::class); - $request->expects(static::once())->method('getServerParam')->willReturn('> referer'); + $request + ->expects(static::atLeastOnce()) + ->method('getParam') + ->willReturnCallback(function (string $key) { + return 'returnurl' === $key ? '> referer' : null; + }) + ; $response = new Response(); $assignedVariables = []; @@ -46,18 +62,32 @@ class LoginControllerTest extends TestCase static::assertInstanceOf(Response::class, $result); static::assertSame(200, $result->getStatusCode()); - static::assertSame('loginform', (string) $result->getBody()); + static::assertSame(TemplatePage::LOGIN, (string) $result->getBody()); static::assertSame('> referer', $assignedVariables['returnurl']); static::assertSame(true, $assignedVariables['remember_user_default']); static::assertSame('Login - Shaarli', $assignedVariables['pagetitle']); } + /** + * Test displaying login form with username defined in the request. + */ public function testValidControllerInvokeWithUserName(): void { + $this->container->environment = ['HTTP_REFERER' => '> referer']; + $request = $this->createMock(Request::class); - $request->expects(static::once())->method('getServerParam')->willReturn('> referer'); - $request->expects(static::exactly(2))->method('getParam')->willReturn('myUser>'); + $request + ->expects(static::atLeastOnce()) + ->method('getParam') + ->willReturnCallback(function (string $key, $default) { + if ('login' === $key) { + return 'myUser>'; + } + + return $default; + }) + ; $response = new Response(); $assignedVariables = []; @@ -84,6 +114,9 @@ class LoginControllerTest extends TestCase static::assertSame('Login - Shaarli', $assignedVariables['pagetitle']); } + /** + * Test displaying login page while being logged in. + */ public function testLoginControllerWhileLoggedIn(): void { $request = $this->createMock(Request::class); @@ -98,6 +131,9 @@ class LoginControllerTest extends TestCase static::assertSame(['/subfolder/'], $result->getHeader('Location')); } + /** + * Test displaying login page with open shaarli configured: redirect to homepage. + */ public function testLoginControllerOpenShaarli(): void { $request = $this->createMock(Request::class); @@ -119,6 +155,9 @@ class LoginControllerTest extends TestCase static::assertSame(['/subfolder/'], $result->getHeader('Location')); } + /** + * Test displaying login page while being banned. + */ public function testLoginControllerWhileBanned(): void { $request = $this->createMock(Request::class); @@ -131,4 +170,235 @@ class LoginControllerTest extends TestCase $this->controller->index($request, $response); } + + /** + * Test processing login with valid parameters. + */ + public function testProcessLoginWithValidParameters(): void + { + $parameters = [ + 'login' => 'bob', + 'password' => 'pass', + ]; + $request = $this->createMock(Request::class); + $request + ->expects(static::atLeastOnce()) + ->method('getParam') + ->willReturnCallback(function (string $key) use ($parameters) { + return $parameters[$key] ?? null; + }) + ; + $response = new Response(); + + $this->container->loginManager->method('canLogin')->willReturn(true); + $this->container->loginManager->expects(static::once())->method('handleSuccessfulLogin'); + $this->container->loginManager + ->expects(static::once()) + ->method('checkCredentials') + ->with('1.2.3.4', '1.2.3.4', 'bob', 'pass') + ->willReturn(true) + ; + $this->container->loginManager->method('getStaySignedInToken')->willReturn(bin2hex(random_bytes(8))); + + $this->container->sessionManager->expects(static::never())->method('extendSession'); + $this->container->sessionManager->expects(static::once())->method('destroy'); + $this->container->sessionManager + ->expects(static::once()) + ->method('cookieParameters') + ->with(0, '/subfolder/', 'shaarli') + ; + $this->container->sessionManager->expects(static::once())->method('start'); + $this->container->sessionManager->expects(static::once())->method('regenerateId')->with(true); + + $result = $this->controller->login($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/', $result->getHeader('location')[0]); + } + + /** + * Test processing login with return URL. + */ + public function testProcessLoginWithReturnUrl(): void + { + $parameters = [ + 'returnurl' => 'http://shaarli/subfolder/admin/shaare', + ]; + $request = $this->createMock(Request::class); + $request + ->expects(static::atLeastOnce()) + ->method('getParam') + ->willReturnCallback(function (string $key) use ($parameters) { + return $parameters[$key] ?? null; + }) + ; + $response = new Response(); + + $this->container->loginManager->method('canLogin')->willReturn(true); + $this->container->loginManager->expects(static::once())->method('handleSuccessfulLogin'); + $this->container->loginManager->expects(static::once())->method('checkCredentials')->willReturn(true); + $this->container->loginManager->method('getStaySignedInToken')->willReturn(bin2hex(random_bytes(8))); + + $result = $this->controller->login($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/admin/shaare', $result->getHeader('location')[0]); + } + + /** + * Test processing login with remember me session enabled. + */ + public function testProcessLoginLongLastingSession(): void + { + $parameters = [ + 'longlastingsession' => true, + ]; + $request = $this->createMock(Request::class); + $request + ->expects(static::atLeastOnce()) + ->method('getParam') + ->willReturnCallback(function (string $key) use ($parameters) { + return $parameters[$key] ?? null; + }) + ; + $response = new Response(); + + $this->container->loginManager->method('canLogin')->willReturn(true); + $this->container->loginManager->expects(static::once())->method('handleSuccessfulLogin'); + $this->container->loginManager->expects(static::once())->method('checkCredentials')->willReturn(true); + $this->container->loginManager->method('getStaySignedInToken')->willReturn(bin2hex(random_bytes(8))); + + $this->container->sessionManager->expects(static::once())->method('destroy'); + $this->container->sessionManager + ->expects(static::once()) + ->method('cookieParameters') + ->with(42, '/subfolder/', 'shaarli') + ; + $this->container->sessionManager->expects(static::once())->method('start'); + $this->container->sessionManager->expects(static::once())->method('regenerateId')->with(true); + $this->container->sessionManager->expects(static::once())->method('extendSession')->willReturn(42); + + $this->container->cookieManager = $this->createMock(CookieManager::class); + $this->container->cookieManager + ->expects(static::once()) + ->method('setCookieParameter') + ->willReturnCallback(function (string $name): CookieManager { + static::assertSame(CookieManager::STAY_SIGNED_IN, $name); + + return $this->container->cookieManager; + }) + ; + + $result = $this->controller->login($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/', $result->getHeader('location')[0]); + } + + /** + * Test processing login with invalid credentials + */ + public function testProcessLoginWrongCredentials(): void + { + $parameters = [ + 'returnurl' => 'http://shaarli/subfolder/admin/shaare', + ]; + $request = $this->createMock(Request::class); + $request + ->expects(static::atLeastOnce()) + ->method('getParam') + ->willReturnCallback(function (string $key) use ($parameters) { + return $parameters[$key] ?? null; + }) + ; + $response = new Response(); + + $this->container->loginManager->method('canLogin')->willReturn(true); + $this->container->loginManager->expects(static::once())->method('handleFailedLogin'); + $this->container->loginManager->expects(static::once())->method('checkCredentials')->willReturn(false); + + $this->container->sessionManager + ->expects(static::once()) + ->method('setSessionParameter') + ->with(SessionManager::KEY_ERROR_MESSAGES, ['Wrong login/password.']) + ; + + $result = $this->controller->login($request, $response); + + static::assertSame(200, $result->getStatusCode()); + static::assertSame(TemplatePage::LOGIN, (string) $result->getBody()); + } + + /** + * Test processing login with wrong token + */ + public function testProcessLoginWrongToken(): void + { + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->sessionManager = $this->createMock(SessionManager::class); + $this->container->sessionManager->method('checkToken')->willReturn(false); + + $this->expectException(WrongTokenException::class); + + $this->controller->login($request, $response); + } + + /** + * Test processing login with wrong token + */ + public function testProcessLoginAlreadyLoggedIn(): void + { + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->loginManager->method('isLoggedIn')->willReturn(true); + $this->container->loginManager->expects(static::never())->method('handleSuccessfulLogin'); + $this->container->loginManager->expects(static::never())->method('handleFailedLogin'); + + $result = $this->controller->login($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/', $result->getHeader('location')[0]); + } + + /** + * Test processing login with wrong token + */ + public function testProcessLoginInOpenShaarli(): void + { + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->conf = $this->createMock(ConfigManager::class); + $this->container->conf->method('get')->willReturnCallback(function (string $key, $value) { + return 'security.open_shaarli' === $key ? true : $value; + }); + + $this->container->loginManager->expects(static::never())->method('handleSuccessfulLogin'); + $this->container->loginManager->expects(static::never())->method('handleFailedLogin'); + + $result = $this->controller->login($request, $response); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame('/subfolder/', $result->getHeader('location')[0]); + } + + /** + * Test processing login while being banned + */ + public function testProcessLoginWhileBanned(): void + { + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->loginManager->method('canLogin')->willReturn(false); + $this->container->loginManager->expects(static::never())->method('handleSuccessfulLogin'); + $this->container->loginManager->expects(static::never())->method('handleFailedLogin'); + + $this->expectException(LoginBannedException::class); + + $this->controller->login($request, $response); + } } -- cgit v1.2.3 From 3ee8351e438f13ccf36062ce956e0b4a4d5f4a29 Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Thu, 23 Jul 2020 16:41:32 +0200 Subject: Multiple small fixes --- tests/front/controller/admin/PluginsControllerTest.php | 2 +- tests/front/controller/visitor/InstallControllerTest.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'tests') diff --git a/tests/front/controller/admin/PluginsControllerTest.php b/tests/front/controller/admin/PluginsControllerTest.php index 700a0df2..ad0cda70 100644 --- a/tests/front/controller/admin/PluginsControllerTest.php +++ b/tests/front/controller/admin/PluginsControllerTest.php @@ -162,7 +162,7 @@ class PluginsControllerTest extends TestCase ->method('setSessionParameter') ->with( SessionManager::KEY_ERROR_MESSAGES, - ['ERROR while saving plugin configuration: ' . PHP_EOL . $message] + ['Error while saving plugin configuration: ' . PHP_EOL . $message] ) ; diff --git a/tests/front/controller/visitor/InstallControllerTest.php b/tests/front/controller/visitor/InstallControllerTest.php index 6871fdd9..29c4d7a0 100644 --- a/tests/front/controller/visitor/InstallControllerTest.php +++ b/tests/front/controller/visitor/InstallControllerTest.php @@ -189,6 +189,7 @@ class InstallControllerTest extends TestCase 'updates.check_updates' => true, 'api.enabled' => true, 'api.secret' => '_NOT_EMPTY', + 'general.header_link' => '/subfolder', ]; $request = $this->createMock(Request::class); -- cgit v1.2.3 From 87ae3c4f08431e02869376cb57add257747910d1 Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Fri, 24 Jul 2020 10:30:47 +0200 Subject: Fix default link and redirection in install controller --- tests/front/controller/visitor/InstallControllerTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/front/controller/visitor/InstallControllerTest.php b/tests/front/controller/visitor/InstallControllerTest.php index 29c4d7a0..089c64ac 100644 --- a/tests/front/controller/visitor/InstallControllerTest.php +++ b/tests/front/controller/visitor/InstallControllerTest.php @@ -236,7 +236,7 @@ class InstallControllerTest extends TestCase $result = $this->controller->save($request, $response); static::assertSame(302, $result->getStatusCode()); - static::assertSame('/subfolder/', $result->getHeader('location')[0]); + static::assertSame('/subfolder/login', $result->getHeader('location')[0]); } /** @@ -257,7 +257,7 @@ class InstallControllerTest extends TestCase $result = $this->controller->save($request, $response); static::assertSame(302, $result->getStatusCode()); - static::assertSame('/subfolder/', $result->getHeader('location')[0]); + static::assertSame('/subfolder/login', $result->getHeader('location')[0]); static::assertSame('UTC', $confSettings['general.timezone']); static::assertSame('Shared bookmarks on http://shaarli', $confSettings['general.title']); -- cgit v1.2.3 From 204035bd3c91b9a5c39fcb6fc470e108b032dbd9 Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Fri, 24 Jul 2020 12:48:53 +0200 Subject: Fix: visitor are allowed to chose nb of links per page --- .../admin/SessionFilterControllerTest.php | 48 +-------------- .../visitor/PublicSessionFilterControllerTest.php | 71 ++++++++++++++++++++++ 2 files changed, 72 insertions(+), 47 deletions(-) create mode 100644 tests/front/controller/visitor/PublicSessionFilterControllerTest.php (limited to 'tests') diff --git a/tests/front/controller/admin/SessionFilterControllerTest.php b/tests/front/controller/admin/SessionFilterControllerTest.php index ea07edee..124b0bf2 100644 --- a/tests/front/controller/admin/SessionFilterControllerTest.php +++ b/tests/front/controller/admin/SessionFilterControllerTest.php @@ -23,53 +23,7 @@ class SessionFilterControllerTest extends TestCase $this->controller = new SessionFilterController($this->container); } - - /** - * Link per page - Default call with valid parameter and a referer. - */ - public function testLinksPerPage(): void - { - $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/subfolder/controller/?searchtag=abc']; - - $request = $this->createMock(Request::class); - $request->method('getParam')->with('nb')->willReturn('8'); - $response = new Response(); - - $this->container->sessionManager - ->expects(static::once()) - ->method('setSessionParameter') - ->with(SessionManager::KEY_LINKS_PER_PAGE, 8) - ; - - $result = $this->controller->linksPerPage($request, $response); - - static::assertInstanceOf(Response::class, $result); - static::assertSame(302, $result->getStatusCode()); - static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); - } - - /** - * Link per page - Invalid value, should use default value (20) - */ - public function testLinksPerPageNotValid(): void - { - $request = $this->createMock(Request::class); - $request->method('getParam')->with('nb')->willReturn('test'); - $response = new Response(); - - $this->container->sessionManager - ->expects(static::once()) - ->method('setSessionParameter') - ->with(SessionManager::KEY_LINKS_PER_PAGE, 20) - ; - - $result = $this->controller->linksPerPage($request, $response); - - static::assertInstanceOf(Response::class, $result); - static::assertSame(302, $result->getStatusCode()); - static::assertSame(['/subfolder/'], $result->getHeader('location')); - } - + /** * Visibility - Default call for private filter while logged in without current value */ diff --git a/tests/front/controller/visitor/PublicSessionFilterControllerTest.php b/tests/front/controller/visitor/PublicSessionFilterControllerTest.php new file mode 100644 index 00000000..3aa1cb99 --- /dev/null +++ b/tests/front/controller/visitor/PublicSessionFilterControllerTest.php @@ -0,0 +1,71 @@ +createContainer(); + + $this->controller = new PublicSessionFilterController($this->container); + } + + /** + * Link per page - Default call with valid parameter and a referer. + */ + public function testLinksPerPage(): void + { + $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/subfolder/controller/?searchtag=abc']; + + $request = $this->createMock(Request::class); + $request->method('getParam')->with('nb')->willReturn('8'); + $response = new Response(); + + $this->container->sessionManager + ->expects(static::once()) + ->method('setSessionParameter') + ->with(SessionManager::KEY_LINKS_PER_PAGE, 8) + ; + + $result = $this->controller->linksPerPage($request, $response); + + static::assertInstanceOf(Response::class, $result); + static::assertSame(302, $result->getStatusCode()); + static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); + } + + /** + * Link per page - Invalid value, should use default value (20) + */ + public function testLinksPerPageNotValid(): void + { + $request = $this->createMock(Request::class); + $request->method('getParam')->with('nb')->willReturn('test'); + $response = new Response(); + + $this->container->sessionManager + ->expects(static::once()) + ->method('setSessionParameter') + ->with(SessionManager::KEY_LINKS_PER_PAGE, 20) + ; + + $result = $this->controller->linksPerPage($request, $response); + + static::assertInstanceOf(Response::class, $result); + static::assertSame(302, $result->getStatusCode()); + static::assertSame(['/subfolder/'], $result->getHeader('location')); + } +} -- cgit v1.2.3 From 9fbc42294e7667c5ef19cafa0d1fcfbc1c0f36a9 Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Sun, 26 Jul 2020 14:43:10 +0200 Subject: New basePath: fix officiel plugin paths and vintage template --- tests/config/ConfigPluginTest.php | 16 +++++++++++---- .../DeleteBookmarkTest.php | 23 ++++++++++++++++++---- .../controller/admin/PluginsControllerTest.php | 14 +++++++++++++ .../admin/SessionFilterControllerTest.php | 2 +- .../visitor/ShaarliVisitorControllerTest.php | 2 -- tests/plugins/PluginAddlinkTest.php | 4 ++++ 6 files changed, 50 insertions(+), 11 deletions(-) (limited to 'tests') diff --git a/tests/config/ConfigPluginTest.php b/tests/config/ConfigPluginTest.php index d7a70e68..b2cc0045 100644 --- a/tests/config/ConfigPluginTest.php +++ b/tests/config/ConfigPluginTest.php @@ -2,6 +2,7 @@ namespace Shaarli\Config; use Shaarli\Config\Exception\PluginConfigOrderException; +use Shaarli\Plugin\PluginManager; require_once 'application/config/ConfigPlugin.php'; @@ -17,23 +18,30 @@ class ConfigPluginTest extends \PHPUnit\Framework\TestCase */ public function testSavePluginConfigValid() { - $data = array( + $data = [ 'order_plugin1' => 2, // no plugin related 'plugin2' => 0, // new - at the end 'plugin3' => 0, // 2nd 'order_plugin3' => 8, 'plugin4' => 0, // 1st 'order_plugin4' => 5, - ); + ]; - $expected = array( + $expected = [ 'plugin3', 'plugin4', 'plugin2', - ); + ]; + + mkdir($path = __DIR__ . '/folder'); + PluginManager::$PLUGINS_PATH = $path; + array_map(function (string $plugin) use ($path) { touch($path . '/' . $plugin); }, $expected); $out = save_plugin_config($data); $this->assertEquals($expected, $out); + + array_map(function (string $plugin) use ($path) { unlink($path . '/' . $plugin); }, $expected); + rmdir($path); } /** diff --git a/tests/front/controller/admin/ManageShaareControllerTest/DeleteBookmarkTest.php b/tests/front/controller/admin/ManageShaareControllerTest/DeleteBookmarkTest.php index caaf549d..dee622bb 100644 --- a/tests/front/controller/admin/ManageShaareControllerTest/DeleteBookmarkTest.php +++ b/tests/front/controller/admin/ManageShaareControllerTest/DeleteBookmarkTest.php @@ -59,8 +59,12 @@ class DeleteBookmarkTest extends TestCase ->with('raw') ->willReturnCallback(function () use ($bookmark): BookmarkFormatter { $formatter = $this->createMock(BookmarkFormatter::class); - - $formatter->expects(static::once())->method('format')->with($bookmark); + $formatter + ->expects(static::once()) + ->method('format') + ->with($bookmark) + ->willReturn(['formatted' => $bookmark]) + ; return $formatter; }) @@ -70,7 +74,7 @@ class DeleteBookmarkTest extends TestCase $this->container->pluginManager ->expects(static::once()) ->method('executeHooks') - ->with('delete_link') + ->with('delete_link', ['formatted' => $bookmark]) ; $result = $this->controller->deleteBookmark($request, $response); @@ -129,6 +133,9 @@ class DeleteBookmarkTest extends TestCase ->withConsecutive(...array_map(function (Bookmark $bookmark): array { return [$bookmark]; }, $bookmarks)) + ->willReturnOnConsecutiveCalls(...array_map(function (Bookmark $bookmark): array { + return ['formatted' => $bookmark]; + }, $bookmarks)) ; return $formatter; @@ -254,6 +261,9 @@ class DeleteBookmarkTest extends TestCase ->withConsecutive(...array_map(function (Bookmark $bookmark): array { return [$bookmark]; }, $bookmarks)) + ->willReturnOnConsecutiveCalls(...array_map(function (Bookmark $bookmark): array { + return ['formatted' => $bookmark]; + }, $bookmarks)) ; return $formatter; @@ -350,7 +360,12 @@ class DeleteBookmarkTest extends TestCase $this->container->formatterFactory ->expects(static::once()) ->method('getFormatter') - ->willReturn($this->createMock(BookmarkFormatter::class)) + ->willReturnCallback(function (): BookmarkFormatter { + $formatter = $this->createMock(BookmarkFormatter::class); + $formatter->method('format')->willReturn(['formatted']); + + return $formatter; + }) ; $result = $this->controller->deleteBookmark($request, $response); diff --git a/tests/front/controller/admin/PluginsControllerTest.php b/tests/front/controller/admin/PluginsControllerTest.php index ad0cda70..5b59285c 100644 --- a/tests/front/controller/admin/PluginsControllerTest.php +++ b/tests/front/controller/admin/PluginsControllerTest.php @@ -7,6 +7,7 @@ namespace Shaarli\Front\Controller\Admin; use PHPUnit\Framework\TestCase; use Shaarli\Config\ConfigManager; use Shaarli\Front\Exception\WrongTokenException; +use Shaarli\Plugin\PluginManager; use Shaarli\Security\SessionManager; use Slim\Http\Request; use Slim\Http\Response; @@ -15,6 +16,8 @@ class PluginsControllerTest extends TestCase { use FrontAdminControllerMockHelper; + const PLUGIN_NAMES = ['plugin1', 'plugin2', 'plugin3', 'plugin4']; + /** @var PluginsController */ protected $controller; @@ -23,6 +26,17 @@ class PluginsControllerTest extends TestCase $this->createContainer(); $this->controller = new PluginsController($this->container); + + mkdir($path = __DIR__ . '/folder'); + PluginManager::$PLUGINS_PATH = $path; + array_map(function (string $plugin) use ($path) { touch($path . '/' . $plugin); }, static::PLUGIN_NAMES); + } + + public function tearDown() + { + $path = __DIR__ . '/folder'; + array_map(function (string $plugin) use ($path) { unlink($path . '/' . $plugin); }, static::PLUGIN_NAMES); + rmdir($path); } /** diff --git a/tests/front/controller/admin/SessionFilterControllerTest.php b/tests/front/controller/admin/SessionFilterControllerTest.php index 124b0bf2..7d5511ed 100644 --- a/tests/front/controller/admin/SessionFilterControllerTest.php +++ b/tests/front/controller/admin/SessionFilterControllerTest.php @@ -23,7 +23,7 @@ class SessionFilterControllerTest extends TestCase $this->controller = new SessionFilterController($this->container); } - + /** * Visibility - Default call for private filter while logged in without current value */ diff --git a/tests/front/controller/visitor/ShaarliVisitorControllerTest.php b/tests/front/controller/visitor/ShaarliVisitorControllerTest.php index 83d08358..316ce49c 100644 --- a/tests/front/controller/visitor/ShaarliVisitorControllerTest.php +++ b/tests/front/controller/visitor/ShaarliVisitorControllerTest.php @@ -96,8 +96,6 @@ class ShaarliVisitorControllerTest extends TestCase static::assertSame(10, $this->assignedValues['linkcount']); static::assertSame(5, $this->assignedValues['privateLinkcount']); static::assertSame(['error'], $this->assignedValues['plugin_errors']); - static::assertSame('/subfolder', $this->assignedValues['base_path']); - static::assertSame('/subfolder/tpl/default', $this->assignedValues['asset_path']); static::assertSame('templateName', $this->assignedValues['plugins_includes']['render_includes']['target']); static::assertTrue($this->assignedValues['plugins_includes']['render_includes']['loggedin']); diff --git a/tests/plugins/PluginAddlinkTest.php b/tests/plugins/PluginAddlinkTest.php index 4018c1a8..aa5c6988 100644 --- a/tests/plugins/PluginAddlinkTest.php +++ b/tests/plugins/PluginAddlinkTest.php @@ -28,6 +28,7 @@ class PluginAddlinkTest extends \PHPUnit\Framework\TestCase $data = array($str => $str); $data['_PAGE_'] = TemplatePage::LINKLIST; $data['_LOGGEDIN_'] = true; + $data['_BASE_PATH_'] = '/subfolder'; $data = hook_addlink_toolbar_render_header($data); $this->assertEquals($str, $data[$str]); @@ -36,6 +37,8 @@ class PluginAddlinkTest extends \PHPUnit\Framework\TestCase $data = array($str => $str); $data['_PAGE_'] = $str; $data['_LOGGEDIN_'] = true; + $data['_BASE_PATH_'] = '/subfolder'; + $data = hook_addlink_toolbar_render_header($data); $this->assertEquals($str, $data[$str]); $this->assertArrayNotHasKey('fields_toolbar', $data); @@ -50,6 +53,7 @@ class PluginAddlinkTest extends \PHPUnit\Framework\TestCase $data = array($str => $str); $data['_PAGE_'] = TemplatePage::LINKLIST; $data['_LOGGEDIN_'] = false; + $data['_BASE_PATH_'] = '/subfolder'; $data = hook_addlink_toolbar_render_header($data); $this->assertEquals($str, $data[$str]); -- cgit v1.2.3 From 301c7ab1a079d937ab41c6f52b8804e5731008e6 Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Tue, 28 Jul 2020 20:46:11 +0200 Subject: Better support for notes permalink --- tests/api/controllers/links/PostLinkTest.php | 4 ++-- tests/api/controllers/links/PutLinkTest.php | 4 ++-- tests/bookmark/BookmarkFileServiceTest.php | 4 ++-- tests/bookmark/BookmarkTest.php | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) (limited to 'tests') diff --git a/tests/api/controllers/links/PostLinkTest.php b/tests/api/controllers/links/PostLinkTest.php index b2dd09eb..4e791a04 100644 --- a/tests/api/controllers/links/PostLinkTest.php +++ b/tests/api/controllers/links/PostLinkTest.php @@ -131,8 +131,8 @@ class PostLinkTest extends TestCase $this->assertEquals(self::NB_FIELDS_LINK, count($data)); $this->assertEquals(43, $data['id']); $this->assertRegExp('/[\w_-]{6}/', $data['shorturl']); - $this->assertEquals('http://domain.tld/?' . $data['shorturl'], $data['url']); - $this->assertEquals('?' . $data['shorturl'], $data['title']); + $this->assertEquals('http://domain.tld/shaare/' . $data['shorturl'], $data['url']); + $this->assertEquals('/shaare/' . $data['shorturl'], $data['title']); $this->assertEquals('', $data['description']); $this->assertEquals([], $data['tags']); $this->assertEquals(true, $data['private']); diff --git a/tests/api/controllers/links/PutLinkTest.php b/tests/api/controllers/links/PutLinkTest.php index cb63742e..302cac0f 100644 --- a/tests/api/controllers/links/PutLinkTest.php +++ b/tests/api/controllers/links/PutLinkTest.php @@ -114,8 +114,8 @@ class PutLinkTest extends \PHPUnit\Framework\TestCase $this->assertEquals(self::NB_FIELDS_LINK, count($data)); $this->assertEquals($id, $data['id']); $this->assertEquals('WDWyig', $data['shorturl']); - $this->assertEquals('http://domain.tld/?WDWyig', $data['url']); - $this->assertEquals('?WDWyig', $data['title']); + $this->assertEquals('http://domain.tld/shaare/WDWyig', $data['url']); + $this->assertEquals('/shaare/WDWyig', $data['title']); $this->assertEquals('', $data['description']); $this->assertEquals([], $data['tags']); $this->assertEquals(true, $data['private']); diff --git a/tests/bookmark/BookmarkFileServiceTest.php b/tests/bookmark/BookmarkFileServiceTest.php index b19c8250..a8bf47cb 100644 --- a/tests/bookmark/BookmarkFileServiceTest.php +++ b/tests/bookmark/BookmarkFileServiceTest.php @@ -200,7 +200,7 @@ class BookmarkFileServiceTest extends TestCase $bookmark = $this->privateLinkDB->get(43); $this->assertEquals(43, $bookmark->getId()); - $this->assertRegExp('/\?[\w\-]{6}/', $bookmark->getUrl()); + $this->assertRegExp('#/shaare/[\w\-]{6}#', $bookmark->getUrl()); $this->assertRegExp('/[\w\-]{6}/', $bookmark->getShortUrl()); $this->assertEquals($bookmark->getUrl(), $bookmark->getTitle()); $this->assertEmpty($bookmark->getDescription()); @@ -216,7 +216,7 @@ class BookmarkFileServiceTest extends TestCase $bookmark = $this->privateLinkDB->get(43); $this->assertEquals(43, $bookmark->getId()); - $this->assertRegExp('/\?[\w\-]{6}/', $bookmark->getUrl()); + $this->assertRegExp('#/shaare/[\w\-]{6}#', $bookmark->getUrl()); $this->assertRegExp('/[\w\-]{6}/', $bookmark->getShortUrl()); $this->assertEquals($bookmark->getUrl(), $bookmark->getTitle()); $this->assertEmpty($bookmark->getDescription()); diff --git a/tests/bookmark/BookmarkTest.php b/tests/bookmark/BookmarkTest.php index 9a3bbbfc..4b6a3c07 100644 --- a/tests/bookmark/BookmarkTest.php +++ b/tests/bookmark/BookmarkTest.php @@ -124,8 +124,8 @@ class BookmarkTest extends TestCase $this->assertEquals(1, $bookmark->getId()); $this->assertEquals('abc', $bookmark->getShortUrl()); $this->assertEquals($date, $bookmark->getCreated()); - $this->assertEquals('?abc', $bookmark->getUrl()); - $this->assertEquals('?abc', $bookmark->getTitle()); + $this->assertEquals('/shaare/abc', $bookmark->getUrl()); + $this->assertEquals('/shaare/abc', $bookmark->getTitle()); $this->assertEquals('', $bookmark->getDescription()); $this->assertEquals([], $bookmark->getTags()); $this->assertEquals('', $bookmark->getTagsString()); -- cgit v1.2.3 From f7f08ceec1b218e1525153e8bd3d0199f2fb1c9d Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Tue, 28 Jul 2020 22:24:41 +0200 Subject: Fix basePath in unit tests reference DB --- tests/api/controllers/links/GetLinkIdTest.php | 2 +- tests/api/controllers/links/GetLinksTest.php | 2 +- tests/bookmark/BookmarkFileServiceTest.php | 4 ++-- tests/feed/FeedBuilderTest.php | 18 +++++++++--------- tests/netscape/BookmarkExportTest.php | 4 ++-- tests/updater/UpdaterTest.php | 14 ++++++-------- tests/utils/ReferenceLinkDB.php | 8 ++++---- 7 files changed, 25 insertions(+), 27 deletions(-) (limited to 'tests') diff --git a/tests/api/controllers/links/GetLinkIdTest.php b/tests/api/controllers/links/GetLinkIdTest.php index c26411ac..8bb81dc8 100644 --- a/tests/api/controllers/links/GetLinkIdTest.php +++ b/tests/api/controllers/links/GetLinkIdTest.php @@ -102,7 +102,7 @@ class GetLinkIdTest extends \PHPUnit\Framework\TestCase $this->assertEquals($id, $data['id']); // Check link elements - $this->assertEquals('http://domain.tld/?WDWyig', $data['url']); + $this->assertEquals('http://domain.tld/shaare/WDWyig', $data['url']); $this->assertEquals('WDWyig', $data['shorturl']); $this->assertEquals('Link title: @website', $data['title']); $this->assertEquals( diff --git a/tests/api/controllers/links/GetLinksTest.php b/tests/api/controllers/links/GetLinksTest.php index 4e2d55ac..d02e6fad 100644 --- a/tests/api/controllers/links/GetLinksTest.php +++ b/tests/api/controllers/links/GetLinksTest.php @@ -109,7 +109,7 @@ class GetLinksTest extends \PHPUnit\Framework\TestCase // Check first element fields $first = $data[2]; - $this->assertEquals('http://domain.tld/?WDWyig', $first['url']); + $this->assertEquals('http://domain.tld/shaare/WDWyig', $first['url']); $this->assertEquals('WDWyig', $first['shorturl']); $this->assertEquals('Link title: @website', $first['title']); $this->assertEquals( diff --git a/tests/bookmark/BookmarkFileServiceTest.php b/tests/bookmark/BookmarkFileServiceTest.php index a8bf47cb..7b1906d3 100644 --- a/tests/bookmark/BookmarkFileServiceTest.php +++ b/tests/bookmark/BookmarkFileServiceTest.php @@ -340,7 +340,7 @@ class BookmarkFileServiceTest extends TestCase $bookmark = $this->privateLinkDB->get(42); $this->assertEquals(42, $bookmark->getId()); - $this->assertEquals('?WDWyig', $bookmark->getUrl()); + $this->assertEquals('/shaare/WDWyig', $bookmark->getUrl()); $this->assertEquals('1eYJ1Q', $bookmark->getShortUrl()); $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle()); $this->assertEquals('Used to test bookmarks reordering.', $bookmark->getDescription()); @@ -359,7 +359,7 @@ class BookmarkFileServiceTest extends TestCase $bookmark = $this->privateLinkDB->get(42); $this->assertEquals(42, $bookmark->getId()); - $this->assertEquals('?WDWyig', $bookmark->getUrl()); + $this->assertEquals('/shaare/WDWyig', $bookmark->getUrl()); $this->assertEquals('1eYJ1Q', $bookmark->getShortUrl()); $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle()); $this->assertEquals('Used to test bookmarks reordering.', $bookmark->getDescription()); diff --git a/tests/feed/FeedBuilderTest.php b/tests/feed/FeedBuilderTest.php index b2b70b70..5c2aaedb 100644 --- a/tests/feed/FeedBuilderTest.php +++ b/tests/feed/FeedBuilderTest.php @@ -90,15 +90,15 @@ class FeedBuilderTest extends \PHPUnit\Framework\TestCase $link = $data['links'][array_keys($data['links'])[2]]; $this->assertEquals(41, $link['id']); $this->assertEquals(DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); - $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); - $this->assertEquals('http://host.tld/?WDWyig', $link['url']); + $this->assertEquals('http://host.tld/shaare/WDWyig', $link['guid']); + $this->assertEquals('http://host.tld/shaare/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->assertContains('http://host.tld/shaare/WDWyig', $link['description']); $this->assertEquals(1, count($link['taglist'])); $this->assertEquals('sTuff', $link['taglist'][0]); @@ -198,15 +198,15 @@ class FeedBuilderTest extends \PHPUnit\Framework\TestCase $link = $data['links'][array_keys($data['links'])[2]]; $this->assertEquals(41, $link['id']); $this->assertEquals(DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20150310_114651'), $link['created']); - $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); - $this->assertEquals('http://host.tld/?WDWyig', $link['url']); + $this->assertEquals('http://host.tld/shaare/WDWyig', $link['guid']); + $this->assertEquals('http://host.tld/shaare/WDWyig', $link['url']); $this->assertContains('Direct link', $link['description']); - $this->assertContains('http://host.tld/?WDWyig', $link['description']); + $this->assertContains('http://host.tld/shaare/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(Bookmark::LINK_DATE_FORMAT, '20150310_114633'), $link['created']); - $this->assertEquals('http://host.tld/?RttfEw', $link['guid']); + $this->assertEquals('http://host.tld/shaare/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']); @@ -271,8 +271,8 @@ class FeedBuilderTest extends \PHPUnit\Framework\TestCase // 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->assertEquals('http://host.tld:8080/~user/shaarli/shaare/WDWyig', $link['guid']); + $this->assertEquals('http://host.tld:8080/~user/shaarli/shaare/WDWyig', $link['url']); $this->assertContains('http://host.tld:8080/~user/shaarli/./add-tag/hashtag', $link['description']); } } diff --git a/tests/netscape/BookmarkExportTest.php b/tests/netscape/BookmarkExportTest.php index 344c1dc0..509da51d 100644 --- a/tests/netscape/BookmarkExportTest.php +++ b/tests/netscape/BookmarkExportTest.php @@ -177,7 +177,7 @@ class BookmarkExportTest extends TestCase '' ); $this->assertEquals( - '?WDWyig', + '/shaare/WDWyig', $links[2]['url'] ); } @@ -195,7 +195,7 @@ class BookmarkExportTest extends TestCase $indexUrl ); $this->assertEquals( - $indexUrl . '?WDWyig', + $indexUrl . 'shaare/WDWyig', $links[2]['url'] ); } diff --git a/tests/updater/UpdaterTest.php b/tests/updater/UpdaterTest.php index c801d451..a7dd70bf 100644 --- a/tests/updater/UpdaterTest.php +++ b/tests/updater/UpdaterTest.php @@ -2,6 +2,7 @@ namespace Shaarli\Updater; use Exception; +use PHPUnit\Framework\TestCase; use Shaarli\Bookmark\BookmarkFileService; use Shaarli\Bookmark\BookmarkServiceInterface; use Shaarli\Config\ConfigManager; @@ -12,7 +13,7 @@ use Shaarli\History; * Class UpdaterTest. * Runs unit tests against the updater class. */ -class UpdaterTest extends \PHPUnit\Framework\TestCase +class UpdaterTest extends TestCase { /** * @var string Path to test datastore. @@ -194,7 +195,6 @@ class UpdaterTest extends \PHPUnit\Framework\TestCase public function testUpdateMethodRelativeHomeLinkDoNotRename(): void { - $this->updater->setBasePath('/subfolder'); $this->conf->set('general.header_link', '~/my-blog'); $this->updater->updateMethodRelativeHomeLink(); @@ -204,8 +204,6 @@ class UpdaterTest extends \PHPUnit\Framework\TestCase public function testUpdateMethodMigrateExistingNotesUrl(): void { - $this->updater->setBasePath('/subfolder'); - $this->updater->updateMethodMigrateExistingNotesUrl(); static::assertSame($this->refDB->getLinks()[0]->getUrl(), $this->bookmarkService->get(0)->getUrl()); @@ -215,9 +213,9 @@ class UpdaterTest extends \PHPUnit\Framework\TestCase static::assertSame($this->refDB->getLinks()[7]->getUrl(), $this->bookmarkService->get(7)->getUrl()); static::assertSame($this->refDB->getLinks()[8]->getUrl(), $this->bookmarkService->get(8)->getUrl()); static::assertSame($this->refDB->getLinks()[9]->getUrl(), $this->bookmarkService->get(9)->getUrl()); - static::assertSame('/subfolder/shaare/WDWyig', $this->bookmarkService->get(42)->getUrl()); - static::assertSame('/subfolder/shaare/WDWyig', $this->bookmarkService->get(41)->getUrl()); - static::assertSame('/subfolder/shaare/0gCTjQ', $this->bookmarkService->get(10)->getUrl()); - static::assertSame('/subfolder/shaare/PCRizQ', $this->bookmarkService->get(11)->getUrl()); + static::assertSame('/shaare/WDWyig', $this->bookmarkService->get(42)->getUrl()); + static::assertSame('/shaare/WDWyig', $this->bookmarkService->get(41)->getUrl()); + static::assertSame('/shaare/0gCTjQ', $this->bookmarkService->get(10)->getUrl()); + static::assertSame('/shaare/PCRizQ', $this->bookmarkService->get(11)->getUrl()); } } diff --git a/tests/utils/ReferenceLinkDB.php b/tests/utils/ReferenceLinkDB.php index 0095f5a1..fc3cb109 100644 --- a/tests/utils/ReferenceLinkDB.php +++ b/tests/utils/ReferenceLinkDB.php @@ -30,7 +30,7 @@ class ReferenceLinkDB $this->addLink( 11, 'Pined older', - '?PCRizQ', + '/shaare/PCRizQ', 'This is an older pinned link', 0, DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20100309_101010'), @@ -43,7 +43,7 @@ class ReferenceLinkDB $this->addLink( 10, 'Pined', - '?0gCTjQ', + '/shaare/0gCTjQ', 'This is a pinned link', 0, DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20121207_152312'), @@ -56,7 +56,7 @@ class ReferenceLinkDB $this->addLink( 41, 'Link title: @website', - '?WDWyig', + '/shaare/WDWyig', 'Stallman has a beard and is part of the Free Software Foundation (or not). Seriously, read this. #hashtag', 0, DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20150310_114651'), @@ -68,7 +68,7 @@ class ReferenceLinkDB $this->addLink( 42, 'Note: I have a big ID but an old date', - '?WDWyig', + '/shaare/WDWyig', 'Used to test bookmarks reordering.', 0, DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20100310_101010'), -- cgit v1.2.3 From d6e5f04d3987e498c5cb859eed6bff33d67949df Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Sat, 1 Aug 2020 11:10:57 +0200 Subject: Remove anonymous permission and initialize bookmarks on login --- tests/bookmark/BookmarkInitializerTest.php | 14 +++++++++----- tests/front/controller/visitor/InstallControllerTest.php | 3 --- 2 files changed, 9 insertions(+), 8 deletions(-) (limited to 'tests') diff --git a/tests/bookmark/BookmarkInitializerTest.php b/tests/bookmark/BookmarkInitializerTest.php index d23eb069..3906cc7f 100644 --- a/tests/bookmark/BookmarkInitializerTest.php +++ b/tests/bookmark/BookmarkInitializerTest.php @@ -3,7 +3,6 @@ namespace Shaarli\Bookmark; use PHPUnit\Framework\TestCase; -use ReferenceLinkDB; use Shaarli\Config\ConfigManager; use Shaarli\History; @@ -54,9 +53,9 @@ class BookmarkInitializerTest extends TestCase } /** - * Test initialize() with an empty data store. + * Test initialize() with a data store containing bookmarks. */ - public function testInitializeEmptyDataStore() + public function testInitializeNotEmptyDataStore(): void { $refDB = new \ReferenceLinkDB(); $refDB->write(self::$testDatastore); @@ -79,6 +78,8 @@ class BookmarkInitializerTest extends TestCase ); $this->assertFalse($bookmark->isPrivate()); + $this->bookmarkService->save(); + // Reload from file $this->bookmarkService = new BookmarkFileService($this->conf, $this->history, true); $this->assertEquals($refDB->countLinks() + 2, $this->bookmarkService->count()); @@ -97,10 +98,13 @@ class BookmarkInitializerTest extends TestCase } /** - * Test initialize() with a data store containing bookmarks. + * Test initialize() with an a non existent datastore file . */ - public function testInitializeNotEmptyDataStore() + public function testInitializeNonExistentDataStore(): void { + $this->conf->set('resource.datastore', static::$testDatastore . '_empty'); + $this->bookmarkService = new BookmarkFileService($this->conf, $this->history, true); + $this->initializer->initialize(); $this->assertEquals(2, $this->bookmarkService->count()); diff --git a/tests/front/controller/visitor/InstallControllerTest.php b/tests/front/controller/visitor/InstallControllerTest.php index 089c64ac..3b855365 100644 --- a/tests/front/controller/visitor/InstallControllerTest.php +++ b/tests/front/controller/visitor/InstallControllerTest.php @@ -224,9 +224,6 @@ class InstallControllerTest extends TestCase ; $this->container->conf->expects(static::once())->method('write'); - $this->container->bookmarkService->expects(static::once())->method('count')->willReturn(0); - $this->container->bookmarkService->expects(static::once())->method('initialize'); - $this->container->sessionManager ->expects(static::once()) ->method('setSessionParameter') -- cgit v1.2.3 From bedbb845eec20363b928b424143787dbe988eefe Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Thu, 13 Aug 2020 11:08:13 +0200 Subject: Move all admin controller into a dedicated group Also handle authentication check in a new middleware for the admin group. --- tests/front/ShaarliAdminMiddlewareTest.php | 100 +++++++++++++++++++++ tests/front/ShaarliMiddlewareTest.php | 2 +- .../admin/SessionFilterControllerTest.php | 51 ----------- .../admin/ShaarliAdminControllerTest.php | 15 ---- .../visitor/PublicSessionFilterControllerTest.php | 51 +++++++++++ tests/legacy/LegacyControllerTest.php | 4 +- 6 files changed, 154 insertions(+), 69 deletions(-) create mode 100644 tests/front/ShaarliAdminMiddlewareTest.php (limited to 'tests') diff --git a/tests/front/ShaarliAdminMiddlewareTest.php b/tests/front/ShaarliAdminMiddlewareTest.php new file mode 100644 index 00000000..7451330b --- /dev/null +++ b/tests/front/ShaarliAdminMiddlewareTest.php @@ -0,0 +1,100 @@ +container = $this->createMock(ShaarliContainer::class); + + touch(static::TMP_MOCK_FILE); + + $this->container->conf = $this->createMock(ConfigManager::class); + $this->container->conf->method('getConfigFileExt')->willReturn(static::TMP_MOCK_FILE); + + $this->container->loginManager = $this->createMock(LoginManager::class); + $this->container->updater = $this->createMock(Updater::class); + + $this->container->environment = ['REQUEST_URI' => 'http://shaarli/subfolder/path']; + + $this->middleware = new ShaarliAdminMiddleware($this->container); + } + + public function tearDown(): void + { + unlink(static::TMP_MOCK_FILE); + } + + /** + * Try to access an admin controller while logged out -> redirected to login page. + */ + public function testMiddlewareWhileLoggedOut(): void + { + $this->container->loginManager->expects(static::once())->method('isLoggedIn')->willReturn(false); + + $request = $this->createMock(Request::class); + $request->method('getUri')->willReturnCallback(function (): Uri { + $uri = $this->createMock(Uri::class); + $uri->method('getBasePath')->willReturn('/subfolder'); + + return $uri; + }); + + $response = new Response(); + + /** @var Response $result */ + $result = $this->middleware->__invoke($request, $response, function () {}); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame( + '/subfolder/login?returnurl=' . urlencode('http://shaarli/subfolder/path'), + $result->getHeader('location')[0] + ); + } + + /** + * Process controller while logged in. + */ + public function testMiddlewareWhileLoggedIn(): void + { + $this->container->loginManager->method('isLoggedIn')->willReturn(true); + + $request = $this->createMock(Request::class); + $request->method('getUri')->willReturnCallback(function (): Uri { + $uri = $this->createMock(Uri::class); + $uri->method('getBasePath')->willReturn('/subfolder'); + + return $uri; + }); + + $response = new Response(); + $controller = function (Request $request, Response $response): Response { + return $response->withStatus(418); // I'm a tea pot + }; + + /** @var Response $result */ + $result = $this->middleware->__invoke($request, $response, $controller); + + static::assertSame(418, $result->getStatusCode()); + } +} diff --git a/tests/front/ShaarliMiddlewareTest.php b/tests/front/ShaarliMiddlewareTest.php index 09bebd04..d435f506 100644 --- a/tests/front/ShaarliMiddlewareTest.php +++ b/tests/front/ShaarliMiddlewareTest.php @@ -43,7 +43,7 @@ class ShaarliMiddlewareTest extends TestCase $this->middleware = new ShaarliMiddleware($this->container); } - public function tearDown() + public function tearDown(): void { unlink(static::TMP_MOCK_FILE); } diff --git a/tests/front/controller/admin/SessionFilterControllerTest.php b/tests/front/controller/admin/SessionFilterControllerTest.php index 7d5511ed..d306c6e9 100644 --- a/tests/front/controller/admin/SessionFilterControllerTest.php +++ b/tests/front/controller/admin/SessionFilterControllerTest.php @@ -174,55 +174,4 @@ class SessionFilterControllerTest extends TestCase static::assertSame(302, $result->getStatusCode()); static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); } - - /** - * Untagged only - valid call - */ - public function testUntaggedOnly(): void - { - $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/subfolder/controller/?searchtag=abc']; - - $request = $this->createMock(Request::class); - $response = new Response(); - - $this->container->sessionManager - ->expects(static::once()) - ->method('setSessionParameter') - ->with(SessionManager::KEY_UNTAGGED_ONLY, true) - ; - - $result = $this->controller->untaggedOnly($request, $response); - - static::assertInstanceOf(Response::class, $result); - static::assertSame(302, $result->getStatusCode()); - static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); - } - - /** - * Untagged only - toggle off - */ - public function testUntaggedOnlyToggleOff(): void - { - $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/subfolder/controller/?searchtag=abc']; - - $request = $this->createMock(Request::class); - $response = new Response(); - - $this->container->sessionManager - ->method('getSessionParameter') - ->with(SessionManager::KEY_UNTAGGED_ONLY) - ->willReturn(true) - ; - $this->container->sessionManager - ->expects(static::once()) - ->method('setSessionParameter') - ->with(SessionManager::KEY_UNTAGGED_ONLY, false) - ; - - $result = $this->controller->untaggedOnly($request, $response); - - static::assertInstanceOf(Response::class, $result); - static::assertSame(302, $result->getStatusCode()); - static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); - } } diff --git a/tests/front/controller/admin/ShaarliAdminControllerTest.php b/tests/front/controller/admin/ShaarliAdminControllerTest.php index 7c5f50a6..fff427cb 100644 --- a/tests/front/controller/admin/ShaarliAdminControllerTest.php +++ b/tests/front/controller/admin/ShaarliAdminControllerTest.php @@ -5,9 +5,7 @@ declare(strict_types=1); namespace Shaarli\Front\Controller\Admin; use PHPUnit\Framework\TestCase; -use Shaarli\Front\Exception\UnauthorizedException; use Shaarli\Front\Exception\WrongTokenException; -use Shaarli\Security\LoginManager; use Shaarli\Security\SessionManager; use Slim\Http\Request; @@ -52,19 +50,6 @@ class ShaarliAdminControllerTest extends TestCase }; } - /** - * Creating an instance of an admin controller while logged out should raise an exception. - */ - public function testInstantiateWhileLoggedOut(): void - { - $this->expectException(UnauthorizedException::class); - - $this->container->loginManager = $this->createMock(LoginManager::class); - $this->container->loginManager->method('isLoggedIn')->willReturn(false); - - $this->controller = new class($this->container) extends ShaarliAdminController {}; - } - /** * Trigger controller's checkToken with a valid token. */ diff --git a/tests/front/controller/visitor/PublicSessionFilterControllerTest.php b/tests/front/controller/visitor/PublicSessionFilterControllerTest.php index 3aa1cb99..06352750 100644 --- a/tests/front/controller/visitor/PublicSessionFilterControllerTest.php +++ b/tests/front/controller/visitor/PublicSessionFilterControllerTest.php @@ -68,4 +68,55 @@ class PublicSessionFilterControllerTest extends TestCase static::assertSame(302, $result->getStatusCode()); static::assertSame(['/subfolder/'], $result->getHeader('location')); } + + /** + * Untagged only - valid call + */ + public function testUntaggedOnly(): void + { + $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/subfolder/controller/?searchtag=abc']; + + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->sessionManager + ->expects(static::once()) + ->method('setSessionParameter') + ->with(SessionManager::KEY_UNTAGGED_ONLY, true) + ; + + $result = $this->controller->untaggedOnly($request, $response); + + static::assertInstanceOf(Response::class, $result); + static::assertSame(302, $result->getStatusCode()); + static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); + } + + /** + * Untagged only - toggle off + */ + public function testUntaggedOnlyToggleOff(): void + { + $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/subfolder/controller/?searchtag=abc']; + + $request = $this->createMock(Request::class); + $response = new Response(); + + $this->container->sessionManager + ->method('getSessionParameter') + ->with(SessionManager::KEY_UNTAGGED_ONLY) + ->willReturn(true) + ; + $this->container->sessionManager + ->expects(static::once()) + ->method('setSessionParameter') + ->with(SessionManager::KEY_UNTAGGED_ONLY, false) + ; + + $result = $this->controller->untaggedOnly($request, $response); + + static::assertInstanceOf(Response::class, $result); + static::assertSame(302, $result->getStatusCode()); + static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location')); + } } diff --git a/tests/legacy/LegacyControllerTest.php b/tests/legacy/LegacyControllerTest.php index ff4520a3..759a5b2a 100644 --- a/tests/legacy/LegacyControllerTest.php +++ b/tests/legacy/LegacyControllerTest.php @@ -73,8 +73,8 @@ class LegacyControllerTest extends TestCase ['addlink', [], '/login', false], ['login', [], '/login', true], ['login', [], '/login', false], - ['logout', [], '/logout', true], - ['logout', [], '/logout', false], + ['logout', [], '/admin/logout', true], + ['logout', [], '/admin/logout', false], ['picwall', [], '/picture-wall', false], ['picwall', [], '/picture-wall', true], ['tagcloud', [], '/tags/cloud', false], -- cgit v1.2.3 From 0c6fdbe12bbbb336348666b14b82096f24d5858b Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Fri, 21 Aug 2020 10:50:44 +0200 Subject: Move error handling to dedicated controller instead of middleware --- tests/front/ShaarliMiddlewareTest.php | 29 +++++---- .../controller/visitor/ErrorControllerTest.php | 70 ++++++++++++++++++++++ 2 files changed, 84 insertions(+), 15 deletions(-) create mode 100644 tests/front/controller/visitor/ErrorControllerTest.php (limited to 'tests') diff --git a/tests/front/ShaarliMiddlewareTest.php b/tests/front/ShaarliMiddlewareTest.php index d435f506..05aa34a9 100644 --- a/tests/front/ShaarliMiddlewareTest.php +++ b/tests/front/ShaarliMiddlewareTest.php @@ -74,7 +74,8 @@ class ShaarliMiddlewareTest extends TestCase } /** - * Test middleware execution with controller throwing a known front exception + * Test middleware execution with controller throwing a known front exception. + * The exception should be thrown to be later handled by the error handler. */ public function testMiddlewareExecutionWithFrontException(): void { @@ -99,16 +100,14 @@ class ShaarliMiddlewareTest extends TestCase }); $this->container->pageBuilder = $pageBuilder; - /** @var Response $result */ - $result = $this->middleware->__invoke($request, $response, $controller); + $this->expectException(LoginBannedException::class); - static::assertInstanceOf(Response::class, $result); - static::assertSame(401, $result->getStatusCode()); - static::assertContains('error', (string) $result->getBody()); + $this->middleware->__invoke($request, $response, $controller); } /** * Test middleware execution with controller throwing a not authorized exception + * The middle should send a redirection response to the login page. */ public function testMiddlewareExecutionWithUnauthorizedException(): void { @@ -136,9 +135,10 @@ class ShaarliMiddlewareTest extends TestCase } /** - * Test middleware execution with controller throwing a not authorized exception + * Test middleware execution with controller throwing a not authorized exception. + * The exception should be thrown to be later handled by the error handler. */ - public function testMiddlewareExecutionWithServerExceptionWith(): void + public function testMiddlewareExecutionWithServerException(): void { $request = $this->createMock(Request::class); $request->method('getUri')->willReturnCallback(function (): Uri { @@ -148,9 +148,11 @@ class ShaarliMiddlewareTest extends TestCase return $uri; }); + $dummyException = new class() extends \Exception {}; + $response = new Response(); - $controller = function (): void { - throw new \Exception(); + $controller = function () use ($dummyException): void { + throw $dummyException; }; $parameters = []; @@ -165,12 +167,9 @@ class ShaarliMiddlewareTest extends TestCase }) ; - /** @var Response $result */ - $result = $this->middleware->__invoke($request, $response, $controller); + $this->expectException(get_class($dummyException)); - static::assertSame(500, $result->getStatusCode()); - static::assertContains('error', (string) $result->getBody()); - static::assertSame('An unexpected error occurred.', $parameters['message']); + $this->middleware->__invoke($request, $response, $controller); } public function testMiddlewareExecutionWithUpdates(): void diff --git a/tests/front/controller/visitor/ErrorControllerTest.php b/tests/front/controller/visitor/ErrorControllerTest.php new file mode 100644 index 00000000..e497bfef --- /dev/null +++ b/tests/front/controller/visitor/ErrorControllerTest.php @@ -0,0 +1,70 @@ +createContainer(); + + $this->controller = new ErrorController($this->container); + } + + /** + * Test displaying error with a ShaarliFrontException: display exception message and use its code for HTTTP code + */ + public function testDisplayFrontExceptionError(): void + { + $request = $this->createMock(Request::class); + $response = new Response(); + + $message = 'error message'; + $errorCode = 418; + + // Save RainTPL assigned variables + $assignedVariables = []; + $this->assignTemplateVars($assignedVariables); + + $result = ($this->controller)( + $request, + $response, + new class($message, $errorCode) extends ShaarliFrontException {} + ); + + static::assertSame($errorCode, $result->getStatusCode()); + static::assertSame($message, $assignedVariables['message']); + static::assertArrayNotHasKey('stacktrace', $assignedVariables); + } + + /** + * Test displaying error with any exception (no debug): only display an error occurred with HTTP 500. + */ + public function testDisplayAnyExceptionErrorNoDebug(): void + { + $request = $this->createMock(Request::class); + $response = new Response(); + + // Save RainTPL assigned variables + $assignedVariables = []; + $this->assignTemplateVars($assignedVariables); + + $result = ($this->controller)($request, $response, new \Exception('abc')); + + static::assertSame(500, $result->getStatusCode()); + static::assertSame('An unexpected error occurred.', $assignedVariables['message']); + static::assertArrayNotHasKey('stacktrace', $assignedVariables); + } +} -- cgit v1.2.3