aboutsummaryrefslogtreecommitdiffhomepage
path: root/tests/front/controller/visitor
diff options
context:
space:
mode:
Diffstat (limited to 'tests/front/controller/visitor')
-rw-r--r--tests/front/controller/visitor/BookmarkListControllerTest.php532
-rw-r--r--tests/front/controller/visitor/DailyControllerTest.php716
-rw-r--r--tests/front/controller/visitor/ErrorControllerTest.php70
-rw-r--r--tests/front/controller/visitor/ErrorNotFoundControllerTest.php81
-rw-r--r--tests/front/controller/visitor/FeedControllerTest.php151
-rw-r--r--tests/front/controller/visitor/FrontControllerMockHelper.php118
-rw-r--r--tests/front/controller/visitor/InstallControllerTest.php304
-rw-r--r--tests/front/controller/visitor/LoginControllerTest.php404
-rw-r--r--tests/front/controller/visitor/OpenSearchControllerTest.php44
-rw-r--r--tests/front/controller/visitor/PictureWallControllerTest.php123
-rw-r--r--tests/front/controller/visitor/PublicSessionFilterControllerTest.php122
-rw-r--r--tests/front/controller/visitor/ShaarliVisitorControllerTest.php246
-rw-r--r--tests/front/controller/visitor/TagCloudControllerTest.php381
-rw-r--r--tests/front/controller/visitor/TagControllerTest.php215
14 files changed, 3507 insertions, 0 deletions
diff --git a/tests/front/controller/visitor/BookmarkListControllerTest.php b/tests/front/controller/visitor/BookmarkListControllerTest.php
new file mode 100644
index 00000000..5cbc8c73
--- /dev/null
+++ b/tests/front/controller/visitor/BookmarkListControllerTest.php
@@ -0,0 +1,532 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Bookmark\Bookmark;
8use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
9use Shaarli\Config\ConfigManager;
10use Shaarli\Security\LoginManager;
11use Shaarli\TestCase;
12use Shaarli\Thumbnailer;
13use Slim\Http\Request;
14use Slim\Http\Response;
15
16class BookmarkListControllerTest extends TestCase
17{
18 use FrontControllerMockHelper;
19
20 /** @var BookmarkListController */
21 protected $controller;
22
23 public function setUp(): void
24 {
25 $this->createContainer();
26
27 $this->controller = new BookmarkListController($this->container);
28 }
29
30 /**
31 * Test rendering list of bookmarks with default parameters (first page).
32 */
33 public function testIndexDefaultFirstPage(): void
34 {
35 $assignedVariables = [];
36 $this->assignTemplateVars($assignedVariables);
37
38 $request = $this->createMock(Request::class);
39 $response = new Response();
40
41 $this->container->bookmarkService
42 ->expects(static::once())
43 ->method('search')
44 ->with(
45 ['searchtags' => '', 'searchterm' => ''],
46 null,
47 false,
48 false
49 )
50 ->willReturn([
51 (new Bookmark())->setId(1)->setUrl('http://url1.tld')->setTitle('Title 1'),
52 (new Bookmark())->setId(2)->setUrl('http://url2.tld')->setTitle('Title 2'),
53 (new Bookmark())->setId(3)->setUrl('http://url3.tld')->setTitle('Title 3'),
54 ]
55 );
56
57 $this->container->sessionManager
58 ->method('getSessionParameter')
59 ->willReturnCallback(function (string $parameter, $default = null) {
60 if ('LINKS_PER_PAGE' === $parameter) {
61 return 2;
62 }
63
64 return $default;
65 })
66 ;
67
68 $result = $this->controller->index($request, $response);
69
70 static::assertSame(200, $result->getStatusCode());
71 static::assertSame('linklist', (string) $result->getBody());
72
73 static::assertSame('Shaarli', $assignedVariables['pagetitle']);
74 static::assertSame('?page=2', $assignedVariables['previous_page_url']);
75 static::assertSame('', $assignedVariables['next_page_url']);
76 static::assertSame(2, $assignedVariables['page_max']);
77 static::assertSame('', $assignedVariables['search_tags']);
78 static::assertSame(3, $assignedVariables['result_count']);
79 static::assertSame(1, $assignedVariables['page_current']);
80 static::assertSame('', $assignedVariables['search_term']);
81 static::assertNull($assignedVariables['visibility']);
82 static::assertCount(2, $assignedVariables['links']);
83
84 $link = $assignedVariables['links'][0];
85
86 static::assertSame(1, $link['id']);
87 static::assertSame('http://url1.tld', $link['url']);
88 static::assertSame('Title 1', $link['title']);
89
90 $link = $assignedVariables['links'][1];
91
92 static::assertSame(2, $link['id']);
93 static::assertSame('http://url2.tld', $link['url']);
94 static::assertSame('Title 2', $link['title']);
95 }
96
97 /**
98 * Test rendering list of bookmarks with default parameters (second page).
99 */
100 public function testIndexDefaultSecondPage(): void
101 {
102 $assignedVariables = [];
103 $this->assignTemplateVars($assignedVariables);
104
105 $request = $this->createMock(Request::class);
106 $request->method('getParam')->willReturnCallback(function (string $key) {
107 if ('page' === $key) {
108 return '2';
109 }
110
111 return null;
112 });
113 $response = new Response();
114
115 $this->container->bookmarkService
116 ->expects(static::once())
117 ->method('search')
118 ->with(
119 ['searchtags' => '', 'searchterm' => ''],
120 null,
121 false,
122 false
123 )
124 ->willReturn([
125 (new Bookmark())->setId(1)->setUrl('http://url1.tld')->setTitle('Title 1'),
126 (new Bookmark())->setId(2)->setUrl('http://url2.tld')->setTitle('Title 2'),
127 (new Bookmark())->setId(3)->setUrl('http://url3.tld')->setTitle('Title 3'),
128 ])
129 ;
130
131 $this->container->sessionManager
132 ->method('getSessionParameter')
133 ->willReturnCallback(function (string $parameter, $default = null) {
134 if ('LINKS_PER_PAGE' === $parameter) {
135 return 2;
136 }
137
138 return $default;
139 })
140 ;
141
142 $result = $this->controller->index($request, $response);
143
144 static::assertSame(200, $result->getStatusCode());
145 static::assertSame('linklist', (string) $result->getBody());
146
147 static::assertSame('Shaarli', $assignedVariables['pagetitle']);
148 static::assertSame('', $assignedVariables['previous_page_url']);
149 static::assertSame('?page=1', $assignedVariables['next_page_url']);
150 static::assertSame(2, $assignedVariables['page_max']);
151 static::assertSame('', $assignedVariables['search_tags']);
152 static::assertSame(3, $assignedVariables['result_count']);
153 static::assertSame(2, $assignedVariables['page_current']);
154 static::assertSame('', $assignedVariables['search_term']);
155 static::assertNull($assignedVariables['visibility']);
156 static::assertCount(1, $assignedVariables['links']);
157
158 $link = $assignedVariables['links'][2];
159
160 static::assertSame(3, $link['id']);
161 static::assertSame('http://url3.tld', $link['url']);
162 static::assertSame('Title 3', $link['title']);
163 }
164
165 /**
166 * Test rendering list of bookmarks with filters.
167 */
168 public function testIndexDefaultWithFilters(): void
169 {
170 $assignedVariables = [];
171 $this->assignTemplateVars($assignedVariables);
172
173 $request = $this->createMock(Request::class);
174 $request->method('getParam')->willReturnCallback(function (string $key) {
175 if ('searchtags' === $key) {
176 return 'abc def';
177 }
178 if ('searchterm' === $key) {
179 return 'ghi jkl';
180 }
181
182 return null;
183 });
184 $response = new Response();
185
186 $this->container->sessionManager
187 ->method('getSessionParameter')
188 ->willReturnCallback(function (string $key, $default) {
189 if ('LINKS_PER_PAGE' === $key) {
190 return 2;
191 }
192 if ('visibility' === $key) {
193 return 'private';
194 }
195 if ('untaggedonly' === $key) {
196 return true;
197 }
198
199 return $default;
200 })
201 ;
202
203 $this->container->bookmarkService
204 ->expects(static::once())
205 ->method('search')
206 ->with(
207 ['searchtags' => 'abc def', 'searchterm' => 'ghi jkl'],
208 'private',
209 false,
210 true
211 )
212 ->willReturn([
213 (new Bookmark())->setId(1)->setUrl('http://url1.tld')->setTitle('Title 1'),
214 (new Bookmark())->setId(2)->setUrl('http://url2.tld')->setTitle('Title 2'),
215 (new Bookmark())->setId(3)->setUrl('http://url3.tld')->setTitle('Title 3'),
216 ])
217 ;
218
219 $result = $this->controller->index($request, $response);
220
221 static::assertSame(200, $result->getStatusCode());
222 static::assertSame('linklist', (string) $result->getBody());
223
224 static::assertSame('Search: ghi jkl [abc] [def] - Shaarli', $assignedVariables['pagetitle']);
225 static::assertSame('?page=2&searchterm=ghi+jkl&searchtags=abc+def', $assignedVariables['previous_page_url']);
226 }
227
228 /**
229 * Test displaying a permalink with valid parameters
230 */
231 public function testPermalinkValid(): void
232 {
233 $hash = 'abcdef';
234
235 $assignedVariables = [];
236 $this->assignTemplateVars($assignedVariables);
237
238 $request = $this->createMock(Request::class);
239 $response = new Response();
240
241 $this->container->bookmarkService
242 ->expects(static::once())
243 ->method('findByHash')
244 ->with($hash)
245 ->willReturn((new Bookmark())->setId(123)->setTitle('Title 1')->setUrl('http://url1.tld'))
246 ;
247
248 $result = $this->controller->permalink($request, $response, ['hash' => $hash]);
249
250 static::assertSame(200, $result->getStatusCode());
251 static::assertSame('linklist', (string) $result->getBody());
252
253 static::assertSame('Title 1 - Shaarli', $assignedVariables['pagetitle']);
254 static::assertCount(1, $assignedVariables['links']);
255
256 $link = $assignedVariables['links'][0];
257
258 static::assertSame(123, $link['id']);
259 static::assertSame('http://url1.tld', $link['url']);
260 static::assertSame('Title 1', $link['title']);
261 }
262
263 /**
264 * Test displaying a permalink with an unknown small hash : renders a 404 template error
265 */
266 public function testPermalinkNotFound(): void
267 {
268 $hash = 'abcdef';
269
270 $assignedVariables = [];
271 $this->assignTemplateVars($assignedVariables);
272
273 $request = $this->createMock(Request::class);
274 $response = new Response();
275
276 $this->container->bookmarkService
277 ->expects(static::once())
278 ->method('findByHash')
279 ->with($hash)
280 ->willThrowException(new BookmarkNotFoundException())
281 ;
282
283 $result = $this->controller->permalink($request, $response, ['hash' => $hash]);
284
285 static::assertSame(200, $result->getStatusCode());
286 static::assertSame('404', (string) $result->getBody());
287
288 static::assertSame(
289 'The link you are trying to reach does not exist or has been deleted.',
290 $assignedVariables['error_message']
291 );
292 }
293
294 /**
295 * Test GET /shaare/{hash}?key={key} - Find a link by hash using a private link.
296 */
297 public function testPermalinkWithPrivateKey(): void
298 {
299 $hash = 'abcdef';
300 $privateKey = 'this is a private key';
301
302 $assignedVariables = [];
303 $this->assignTemplateVars($assignedVariables);
304
305 $request = $this->createMock(Request::class);
306 $request->method('getParam')->willReturnCallback(function (string $key, $default = null) use ($privateKey) {
307 return $key === 'key' ? $privateKey : $default;
308 });
309 $response = new Response();
310
311 $this->container->bookmarkService
312 ->expects(static::once())
313 ->method('findByHash')
314 ->with($hash, $privateKey)
315 ->willReturn((new Bookmark())->setId(123)->setTitle('Title 1')->setUrl('http://url1.tld'))
316 ;
317
318 $result = $this->controller->permalink($request, $response, ['hash' => $hash]);
319
320 static::assertSame(200, $result->getStatusCode());
321 static::assertSame('linklist', (string) $result->getBody());
322 static::assertCount(1, $assignedVariables['links']);
323 }
324
325 /**
326 * Test getting link list with thumbnail updates.
327 * -> 2 thumbnails update, only 1 datastore write
328 */
329 public function testThumbnailUpdateFromLinkList(): void
330 {
331 $request = $this->createMock(Request::class);
332 $response = new Response();
333
334 $this->container->loginManager = $this->createMock(LoginManager::class);
335 $this->container->loginManager->method('isLoggedIn')->willReturn(true);
336
337 $this->container->conf = $this->createMock(ConfigManager::class);
338 $this->container->conf
339 ->method('get')
340 ->willReturnCallback(function (string $key, $default) {
341 if ($key === 'thumbnails.mode') {
342 return Thumbnailer::MODE_ALL;
343 } elseif ($key === 'general.enable_async_metadata') {
344 return false;
345 }
346
347 return $default;
348 })
349 ;
350
351 $this->container->thumbnailer = $this->createMock(Thumbnailer::class);
352 $this->container->thumbnailer
353 ->expects(static::exactly(2))
354 ->method('get')
355 ->withConsecutive(['https://url2.tld'], ['https://url4.tld'])
356 ;
357
358 $this->container->bookmarkService
359 ->expects(static::once())
360 ->method('search')
361 ->willReturn([
362 (new Bookmark())->setId(1)->setUrl('https://url1.tld')->setTitle('Title 1')->setThumbnail(false),
363 $b1 = (new Bookmark())->setId(2)->setUrl('https://url2.tld')->setTitle('Title 2'),
364 (new Bookmark())->setId(3)->setUrl('https://url3.tld')->setTitle('Title 3')->setThumbnail(false),
365 $b2 = (new Bookmark())->setId(2)->setUrl('https://url4.tld')->setTitle('Title 4'),
366 (new Bookmark())->setId(2)->setUrl('ftp://url5.tld', ['ftp'])->setTitle('Title 5'),
367 ])
368 ;
369 $this->container->bookmarkService
370 ->expects(static::exactly(2))
371 ->method('set')
372 ->withConsecutive([$b1, false], [$b2, false])
373 ;
374 $this->container->bookmarkService->expects(static::once())->method('save');
375
376 $result = $this->controller->index($request, $response);
377
378 static::assertSame(200, $result->getStatusCode());
379 static::assertSame('linklist', (string) $result->getBody());
380 }
381
382 /**
383 * Test getting a permalink with thumbnail update.
384 */
385 public function testThumbnailUpdateFromPermalink(): void
386 {
387 $request = $this->createMock(Request::class);
388 $response = new Response();
389
390 $this->container->loginManager = $this->createMock(LoginManager::class);
391 $this->container->loginManager->method('isLoggedIn')->willReturn(true);
392
393 $this->container->conf = $this->createMock(ConfigManager::class);
394 $this->container->conf
395 ->method('get')
396 ->willReturnCallback(function (string $key, $default) {
397 if ($key === 'thumbnails.mode') {
398 return Thumbnailer::MODE_ALL;
399 } elseif ($key === 'general.enable_async_metadata') {
400 return false;
401 }
402
403 return $default;
404 })
405 ;
406
407 $this->container->thumbnailer = $this->createMock(Thumbnailer::class);
408 $this->container->thumbnailer->expects(static::once())->method('get')->withConsecutive(['https://url.tld']);
409
410 $this->container->bookmarkService
411 ->expects(static::once())
412 ->method('findByHash')
413 ->willReturn($bookmark = (new Bookmark())->setId(2)->setUrl('https://url.tld')->setTitle('Title 1'))
414 ;
415 $this->container->bookmarkService->expects(static::once())->method('set')->with($bookmark, true);
416 $this->container->bookmarkService->expects(static::never())->method('save');
417
418 $result = $this->controller->permalink($request, $response, ['hash' => 'abc']);
419
420 static::assertSame(200, $result->getStatusCode());
421 static::assertSame('linklist', (string) $result->getBody());
422 }
423
424 /**
425 * Test getting a permalink with thumbnail update with async setting: no update should run.
426 */
427 public function testThumbnailUpdateFromPermalinkAsync(): void
428 {
429 $request = $this->createMock(Request::class);
430 $response = new Response();
431
432 $this->container->loginManager = $this->createMock(LoginManager::class);
433 $this->container->loginManager->method('isLoggedIn')->willReturn(true);
434
435 $this->container->conf = $this->createMock(ConfigManager::class);
436 $this->container->conf
437 ->method('get')
438 ->willReturnCallback(function (string $key, $default) {
439 if ($key === 'thumbnails.mode') {
440 return Thumbnailer::MODE_ALL;
441 } elseif ($key === 'general.enable_async_metadata') {
442 return true;
443 }
444
445 return $default;
446 })
447 ;
448
449 $this->container->thumbnailer = $this->createMock(Thumbnailer::class);
450 $this->container->thumbnailer->expects(static::never())->method('get');
451
452 $this->container->bookmarkService
453 ->expects(static::once())
454 ->method('findByHash')
455 ->willReturn((new Bookmark())->setId(2)->setUrl('https://url.tld')->setTitle('Title 1'))
456 ;
457 $this->container->bookmarkService->expects(static::never())->method('set');
458 $this->container->bookmarkService->expects(static::never())->method('save');
459
460 $result = $this->controller->permalink($request, $response, ['hash' => 'abc']);
461
462 static::assertSame(200, $result->getStatusCode());
463 }
464
465 /**
466 * Trigger legacy controller in link list controller: permalink
467 */
468 public function testLegacyControllerPermalink(): void
469 {
470 $hash = 'abcdef';
471 $this->container->environment['QUERY_STRING'] = $hash;
472
473 $request = $this->createMock(Request::class);
474 $response = new Response();
475
476 $result = $this->controller->index($request, $response);
477
478 static::assertSame(302, $result->getStatusCode());
479 static::assertSame('/subfolder/shaare/' . $hash, $result->getHeader('location')[0]);
480 }
481
482 /**
483 * Trigger legacy controller in link list controller: ?do= query parameter
484 */
485 public function testLegacyControllerDoPage(): void
486 {
487 $request = $this->createMock(Request::class);
488 $request->method('getQueryParam')->with('do')->willReturn('picwall');
489 $response = new Response();
490
491 $result = $this->controller->index($request, $response);
492
493 static::assertSame(302, $result->getStatusCode());
494 static::assertSame('/subfolder/picture-wall', $result->getHeader('location')[0]);
495 }
496
497 /**
498 * Trigger legacy controller in link list controller: ?do= query parameter with unknown legacy route
499 */
500 public function testLegacyControllerUnknownDoPage(): void
501 {
502 $request = $this->createMock(Request::class);
503 $request->method('getQueryParam')->with('do')->willReturn('nope');
504 $response = new Response();
505
506 $result = $this->controller->index($request, $response);
507
508 static::assertSame(200, $result->getStatusCode());
509 static::assertSame('linklist', (string) $result->getBody());
510 }
511
512 /**
513 * Trigger legacy controller in link list controller: other GET route (e.g. ?post)
514 */
515 public function testLegacyControllerGetParameter(): void
516 {
517 $request = $this->createMock(Request::class);
518 $request->method('getQueryParams')->willReturn(['post' => $url = 'http://url.tld']);
519 $response = new Response();
520
521 $this->container->loginManager = $this->createMock(LoginManager::class);
522 $this->container->loginManager->method('isLoggedIn')->willReturn(true);
523
524 $result = $this->controller->index($request, $response);
525
526 static::assertSame(302, $result->getStatusCode());
527 static::assertSame(
528 '/subfolder/admin/shaare?post=' . urlencode($url),
529 $result->getHeader('location')[0]
530 );
531 }
532}
diff --git a/tests/front/controller/visitor/DailyControllerTest.php b/tests/front/controller/visitor/DailyControllerTest.php
new file mode 100644
index 00000000..758e7219
--- /dev/null
+++ b/tests/front/controller/visitor/DailyControllerTest.php
@@ -0,0 +1,716 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Bookmark\Bookmark;
8use Shaarli\Feed\CachedPage;
9use Shaarli\TestCase;
10use Slim\Http\Request;
11use Slim\Http\Response;
12
13class DailyControllerTest extends TestCase
14{
15 use FrontControllerMockHelper;
16
17 /** @var DailyController */
18 protected $controller;
19
20 public function setUp(): void
21 {
22 $this->createContainer();
23
24 $this->controller = new DailyController($this->container);
25 DailyController::$DAILY_RSS_NB_DAYS = 2;
26 }
27
28 public function testValidIndexControllerInvokeDefault(): void
29 {
30 $currentDay = new \DateTimeImmutable('2020-05-13');
31 $previousDate = new \DateTime('2 days ago 00:00:00');
32 $nextDate = new \DateTime('today 00:00:00');
33
34 $request = $this->createMock(Request::class);
35 $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string {
36 return $key === 'day' ? $currentDay->format('Ymd') : null;
37 });
38 $response = new Response();
39
40 // Save RainTPL assigned variables
41 $assignedVariables = [];
42 $this->assignTemplateVars($assignedVariables);
43
44 $this->container->bookmarkService
45 ->expects(static::once())
46 ->method('findByDate')
47 ->willReturnCallback(
48 function ($from, $to, &$previous, &$next) use ($currentDay, $previousDate, $nextDate): array {
49 $previous = $previousDate;
50 $next = $nextDate;
51
52 return [
53 (new Bookmark())
54 ->setId(1)
55 ->setUrl('http://url.tld')
56 ->setTitle(static::generateString(50))
57 ->setDescription(static::generateString(500))
58 ,
59 (new Bookmark())
60 ->setId(2)
61 ->setUrl('http://url2.tld')
62 ->setTitle(static::generateString(50))
63 ->setDescription(static::generateString(500))
64 ,
65 (new Bookmark())
66 ->setId(3)
67 ->setUrl('http://url3.tld')
68 ->setTitle(static::generateString(50))
69 ->setDescription(static::generateString(500))
70 ,
71 ];
72 }
73 )
74 ;
75
76 // Make sure that PluginManager hook is triggered
77 $this->container->pluginManager
78 ->expects(static::atLeastOnce())
79 ->method('executeHooks')
80 ->withConsecutive(['render_daily'])
81 ->willReturnCallback(
82 function (string $hook, array $data, array $param) use ($currentDay, $previousDate, $nextDate): array {
83 if ('render_daily' === $hook) {
84 static::assertArrayHasKey('linksToDisplay', $data);
85 static::assertCount(3, $data['linksToDisplay']);
86 static::assertSame(1, $data['linksToDisplay'][0]['id']);
87 static::assertSame($currentDay->getTimestamp(), $data['day']);
88 static::assertSame($previousDate->format('Ymd'), $data['previousday']);
89 static::assertSame($nextDate->format('Ymd'), $data['nextday']);
90
91 static::assertArrayHasKey('loggedin', $param);
92 }
93
94 return $data;
95 }
96 )
97 ;
98
99 $result = $this->controller->index($request, $response);
100
101 static::assertSame(200, $result->getStatusCode());
102 static::assertSame('daily', (string) $result->getBody());
103 static::assertSame(
104 'Daily - '. format_date($currentDay, false, true) .' - Shaarli',
105 $assignedVariables['pagetitle']
106 );
107 static::assertEquals($currentDay, $assignedVariables['dayDate']);
108 static::assertEquals($currentDay->getTimestamp(), $assignedVariables['day']);
109 static::assertSame($previousDate->format('Ymd'), $assignedVariables['previousday']);
110 static::assertSame($nextDate->format('Ymd'), $assignedVariables['nextday']);
111 static::assertSame('day', $assignedVariables['type']);
112 static::assertSame('May 13, 2020', $assignedVariables['dayDesc']);
113 static::assertSame('Daily', $assignedVariables['localizedType']);
114 static::assertCount(3, $assignedVariables['linksToDisplay']);
115
116 $link = $assignedVariables['linksToDisplay'][0];
117
118 static::assertSame(1, $link['id']);
119 static::assertSame('http://url.tld', $link['url']);
120 static::assertNotEmpty($link['title']);
121 static::assertNotEmpty($link['description']);
122 static::assertNotEmpty($link['formatedDescription']);
123
124 $link = $assignedVariables['linksToDisplay'][1];
125
126 static::assertSame(2, $link['id']);
127 static::assertSame('http://url2.tld', $link['url']);
128 static::assertNotEmpty($link['title']);
129 static::assertNotEmpty($link['description']);
130 static::assertNotEmpty($link['formatedDescription']);
131
132 $link = $assignedVariables['linksToDisplay'][2];
133
134 static::assertSame(3, $link['id']);
135 static::assertSame('http://url3.tld', $link['url']);
136 static::assertNotEmpty($link['title']);
137 static::assertNotEmpty($link['description']);
138 static::assertNotEmpty($link['formatedDescription']);
139
140 static::assertCount(3, $assignedVariables['cols']);
141 static::assertCount(1, $assignedVariables['cols'][0]);
142 static::assertCount(1, $assignedVariables['cols'][1]);
143 static::assertCount(1, $assignedVariables['cols'][2]);
144
145 $link = $assignedVariables['cols'][0][0];
146
147 static::assertSame(1, $link['id']);
148 static::assertSame('http://url.tld', $link['url']);
149 static::assertNotEmpty($link['title']);
150 static::assertNotEmpty($link['description']);
151 static::assertNotEmpty($link['formatedDescription']);
152
153 $link = $assignedVariables['cols'][1][0];
154
155 static::assertSame(2, $link['id']);
156 static::assertSame('http://url2.tld', $link['url']);
157 static::assertNotEmpty($link['title']);
158 static::assertNotEmpty($link['description']);
159 static::assertNotEmpty($link['formatedDescription']);
160
161 $link = $assignedVariables['cols'][2][0];
162
163 static::assertSame(3, $link['id']);
164 static::assertSame('http://url3.tld', $link['url']);
165 static::assertNotEmpty($link['title']);
166 static::assertNotEmpty($link['description']);
167 static::assertNotEmpty($link['formatedDescription']);
168 }
169
170 /**
171 * Daily page - test that everything goes fine with no future or past bookmarks
172 */
173 public function testValidIndexControllerInvokeNoFutureOrPast(): void
174 {
175 $currentDay = new \DateTimeImmutable('2020-05-13');
176
177 $request = $this->createMock(Request::class);
178 $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string {
179 return $key === 'day' ? $currentDay->format('Ymd') : null;
180 });
181 $response = new Response();
182
183 // Save RainTPL assigned variables
184 $assignedVariables = [];
185 $this->assignTemplateVars($assignedVariables);
186
187 $this->container->bookmarkService
188 ->expects(static::once())
189 ->method('findByDate')
190 ->willReturnCallback(function () use ($currentDay): array {
191 return [
192 (new Bookmark())
193 ->setId(1)
194 ->setUrl('http://url.tld')
195 ->setTitle(static::generateString(50))
196 ->setDescription(static::generateString(500))
197 ,
198 ];
199 })
200 ;
201
202 // Make sure that PluginManager hook is triggered
203 $this->container->pluginManager
204 ->expects(static::atLeastOnce())
205 ->method('executeHooks')
206 ->withConsecutive(['render_daily'])
207 ->willReturnCallback(function (string $hook, array $data, array $param) use ($currentDay): array {
208 if ('render_daily' === $hook) {
209 static::assertArrayHasKey('linksToDisplay', $data);
210 static::assertCount(1, $data['linksToDisplay']);
211 static::assertSame(1, $data['linksToDisplay'][0]['id']);
212 static::assertSame($currentDay->getTimestamp(), $data['day']);
213 static::assertEmpty($data['previousday']);
214 static::assertEmpty($data['nextday']);
215
216 static::assertArrayHasKey('loggedin', $param);
217 }
218
219 return $data;
220 });
221
222 $result = $this->controller->index($request, $response);
223
224 static::assertSame(200, $result->getStatusCode());
225 static::assertSame('daily', (string) $result->getBody());
226 static::assertSame(
227 'Daily - '. format_date($currentDay, false, true) .' - Shaarli',
228 $assignedVariables['pagetitle']
229 );
230 static::assertCount(1, $assignedVariables['linksToDisplay']);
231
232 $link = $assignedVariables['linksToDisplay'][0];
233 static::assertSame(1, $link['id']);
234 }
235
236 /**
237 * Daily page - test that height adjustment in columns is working
238 */
239 public function testValidIndexControllerInvokeHeightAdjustment(): void
240 {
241 $currentDay = new \DateTimeImmutable('2020-05-13');
242
243 $request = $this->createMock(Request::class);
244 $response = new Response();
245
246 // Save RainTPL assigned variables
247 $assignedVariables = [];
248 $this->assignTemplateVars($assignedVariables);
249
250 $this->container->bookmarkService
251 ->expects(static::once())
252 ->method('findByDate')
253 ->willReturnCallback(function () use ($currentDay): array {
254 return [
255 (new Bookmark())->setId(1)->setUrl('http://url.tld')->setTitle('title'),
256 (new Bookmark())
257 ->setId(2)
258 ->setUrl('http://url.tld')
259 ->setTitle(static::generateString(50))
260 ->setDescription(static::generateString(5000))
261 ,
262 (new Bookmark())->setId(3)->setUrl('http://url.tld')->setTitle('title'),
263 (new Bookmark())->setId(4)->setUrl('http://url.tld')->setTitle('title'),
264 (new Bookmark())->setId(5)->setUrl('http://url.tld')->setTitle('title'),
265 (new Bookmark())->setId(6)->setUrl('http://url.tld')->setTitle('title'),
266 (new Bookmark())->setId(7)->setUrl('http://url.tld')->setTitle('title'),
267 ];
268 })
269 ;
270
271 // Make sure that PluginManager hook is triggered
272 $this->container->pluginManager
273 ->expects(static::atLeastOnce())
274 ->method('executeHooks')
275 ->willReturnCallback(function (string $hook, array $data, array $param): array {
276 return $data;
277 })
278 ;
279
280 $result = $this->controller->index($request, $response);
281
282 static::assertSame(200, $result->getStatusCode());
283 static::assertSame('daily', (string) $result->getBody());
284 static::assertCount(7, $assignedVariables['linksToDisplay']);
285
286 $columnIds = function (array $column): array {
287 return array_map(function (array $item): int { return $item['id']; }, $column);
288 };
289
290 static::assertSame([1, 4, 6], $columnIds($assignedVariables['cols'][0]));
291 static::assertSame([2], $columnIds($assignedVariables['cols'][1]));
292 static::assertSame([3, 5, 7], $columnIds($assignedVariables['cols'][2]));
293 }
294
295 /**
296 * Daily page - no bookmark
297 */
298 public function testValidIndexControllerInvokeNoBookmark(): void
299 {
300 $request = $this->createMock(Request::class);
301 $response = new Response();
302
303 // Save RainTPL assigned variables
304 $assignedVariables = [];
305 $this->assignTemplateVars($assignedVariables);
306
307 // Links dataset: 2 links with thumbnails
308 $this->container->bookmarkService
309 ->expects(static::once())
310 ->method('findByDate')
311 ->willReturnCallback(function (): array {
312 return [];
313 })
314 ;
315
316 // Make sure that PluginManager hook is triggered
317 $this->container->pluginManager
318 ->expects(static::atLeastOnce())
319 ->method('executeHooks')
320 ->willReturnCallback(function (string $hook, array $data, array $param): array {
321 return $data;
322 })
323 ;
324
325 $result = $this->controller->index($request, $response);
326
327 static::assertSame(200, $result->getStatusCode());
328 static::assertSame('daily', (string) $result->getBody());
329 static::assertCount(0, $assignedVariables['linksToDisplay']);
330 static::assertSame('Today - ' . (new \DateTime())->format('F d, Y'), $assignedVariables['dayDesc']);
331 static::assertEquals((new \DateTime())->setTime(0, 0)->getTimestamp(), $assignedVariables['day']);
332 static::assertEquals((new \DateTime())->setTime(0, 0), $assignedVariables['dayDate']);
333 }
334
335 /**
336 * Daily RSS - default behaviour
337 */
338 public function testValidRssControllerInvokeDefault(): void
339 {
340 $dates = [
341 new \DateTimeImmutable('2020-05-17'),
342 new \DateTimeImmutable('2020-05-15'),
343 new \DateTimeImmutable('2020-05-13'),
344 new \DateTimeImmutable('+1 month'),
345 ];
346
347 $request = $this->createMock(Request::class);
348 $response = new Response();
349
350 $this->container->bookmarkService->expects(static::once())->method('search')->willReturn([
351 (new Bookmark())->setId(1)->setCreated($dates[0])->setUrl('http://domain.tld/1'),
352 (new Bookmark())->setId(2)->setCreated($dates[1])->setUrl('http://domain.tld/2'),
353 (new Bookmark())->setId(3)->setCreated($dates[1])->setUrl('http://domain.tld/3'),
354 (new Bookmark())->setId(4)->setCreated($dates[2])->setUrl('http://domain.tld/4'),
355 (new Bookmark())->setId(5)->setCreated($dates[3])->setUrl('http://domain.tld/5'),
356 ]);
357
358 $this->container->pageCacheManager
359 ->expects(static::once())
360 ->method('getCachePage')
361 ->willReturnCallback(function (): CachedPage {
362 $cachedPage = $this->createMock(CachedPage::class);
363 $cachedPage->expects(static::once())->method('cache')->with('dailyrss');
364
365 return $cachedPage;
366 }
367 );
368
369 // Save RainTPL assigned variables
370 $assignedVariables = [];
371 $this->assignTemplateVars($assignedVariables);
372
373 $result = $this->controller->rss($request, $response);
374
375 static::assertSame(200, $result->getStatusCode());
376 static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]);
377 static::assertSame('dailyrss', (string) $result->getBody());
378 static::assertSame('Shaarli', $assignedVariables['title']);
379 static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']);
380 static::assertSame('http://shaarli/subfolder/daily-rss', $assignedVariables['page_url']);
381 static::assertFalse($assignedVariables['hide_timestamps']);
382 static::assertCount(3, $assignedVariables['days']);
383
384 $day = $assignedVariables['days'][$dates[0]->format('Ymd')];
385 $date = $dates[0]->setTime(23, 59, 59);
386
387 static::assertEquals($date, $day['date']);
388 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
389 static::assertSame(format_date($date, false), $day['date_human']);
390 static::assertSame('http://shaarli/subfolder/daily?day='. $dates[0]->format('Ymd'), $day['absolute_url']);
391 static::assertCount(1, $day['links']);
392 static::assertSame(1, $day['links'][0]['id']);
393 static::assertSame('http://domain.tld/1', $day['links'][0]['url']);
394 static::assertEquals($dates[0], $day['links'][0]['created']);
395
396 $day = $assignedVariables['days'][$dates[1]->format('Ymd')];
397 $date = $dates[1]->setTime(23, 59, 59);
398
399 static::assertEquals($date, $day['date']);
400 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
401 static::assertSame(format_date($date, false), $day['date_human']);
402 static::assertSame('http://shaarli/subfolder/daily?day='. $dates[1]->format('Ymd'), $day['absolute_url']);
403 static::assertCount(2, $day['links']);
404
405 static::assertSame(2, $day['links'][0]['id']);
406 static::assertSame('http://domain.tld/2', $day['links'][0]['url']);
407 static::assertEquals($dates[1], $day['links'][0]['created']);
408 static::assertSame(3, $day['links'][1]['id']);
409 static::assertSame('http://domain.tld/3', $day['links'][1]['url']);
410 static::assertEquals($dates[1], $day['links'][1]['created']);
411
412 $day = $assignedVariables['days'][$dates[2]->format('Ymd')];
413 $date = $dates[2]->setTime(23, 59, 59);
414
415 static::assertEquals($date, $day['date']);
416 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
417 static::assertSame(format_date($date, false), $day['date_human']);
418 static::assertSame('http://shaarli/subfolder/daily?day='. $dates[2]->format('Ymd'), $day['absolute_url']);
419 static::assertCount(1, $day['links']);
420 static::assertSame(4, $day['links'][0]['id']);
421 static::assertSame('http://domain.tld/4', $day['links'][0]['url']);
422 static::assertEquals($dates[2], $day['links'][0]['created']);
423 }
424
425 /**
426 * Daily RSS - trigger cache rendering
427 */
428 public function testValidRssControllerInvokeTriggerCache(): void
429 {
430 $request = $this->createMock(Request::class);
431 $response = new Response();
432
433 $this->container->pageCacheManager->method('getCachePage')->willReturnCallback(function (): CachedPage {
434 $cachedPage = $this->createMock(CachedPage::class);
435 $cachedPage->method('cachedVersion')->willReturn('this is cache!');
436
437 return $cachedPage;
438 });
439
440 $this->container->bookmarkService->expects(static::never())->method('search');
441
442 $result = $this->controller->rss($request, $response);
443
444 static::assertSame(200, $result->getStatusCode());
445 static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]);
446 static::assertSame('this is cache!', (string) $result->getBody());
447 }
448
449 /**
450 * Daily RSS - No bookmark
451 */
452 public function testValidRssControllerInvokeNoBookmark(): void
453 {
454 $request = $this->createMock(Request::class);
455 $response = new Response();
456
457 $this->container->bookmarkService->expects(static::once())->method('search')->willReturn([]);
458
459 // Save RainTPL assigned variables
460 $assignedVariables = [];
461 $this->assignTemplateVars($assignedVariables);
462
463 $result = $this->controller->rss($request, $response);
464
465 static::assertSame(200, $result->getStatusCode());
466 static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]);
467 static::assertSame('dailyrss', (string) $result->getBody());
468 static::assertSame('Shaarli', $assignedVariables['title']);
469 static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']);
470 static::assertSame('http://shaarli/subfolder/daily-rss', $assignedVariables['page_url']);
471 static::assertFalse($assignedVariables['hide_timestamps']);
472 static::assertCount(0, $assignedVariables['days']);
473 }
474
475 /**
476 * Test simple display index with week parameter
477 */
478 public function testSimpleIndexWeekly(): void
479 {
480 $currentDay = new \DateTimeImmutable('2020-05-13');
481 $expectedDay = new \DateTimeImmutable('2020-05-11');
482
483 $request = $this->createMock(Request::class);
484 $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string {
485 return $key === 'week' ? $currentDay->format('YW') : null;
486 });
487 $response = new Response();
488
489 // Save RainTPL assigned variables
490 $assignedVariables = [];
491 $this->assignTemplateVars($assignedVariables);
492
493 $this->container->bookmarkService
494 ->expects(static::once())
495 ->method('findByDate')
496 ->willReturnCallback(
497 function (): array {
498 return [
499 (new Bookmark())
500 ->setId(1)
501 ->setUrl('http://url.tld')
502 ->setTitle(static::generateString(50))
503 ->setDescription(static::generateString(500))
504 ,
505 (new Bookmark())
506 ->setId(2)
507 ->setUrl('http://url2.tld')
508 ->setTitle(static::generateString(50))
509 ->setDescription(static::generateString(500))
510 ,
511 ];
512 }
513 )
514 ;
515
516 $result = $this->controller->index($request, $response);
517
518 static::assertSame(200, $result->getStatusCode());
519 static::assertSame('daily', (string) $result->getBody());
520 static::assertSame(
521 'Weekly - Week 20 (May 11, 2020) - Shaarli',
522 $assignedVariables['pagetitle']
523 );
524
525 static::assertCount(2, $assignedVariables['linksToDisplay']);
526 static::assertEquals($expectedDay->setTime(0, 0), $assignedVariables['dayDate']);
527 static::assertSame($expectedDay->setTime(0, 0)->getTimestamp(), $assignedVariables['day']);
528 static::assertSame('', $assignedVariables['previousday']);
529 static::assertSame('', $assignedVariables['nextday']);
530 static::assertSame('Week 20 (May 11, 2020)', $assignedVariables['dayDesc']);
531 static::assertSame('week', $assignedVariables['type']);
532 static::assertSame('Weekly', $assignedVariables['localizedType']);
533 }
534
535 /**
536 * Test simple display index with month parameter
537 */
538 public function testSimpleIndexMonthly(): void
539 {
540 $currentDay = new \DateTimeImmutable('2020-05-13');
541 $expectedDay = new \DateTimeImmutable('2020-05-01');
542
543 $request = $this->createMock(Request::class);
544 $request->method('getQueryParam')->willReturnCallback(function (string $key) use ($currentDay): ?string {
545 return $key === 'month' ? $currentDay->format('Ym') : null;
546 });
547 $response = new Response();
548
549 // Save RainTPL assigned variables
550 $assignedVariables = [];
551 $this->assignTemplateVars($assignedVariables);
552
553 $this->container->bookmarkService
554 ->expects(static::once())
555 ->method('findByDate')
556 ->willReturnCallback(
557 function (): array {
558 return [
559 (new Bookmark())
560 ->setId(1)
561 ->setUrl('http://url.tld')
562 ->setTitle(static::generateString(50))
563 ->setDescription(static::generateString(500))
564 ,
565 (new Bookmark())
566 ->setId(2)
567 ->setUrl('http://url2.tld')
568 ->setTitle(static::generateString(50))
569 ->setDescription(static::generateString(500))
570 ,
571 ];
572 }
573 )
574 ;
575
576 $result = $this->controller->index($request, $response);
577
578 static::assertSame(200, $result->getStatusCode());
579 static::assertSame('daily', (string) $result->getBody());
580 static::assertSame(
581 'Monthly - May, 2020 - Shaarli',
582 $assignedVariables['pagetitle']
583 );
584
585 static::assertCount(2, $assignedVariables['linksToDisplay']);
586 static::assertEquals($expectedDay->setTime(0, 0), $assignedVariables['dayDate']);
587 static::assertSame($expectedDay->setTime(0, 0)->getTimestamp(), $assignedVariables['day']);
588 static::assertSame('', $assignedVariables['previousday']);
589 static::assertSame('', $assignedVariables['nextday']);
590 static::assertSame('May, 2020', $assignedVariables['dayDesc']);
591 static::assertSame('month', $assignedVariables['type']);
592 static::assertSame('Monthly', $assignedVariables['localizedType']);
593 }
594
595 /**
596 * Test simple display RSS with week parameter
597 */
598 public function testSimpleRssWeekly(): void
599 {
600 $dates = [
601 new \DateTimeImmutable('2020-05-19'),
602 new \DateTimeImmutable('2020-05-13'),
603 ];
604 $expectedDates = [
605 new \DateTimeImmutable('2020-05-24 23:59:59'),
606 new \DateTimeImmutable('2020-05-17 23:59:59'),
607 ];
608
609 $this->container->environment['QUERY_STRING'] = 'week';
610 $request = $this->createMock(Request::class);
611 $request->method('getQueryParam')->willReturnCallback(function (string $key): ?string {
612 return $key === 'week' ? '' : null;
613 });
614 $response = new Response();
615
616 $this->container->bookmarkService->expects(static::once())->method('search')->willReturn([
617 (new Bookmark())->setId(1)->setCreated($dates[0])->setUrl('http://domain.tld/1'),
618 (new Bookmark())->setId(2)->setCreated($dates[1])->setUrl('http://domain.tld/2'),
619 (new Bookmark())->setId(3)->setCreated($dates[1])->setUrl('http://domain.tld/3'),
620 ]);
621
622 // Save RainTPL assigned variables
623 $assignedVariables = [];
624 $this->assignTemplateVars($assignedVariables);
625
626 $result = $this->controller->rss($request, $response);
627
628 static::assertSame(200, $result->getStatusCode());
629 static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]);
630 static::assertSame('dailyrss', (string) $result->getBody());
631 static::assertSame('Shaarli', $assignedVariables['title']);
632 static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']);
633 static::assertSame('http://shaarli/subfolder/daily-rss?week', $assignedVariables['page_url']);
634 static::assertFalse($assignedVariables['hide_timestamps']);
635 static::assertCount(2, $assignedVariables['days']);
636
637 $day = $assignedVariables['days'][$dates[0]->format('YW')];
638 $date = $expectedDates[0];
639
640 static::assertEquals($date, $day['date']);
641 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
642 static::assertSame('Week 21 (May 18, 2020)', $day['date_human']);
643 static::assertSame('http://shaarli/subfolder/daily?week='. $dates[0]->format('YW'), $day['absolute_url']);
644 static::assertCount(1, $day['links']);
645
646 $day = $assignedVariables['days'][$dates[1]->format('YW')];
647 $date = $expectedDates[1];
648
649 static::assertEquals($date, $day['date']);
650 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
651 static::assertSame('Week 20 (May 11, 2020)', $day['date_human']);
652 static::assertSame('http://shaarli/subfolder/daily?week='. $dates[1]->format('YW'), $day['absolute_url']);
653 static::assertCount(2, $day['links']);
654 }
655
656 /**
657 * Test simple display RSS with month parameter
658 */
659 public function testSimpleRssMonthly(): void
660 {
661 $dates = [
662 new \DateTimeImmutable('2020-05-19'),
663 new \DateTimeImmutable('2020-04-13'),
664 ];
665 $expectedDates = [
666 new \DateTimeImmutable('2020-05-31 23:59:59'),
667 new \DateTimeImmutable('2020-04-30 23:59:59'),
668 ];
669
670 $this->container->environment['QUERY_STRING'] = 'month';
671 $request = $this->createMock(Request::class);
672 $request->method('getQueryParam')->willReturnCallback(function (string $key): ?string {
673 return $key === 'month' ? '' : null;
674 });
675 $response = new Response();
676
677 $this->container->bookmarkService->expects(static::once())->method('search')->willReturn([
678 (new Bookmark())->setId(1)->setCreated($dates[0])->setUrl('http://domain.tld/1'),
679 (new Bookmark())->setId(2)->setCreated($dates[1])->setUrl('http://domain.tld/2'),
680 (new Bookmark())->setId(3)->setCreated($dates[1])->setUrl('http://domain.tld/3'),
681 ]);
682
683 // Save RainTPL assigned variables
684 $assignedVariables = [];
685 $this->assignTemplateVars($assignedVariables);
686
687 $result = $this->controller->rss($request, $response);
688
689 static::assertSame(200, $result->getStatusCode());
690 static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]);
691 static::assertSame('dailyrss', (string) $result->getBody());
692 static::assertSame('Shaarli', $assignedVariables['title']);
693 static::assertSame('http://shaarli/subfolder/', $assignedVariables['index_url']);
694 static::assertSame('http://shaarli/subfolder/daily-rss?month', $assignedVariables['page_url']);
695 static::assertFalse($assignedVariables['hide_timestamps']);
696 static::assertCount(2, $assignedVariables['days']);
697
698 $day = $assignedVariables['days'][$dates[0]->format('Ym')];
699 $date = $expectedDates[0];
700
701 static::assertEquals($date, $day['date']);
702 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
703 static::assertSame('May, 2020', $day['date_human']);
704 static::assertSame('http://shaarli/subfolder/daily?month='. $dates[0]->format('Ym'), $day['absolute_url']);
705 static::assertCount(1, $day['links']);
706
707 $day = $assignedVariables['days'][$dates[1]->format('Ym')];
708 $date = $expectedDates[1];
709
710 static::assertEquals($date, $day['date']);
711 static::assertSame($date->format(\DateTime::RSS), $day['date_rss']);
712 static::assertSame('April, 2020', $day['date_human']);
713 static::assertSame('http://shaarli/subfolder/daily?month='. $dates[1]->format('Ym'), $day['absolute_url']);
714 static::assertCount(2, $day['links']);
715 }
716}
diff --git a/tests/front/controller/visitor/ErrorControllerTest.php b/tests/front/controller/visitor/ErrorControllerTest.php
new file mode 100644
index 00000000..75408cf4
--- /dev/null
+++ b/tests/front/controller/visitor/ErrorControllerTest.php
@@ -0,0 +1,70 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Front\Exception\ShaarliFrontException;
8use Shaarli\TestCase;
9use Slim\Http\Request;
10use Slim\Http\Response;
11
12class ErrorControllerTest extends TestCase
13{
14 use FrontControllerMockHelper;
15
16 /** @var ErrorController */
17 protected $controller;
18
19 public function setUp(): void
20 {
21 $this->createContainer();
22
23 $this->controller = new ErrorController($this->container);
24 }
25
26 /**
27 * Test displaying error with a ShaarliFrontException: display exception message and use its code for HTTTP code
28 */
29 public function testDisplayFrontExceptionError(): void
30 {
31 $request = $this->createMock(Request::class);
32 $response = new Response();
33
34 $message = 'error message';
35 $errorCode = 418;
36
37 // Save RainTPL assigned variables
38 $assignedVariables = [];
39 $this->assignTemplateVars($assignedVariables);
40
41 $result = ($this->controller)(
42 $request,
43 $response,
44 new class($message, $errorCode) extends ShaarliFrontException {}
45 );
46
47 static::assertSame($errorCode, $result->getStatusCode());
48 static::assertSame($message, $assignedVariables['message']);
49 static::assertArrayNotHasKey('stacktrace', $assignedVariables);
50 }
51
52 /**
53 * Test displaying error with any exception (no debug): only display an error occurred with HTTP 500.
54 */
55 public function testDisplayAnyExceptionErrorNoDebug(): void
56 {
57 $request = $this->createMock(Request::class);
58 $response = new Response();
59
60 // Save RainTPL assigned variables
61 $assignedVariables = [];
62 $this->assignTemplateVars($assignedVariables);
63
64 $result = ($this->controller)($request, $response, new \Exception('abc'));
65
66 static::assertSame(500, $result->getStatusCode());
67 static::assertSame('An unexpected error occurred.', $assignedVariables['message']);
68 static::assertArrayNotHasKey('stacktrace', $assignedVariables);
69 }
70}
diff --git a/tests/front/controller/visitor/ErrorNotFoundControllerTest.php b/tests/front/controller/visitor/ErrorNotFoundControllerTest.php
new file mode 100644
index 00000000..a1cbbecf
--- /dev/null
+++ b/tests/front/controller/visitor/ErrorNotFoundControllerTest.php
@@ -0,0 +1,81 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\TestCase;
8use Slim\Http\Request;
9use Slim\Http\Response;
10use Slim\Http\Uri;
11
12class ErrorNotFoundControllerTest extends TestCase
13{
14 use FrontControllerMockHelper;
15
16 /** @var ErrorNotFoundController */
17 protected $controller;
18
19 public function setUp(): void
20 {
21 $this->createContainer();
22
23 $this->controller = new ErrorNotFoundController($this->container);
24 }
25
26 /**
27 * Test displaying 404 error
28 */
29 public function testDisplayNotFoundError(): void
30 {
31 $request = $this->createMock(Request::class);
32 $request->expects(static::once())->method('getRequestTarget')->willReturn('/');
33 $request->method('getUri')->willReturnCallback(function (): Uri {
34 $uri = $this->createMock(Uri::class);
35 $uri->method('getBasePath')->willReturn('/subfolder');
36
37 return $uri;
38 });
39
40 $response = new Response();
41
42 // Save RainTPL assigned variables
43 $assignedVariables = [];
44 $this->assignTemplateVars($assignedVariables);
45
46 $result = ($this->controller)(
47 $request,
48 $response
49 );
50
51 static::assertSame(404, $result->getStatusCode());
52 static::assertSame('404', (string) $result->getBody());
53 static::assertSame('Requested page could not be found.', $assignedVariables['error_message']);
54 }
55
56 /**
57 * Test displaying 404 error from REST API
58 */
59 public function testDisplayNotFoundErrorFromAPI(): void
60 {
61 $request = $this->createMock(Request::class);
62 $request->expects(static::once())->method('getRequestTarget')->willReturn('/sufolder/api/v1/links');
63 $request->method('getUri')->willReturnCallback(function (): Uri {
64 $uri = $this->createMock(Uri::class);
65 $uri->method('getBasePath')->willReturn('/subfolder');
66
67 return $uri;
68 });
69
70 $response = new Response();
71
72 // Save RainTPL assigned variables
73 $assignedVariables = [];
74 $this->assignTemplateVars($assignedVariables);
75
76 $result = ($this->controller)($request, $response);
77
78 static::assertSame(404, $result->getStatusCode());
79 static::assertSame([], $assignedVariables);
80 }
81}
diff --git a/tests/front/controller/visitor/FeedControllerTest.php b/tests/front/controller/visitor/FeedControllerTest.php
new file mode 100644
index 00000000..4ae7c925
--- /dev/null
+++ b/tests/front/controller/visitor/FeedControllerTest.php
@@ -0,0 +1,151 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Feed\FeedBuilder;
8use Shaarli\TestCase;
9use Slim\Http\Request;
10use Slim\Http\Response;
11
12class FeedControllerTest extends TestCase
13{
14 use FrontControllerMockHelper;
15
16 /** @var FeedController */
17 protected $controller;
18
19 public function setUp(): void
20 {
21 $this->createContainer();
22
23 $this->container->feedBuilder = $this->createMock(FeedBuilder::class);
24
25 $this->controller = new FeedController($this->container);
26 }
27
28 /**
29 * Feed Controller - RSS default behaviour
30 */
31 public function testDefaultRssController(): void
32 {
33 $request = $this->createMock(Request::class);
34 $response = new Response();
35
36 $this->container->feedBuilder->expects(static::once())->method('setLocale');
37 $this->container->feedBuilder->expects(static::once())->method('setHideDates')->with(false);
38 $this->container->feedBuilder->expects(static::once())->method('setUsePermalinks')->with(true);
39
40 // Save RainTPL assigned variables
41 $assignedVariables = [];
42 $this->assignTemplateVars($assignedVariables);
43
44 $this->container->feedBuilder->method('buildData')->willReturn(['content' => 'data']);
45
46 // Make sure that PluginManager hook is triggered
47 $this->container->pluginManager
48 ->expects(static::atLeastOnce())
49 ->method('executeHooks')
50 ->withConsecutive(['render_feed'])
51 ->willReturnCallback(function (string $hook, array $data, array $param): void {
52 if ('render_feed' === $hook) {
53 static::assertSame('data', $data['content']);
54
55 static::assertArrayHasKey('loggedin', $param);
56 static::assertSame('feed.rss', $param['target']);
57 }
58 })
59 ;
60
61 $result = $this->controller->rss($request, $response);
62
63 static::assertSame(200, $result->getStatusCode());
64 static::assertStringContainsString('application/rss', $result->getHeader('Content-Type')[0]);
65 static::assertSame('feed.rss', (string) $result->getBody());
66 static::assertSame('data', $assignedVariables['content']);
67 }
68
69 /**
70 * Feed Controller - ATOM default behaviour
71 */
72 public function testDefaultAtomController(): void
73 {
74 $request = $this->createMock(Request::class);
75 $response = new Response();
76
77 $this->container->feedBuilder->expects(static::once())->method('setLocale');
78 $this->container->feedBuilder->expects(static::once())->method('setHideDates')->with(false);
79 $this->container->feedBuilder->expects(static::once())->method('setUsePermalinks')->with(true);
80
81 // Save RainTPL assigned variables
82 $assignedVariables = [];
83 $this->assignTemplateVars($assignedVariables);
84
85 $this->container->feedBuilder->method('buildData')->willReturn(['content' => 'data']);
86
87 // Make sure that PluginManager hook is triggered
88 $this->container->pluginManager
89 ->expects(static::atLeastOnce())
90 ->method('executeHooks')
91 ->withConsecutive(['render_feed'])
92 ->willReturnCallback(function (string $hook, array $data, array $param): void {
93 if ('render_feed' === $hook) {
94 static::assertSame('data', $data['content']);
95
96 static::assertArrayHasKey('loggedin', $param);
97 static::assertSame('feed.atom', $param['target']);
98 }
99 })
100 ;
101
102 $result = $this->controller->atom($request, $response);
103
104 static::assertSame(200, $result->getStatusCode());
105 static::assertStringContainsString('application/atom', $result->getHeader('Content-Type')[0]);
106 static::assertSame('feed.atom', (string) $result->getBody());
107 static::assertSame('data', $assignedVariables['content']);
108 }
109
110 /**
111 * Feed Controller - ATOM with parameters
112 */
113 public function testAtomControllerWithParameters(): void
114 {
115 $request = $this->createMock(Request::class);
116 $request->method('getParams')->willReturn(['parameter' => 'value']);
117 $response = new Response();
118
119 // Save RainTPL assigned variables
120 $assignedVariables = [];
121 $this->assignTemplateVars($assignedVariables);
122
123 $this->container->feedBuilder
124 ->method('buildData')
125 ->with('atom', ['parameter' => 'value'])
126 ->willReturn(['content' => 'data'])
127 ;
128
129 // Make sure that PluginManager hook is triggered
130 $this->container->pluginManager
131 ->expects(static::atLeastOnce())
132 ->method('executeHooks')
133 ->withConsecutive(['render_feed'])
134 ->willReturnCallback(function (string $hook, array $data, array $param): void {
135 if ('render_feed' === $hook) {
136 static::assertSame('data', $data['content']);
137
138 static::assertArrayHasKey('loggedin', $param);
139 static::assertSame('feed.atom', $param['target']);
140 }
141 })
142 ;
143
144 $result = $this->controller->atom($request, $response);
145
146 static::assertSame(200, $result->getStatusCode());
147 static::assertStringContainsString('application/atom', $result->getHeader('Content-Type')[0]);
148 static::assertSame('feed.atom', (string) $result->getBody());
149 static::assertSame('data', $assignedVariables['content']);
150 }
151}
diff --git a/tests/front/controller/visitor/FrontControllerMockHelper.php b/tests/front/controller/visitor/FrontControllerMockHelper.php
new file mode 100644
index 00000000..fc0bb7d1
--- /dev/null
+++ b/tests/front/controller/visitor/FrontControllerMockHelper.php
@@ -0,0 +1,118 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Bookmark\BookmarkServiceInterface;
8use Shaarli\Config\ConfigManager;
9use Shaarli\Container\ShaarliTestContainer;
10use Shaarli\Formatter\BookmarkFormatter;
11use Shaarli\Formatter\BookmarkRawFormatter;
12use Shaarli\Formatter\FormatterFactory;
13use Shaarli\Plugin\PluginManager;
14use Shaarli\Render\PageBuilder;
15use Shaarli\Render\PageCacheManager;
16use Shaarli\Security\LoginManager;
17use Shaarli\Security\SessionManager;
18
19/**
20 * Trait FrontControllerMockHelper
21 *
22 * Helper trait used to initialize the ShaarliContainer and mock its services for controller tests.
23 *
24 * @property ShaarliTestContainer $container
25 * @package Shaarli\Front\Controller
26 */
27trait FrontControllerMockHelper
28{
29 /** @var ShaarliTestContainer */
30 protected $container;
31
32 /**
33 * Mock the container instance and initialize container's services used by tests
34 */
35 protected function createContainer(): void
36 {
37 $this->container = $this->createMock(ShaarliTestContainer::class);
38
39 $this->container->loginManager = $this->createMock(LoginManager::class);
40
41 // Config
42 $this->container->conf = $this->createMock(ConfigManager::class);
43 $this->container->conf->method('get')->willReturnCallback(function (string $parameter, $default) {
44 return $default === null ? $parameter : $default;
45 });
46
47 // PageBuilder
48 $this->container->pageBuilder = $this->createMock(PageBuilder::class);
49 $this->container->pageBuilder
50 ->method('render')
51 ->willReturnCallback(function (string $template): string {
52 return $template;
53 })
54 ;
55
56 // Plugin Manager
57 $this->container->pluginManager = $this->createMock(PluginManager::class);
58
59 // BookmarkService
60 $this->container->bookmarkService = $this->createMock(BookmarkServiceInterface::class);
61
62 // Formatter
63 $this->container->formatterFactory = $this->createMock(FormatterFactory::class);
64 $this->container->formatterFactory
65 ->method('getFormatter')
66 ->willReturnCallback(function (): BookmarkFormatter {
67 return new BookmarkRawFormatter($this->container->conf, true);
68 })
69 ;
70
71 // CacheManager
72 $this->container->pageCacheManager = $this->createMock(PageCacheManager::class);
73
74 // SessionManager
75 $this->container->sessionManager = $this->createMock(SessionManager::class);
76
77 // $_SERVER
78 $this->container->environment = [
79 'SERVER_NAME' => 'shaarli',
80 'SERVER_PORT' => '80',
81 'REQUEST_URI' => '/subfolder/daily-rss',
82 'REMOTE_ADDR' => '1.2.3.4',
83 'SCRIPT_NAME' => '/subfolder/index.php',
84 ];
85
86 $this->container->basePath = '/subfolder';
87 }
88
89 /**
90 * Pass a reference of an array which will be populated by `pageBuilder->assign` calls during execution.
91 *
92 * @param mixed $variables Array reference to populate.
93 */
94 protected function assignTemplateVars(array &$variables): void
95 {
96 $this->container->pageBuilder
97 ->method('assign')
98 ->willReturnCallback(function ($key, $value) use (&$variables) {
99 $variables[$key] = $value;
100
101 return $this;
102 })
103 ;
104 }
105
106 protected static function generateString(int $length): string
107 {
108 // bin2hex(random_bytes) generates string twice as long as given parameter
109 $length = (int) ceil($length / 2);
110
111 return bin2hex(random_bytes($length));
112 }
113
114 /**
115 * Force to be used in PHPUnit context.
116 */
117 protected abstract function isInTestsContext(): bool;
118}
diff --git a/tests/front/controller/visitor/InstallControllerTest.php b/tests/front/controller/visitor/InstallControllerTest.php
new file mode 100644
index 00000000..2105ed77
--- /dev/null
+++ b/tests/front/controller/visitor/InstallControllerTest.php
@@ -0,0 +1,304 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Config\ConfigManager;
8use Shaarli\Front\Exception\AlreadyInstalledException;
9use Shaarli\Security\SessionManager;
10use Shaarli\TestCase;
11use Slim\Http\Request;
12use Slim\Http\Response;
13
14class InstallControllerTest extends TestCase
15{
16 use FrontControllerMockHelper;
17
18 const MOCK_FILE = '.tmp';
19
20 /** @var InstallController */
21 protected $controller;
22
23 public function setUp(): void
24 {
25 $this->createContainer();
26
27 $this->container->conf = $this->createMock(ConfigManager::class);
28 $this->container->conf->method('getConfigFileExt')->willReturn(static::MOCK_FILE);
29 $this->container->conf->method('get')->willReturnCallback(function (string $key, $default) {
30 if ($key === 'resource.raintpl_tpl') {
31 return '.';
32 }
33
34 return $default ?? $key;
35 });
36
37 $this->controller = new InstallController($this->container);
38 }
39
40 protected function tearDown(): void
41 {
42 if (file_exists(static::MOCK_FILE)) {
43 unlink(static::MOCK_FILE);
44 }
45 }
46
47 /**
48 * Test displaying install page with valid session.
49 */
50 public function testInstallIndexWithValidSession(): void
51 {
52 $assignedVariables = [];
53 $this->assignTemplateVars($assignedVariables);
54
55 $request = $this->createMock(Request::class);
56 $response = new Response();
57
58 $this->container->sessionManager = $this->createMock(SessionManager::class);
59 $this->container->sessionManager
60 ->method('getSessionParameter')
61 ->willReturnCallback(function (string $key, $default) {
62 return $key === 'session_tested' ? 'Working' : $default;
63 })
64 ;
65
66 $result = $this->controller->index($request, $response);
67
68 static::assertSame(200, $result->getStatusCode());
69 static::assertSame('install', (string) $result->getBody());
70
71 static::assertIsArray($assignedVariables['continents']);
72 static::assertSame('Africa', $assignedVariables['continents'][0]);
73 static::assertSame('UTC', $assignedVariables['continents']['selected']);
74
75 static::assertIsArray($assignedVariables['cities']);
76 static::assertSame(['continent' => 'Africa', 'city' => 'Abidjan'], $assignedVariables['cities'][0]);
77 static::assertSame('UTC', $assignedVariables['continents']['selected']);
78
79 static::assertIsArray($assignedVariables['languages']);
80 static::assertSame('Automatic', $assignedVariables['languages']['auto']);
81 static::assertSame('French', $assignedVariables['languages']['fr']);
82
83 static::assertSame(PHP_VERSION, $assignedVariables['php_version']);
84 static::assertArrayHasKey('php_has_reached_eol', $assignedVariables);
85 static::assertArrayHasKey('php_eol', $assignedVariables);
86 static::assertArrayHasKey('php_extensions', $assignedVariables);
87 static::assertArrayHasKey('permissions', $assignedVariables);
88 static::assertEmpty($assignedVariables['permissions']);
89
90 static::assertSame('Install Shaarli', $assignedVariables['pagetitle']);
91 }
92
93 /**
94 * Instantiate the install controller with an existing config file: exception.
95 */
96 public function testInstallWithExistingConfigFile(): void
97 {
98 $this->expectException(AlreadyInstalledException::class);
99
100 touch(static::MOCK_FILE);
101
102 $this->controller = new InstallController($this->container);
103 }
104
105 /**
106 * Call controller without session yet defined, redirect to test session install page.
107 */
108 public function testInstallRedirectToSessionTest(): void
109 {
110 $request = $this->createMock(Request::class);
111 $response = new Response();
112
113 $this->container->sessionManager = $this->createMock(SessionManager::class);
114 $this->container->sessionManager
115 ->expects(static::once())
116 ->method('setSessionParameter')
117 ->with(InstallController::SESSION_TEST_KEY, InstallController::SESSION_TEST_VALUE)
118 ;
119
120 $result = $this->controller->index($request, $response);
121
122 static::assertSame(302, $result->getStatusCode());
123 static::assertSame('/subfolder/install/session-test', $result->getHeader('location')[0]);
124 }
125
126 /**
127 * Call controller in session test mode: valid session then redirect to install page.
128 */
129 public function testInstallSessionTestValid(): void
130 {
131 $request = $this->createMock(Request::class);
132 $response = new Response();
133
134 $this->container->sessionManager = $this->createMock(SessionManager::class);
135 $this->container->sessionManager
136 ->method('getSessionParameter')
137 ->with(InstallController::SESSION_TEST_KEY)
138 ->willReturn(InstallController::SESSION_TEST_VALUE)
139 ;
140
141 $result = $this->controller->sessionTest($request, $response);
142
143 static::assertSame(302, $result->getStatusCode());
144 static::assertSame('/subfolder/install', $result->getHeader('location')[0]);
145 }
146
147 /**
148 * Call controller in session test mode: invalid session then redirect to error page.
149 */
150 public function testInstallSessionTestError(): void
151 {
152 $assignedVars = [];
153 $this->assignTemplateVars($assignedVars);
154
155 $request = $this->createMock(Request::class);
156 $response = new Response();
157
158 $this->container->sessionManager = $this->createMock(SessionManager::class);
159 $this->container->sessionManager
160 ->method('getSessionParameter')
161 ->with(InstallController::SESSION_TEST_KEY)
162 ->willReturn('KO')
163 ;
164
165 $result = $this->controller->sessionTest($request, $response);
166
167 static::assertSame(200, $result->getStatusCode());
168 static::assertSame('error', (string) $result->getBody());
169 static::assertStringStartsWith(
170 '<pre>Sessions do not seem to work correctly on your server',
171 $assignedVars['message']
172 );
173 }
174
175 /**
176 * Test saving valid data from install form. Also initialize datastore.
177 */
178 public function testSaveInstallValid(): void
179 {
180 $providedParameters = [
181 'continent' => 'Europe',
182 'city' => 'Berlin',
183 'setlogin' => 'bob',
184 'setpassword' => 'password',
185 'title' => 'Shaarli',
186 'language' => 'fr',
187 'updateCheck' => true,
188 'enableApi' => true,
189 ];
190
191 $expectedSettings = [
192 'general.timezone' => 'Europe/Berlin',
193 'credentials.login' => 'bob',
194 'credentials.salt' => '_NOT_EMPTY',
195 'credentials.hash' => '_NOT_EMPTY',
196 'general.title' => 'Shaarli',
197 'translation.language' => 'en',
198 'updates.check_updates' => true,
199 'api.enabled' => true,
200 'api.secret' => '_NOT_EMPTY',
201 'general.header_link' => '/subfolder',
202 ];
203
204 $request = $this->createMock(Request::class);
205 $request->method('getParam')->willReturnCallback(function (string $key) use ($providedParameters) {
206 return $providedParameters[$key] ?? null;
207 });
208 $response = new Response();
209
210 $this->container->conf = $this->createMock(ConfigManager::class);
211 $this->container->conf
212 ->method('get')
213 ->willReturnCallback(function (string $key, $value) {
214 if ($key === 'credentials.login') {
215 return 'bob';
216 } elseif ($key === 'credentials.salt') {
217 return 'salt';
218 }
219
220 return $value;
221 })
222 ;
223 $this->container->conf
224 ->expects(static::exactly(count($expectedSettings)))
225 ->method('set')
226 ->willReturnCallback(function (string $key, $value) use ($expectedSettings) {
227 if ($expectedSettings[$key] ?? null === '_NOT_EMPTY') {
228 static::assertNotEmpty($value);
229 } else {
230 static::assertSame($expectedSettings[$key], $value);
231 }
232 })
233 ;
234 $this->container->conf->expects(static::once())->method('write');
235
236 $this->container->sessionManager
237 ->expects(static::once())
238 ->method('setSessionParameter')
239 ->with(SessionManager::KEY_SUCCESS_MESSAGES)
240 ;
241
242 $result = $this->controller->save($request, $response);
243
244 static::assertSame(302, $result->getStatusCode());
245 static::assertSame('/subfolder/login', $result->getHeader('location')[0]);
246 }
247
248 /**
249 * Test default settings (timezone and title).
250 * Also check that bookmarks are not initialized if
251 */
252 public function testSaveInstallDefaultValues(): void
253 {
254 $confSettings = [];
255
256 $request = $this->createMock(Request::class);
257 $response = new Response();
258
259 $this->container->conf->method('set')->willReturnCallback(function (string $key, $value) use (&$confSettings) {
260 $confSettings[$key] = $value;
261 });
262
263 $result = $this->controller->save($request, $response);
264
265 static::assertSame(302, $result->getStatusCode());
266 static::assertSame('/subfolder/login', $result->getHeader('location')[0]);
267
268 static::assertSame('UTC', $confSettings['general.timezone']);
269 static::assertSame('Shared bookmarks on http://shaarli/subfolder/', $confSettings['general.title']);
270 }
271
272 /**
273 * Same test as testSaveInstallDefaultValues() but for an instance install in root directory.
274 */
275 public function testSaveInstallDefaultValuesWithoutSubfolder(): void
276 {
277 $confSettings = [];
278
279 $this->container->environment = [
280 'SERVER_NAME' => 'shaarli',
281 'SERVER_PORT' => '80',
282 'REQUEST_URI' => '/install',
283 'REMOTE_ADDR' => '1.2.3.4',
284 'SCRIPT_NAME' => '/index.php',
285 ];
286
287 $this->container->basePath = '';
288
289 $request = $this->createMock(Request::class);
290 $response = new Response();
291
292 $this->container->conf->method('set')->willReturnCallback(function (string $key, $value) use (&$confSettings) {
293 $confSettings[$key] = $value;
294 });
295
296 $result = $this->controller->save($request, $response);
297
298 static::assertSame(302, $result->getStatusCode());
299 static::assertSame('/login', $result->getHeader('location')[0]);
300
301 static::assertSame('UTC', $confSettings['general.timezone']);
302 static::assertSame('Shared bookmarks on http://shaarli/', $confSettings['general.title']);
303 }
304}
diff --git a/tests/front/controller/visitor/LoginControllerTest.php b/tests/front/controller/visitor/LoginControllerTest.php
new file mode 100644
index 00000000..00d9eab3
--- /dev/null
+++ b/tests/front/controller/visitor/LoginControllerTest.php
@@ -0,0 +1,404 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Config\ConfigManager;
8use Shaarli\Front\Exception\LoginBannedException;
9use Shaarli\Front\Exception\WrongTokenException;
10use Shaarli\Render\TemplatePage;
11use Shaarli\Security\CookieManager;
12use Shaarli\Security\SessionManager;
13use Shaarli\TestCase;
14use Slim\Http\Request;
15use Slim\Http\Response;
16
17class LoginControllerTest extends TestCase
18{
19 use FrontControllerMockHelper;
20
21 /** @var LoginController */
22 protected $controller;
23
24 public function setUp(): void
25 {
26 $this->createContainer();
27
28 $this->container->cookieManager = $this->createMock(CookieManager::class);
29 $this->container->sessionManager->method('checkToken')->willReturn(true);
30
31 $this->controller = new LoginController($this->container);
32 }
33
34 /**
35 * Test displaying login form with valid parameters.
36 */
37 public function testValidControllerInvoke(): void
38 {
39 $request = $this->createMock(Request::class);
40 $request
41 ->expects(static::atLeastOnce())
42 ->method('getParam')
43 ->willReturnCallback(function (string $key) {
44 return 'returnurl' === $key ? '> referer' : null;
45 })
46 ;
47 $response = new Response();
48
49 $assignedVariables = [];
50 $this->container->pageBuilder
51 ->method('assign')
52 ->willReturnCallback(function ($key, $value) use (&$assignedVariables) {
53 $assignedVariables[$key] = $value;
54
55 return $this;
56 })
57 ;
58
59 $this->container->loginManager->method('canLogin')->willReturn(true);
60
61 $result = $this->controller->index($request, $response);
62
63 static::assertInstanceOf(Response::class, $result);
64 static::assertSame(200, $result->getStatusCode());
65 static::assertSame(TemplatePage::LOGIN, (string) $result->getBody());
66
67 static::assertSame('&gt; referer', $assignedVariables['returnurl']);
68 static::assertSame(true, $assignedVariables['remember_user_default']);
69 static::assertSame('Login - Shaarli', $assignedVariables['pagetitle']);
70 }
71
72 /**
73 * Test displaying login form with username defined in the request.
74 */
75 public function testValidControllerInvokeWithUserName(): void
76 {
77 $this->container->environment = ['HTTP_REFERER' => '> referer'];
78
79 $request = $this->createMock(Request::class);
80 $request
81 ->expects(static::atLeastOnce())
82 ->method('getParam')
83 ->willReturnCallback(function (string $key, $default) {
84 if ('login' === $key) {
85 return 'myUser>';
86 }
87
88 return $default;
89 })
90 ;
91 $response = new Response();
92
93 $assignedVariables = [];
94 $this->container->pageBuilder
95 ->method('assign')
96 ->willReturnCallback(function ($key, $value) use (&$assignedVariables) {
97 $assignedVariables[$key] = $value;
98
99 return $this;
100 })
101 ;
102
103 $this->container->loginManager->expects(static::once())->method('canLogin')->willReturn(true);
104
105 $result = $this->controller->index($request, $response);
106
107 static::assertInstanceOf(Response::class, $result);
108 static::assertSame(200, $result->getStatusCode());
109 static::assertSame('loginform', (string) $result->getBody());
110
111 static::assertSame('myUser&gt;', $assignedVariables['username']);
112 static::assertSame('&gt; referer', $assignedVariables['returnurl']);
113 static::assertSame(true, $assignedVariables['remember_user_default']);
114 static::assertSame('Login - Shaarli', $assignedVariables['pagetitle']);
115 }
116
117 /**
118 * Test displaying login page while being logged in.
119 */
120 public function testLoginControllerWhileLoggedIn(): void
121 {
122 $request = $this->createMock(Request::class);
123 $response = new Response();
124
125 $this->container->loginManager->expects(static::once())->method('isLoggedIn')->willReturn(true);
126
127 $result = $this->controller->index($request, $response);
128
129 static::assertInstanceOf(Response::class, $result);
130 static::assertSame(302, $result->getStatusCode());
131 static::assertSame(['/subfolder/'], $result->getHeader('Location'));
132 }
133
134 /**
135 * Test displaying login page with open shaarli configured: redirect to homepage.
136 */
137 public function testLoginControllerOpenShaarli(): void
138 {
139 $request = $this->createMock(Request::class);
140 $response = new Response();
141
142 $conf = $this->createMock(ConfigManager::class);
143 $conf->method('get')->willReturnCallback(function (string $parameter, $default) {
144 if ($parameter === 'security.open_shaarli') {
145 return true;
146 }
147 return $default;
148 });
149 $this->container->conf = $conf;
150
151 $result = $this->controller->index($request, $response);
152
153 static::assertInstanceOf(Response::class, $result);
154 static::assertSame(302, $result->getStatusCode());
155 static::assertSame(['/subfolder/'], $result->getHeader('Location'));
156 }
157
158 /**
159 * Test displaying login page while being banned.
160 */
161 public function testLoginControllerWhileBanned(): void
162 {
163 $request = $this->createMock(Request::class);
164 $response = new Response();
165
166 $this->container->loginManager->method('isLoggedIn')->willReturn(false);
167 $this->container->loginManager->method('canLogin')->willReturn(false);
168
169 $this->expectException(LoginBannedException::class);
170
171 $this->controller->index($request, $response);
172 }
173
174 /**
175 * Test processing login with valid parameters.
176 */
177 public function testProcessLoginWithValidParameters(): void
178 {
179 $parameters = [
180 'login' => 'bob',
181 'password' => 'pass',
182 ];
183 $request = $this->createMock(Request::class);
184 $request
185 ->expects(static::atLeastOnce())
186 ->method('getParam')
187 ->willReturnCallback(function (string $key) use ($parameters) {
188 return $parameters[$key] ?? null;
189 })
190 ;
191 $response = new Response();
192
193 $this->container->loginManager->method('canLogin')->willReturn(true);
194 $this->container->loginManager->expects(static::once())->method('handleSuccessfulLogin');
195 $this->container->loginManager
196 ->expects(static::once())
197 ->method('checkCredentials')
198 ->with('1.2.3.4', 'bob', 'pass')
199 ->willReturn(true)
200 ;
201 $this->container->loginManager->method('getStaySignedInToken')->willReturn(bin2hex(random_bytes(8)));
202
203 $this->container->sessionManager->expects(static::never())->method('extendSession');
204 $this->container->sessionManager->expects(static::once())->method('destroy');
205 $this->container->sessionManager
206 ->expects(static::once())
207 ->method('cookieParameters')
208 ->with(0, '/subfolder/', 'shaarli')
209 ;
210 $this->container->sessionManager->expects(static::once())->method('start');
211 $this->container->sessionManager->expects(static::once())->method('regenerateId')->with(true);
212
213 $result = $this->controller->login($request, $response);
214
215 static::assertSame(302, $result->getStatusCode());
216 static::assertSame('/subfolder/', $result->getHeader('location')[0]);
217 }
218
219 /**
220 * Test processing login with return URL.
221 */
222 public function testProcessLoginWithReturnUrl(): void
223 {
224 $parameters = [
225 'returnurl' => 'http://shaarli/subfolder/admin/shaare',
226 ];
227 $request = $this->createMock(Request::class);
228 $request
229 ->expects(static::atLeastOnce())
230 ->method('getParam')
231 ->willReturnCallback(function (string $key) use ($parameters) {
232 return $parameters[$key] ?? null;
233 })
234 ;
235 $response = new Response();
236
237 $this->container->loginManager->method('canLogin')->willReturn(true);
238 $this->container->loginManager->expects(static::once())->method('handleSuccessfulLogin');
239 $this->container->loginManager->expects(static::once())->method('checkCredentials')->willReturn(true);
240 $this->container->loginManager->method('getStaySignedInToken')->willReturn(bin2hex(random_bytes(8)));
241
242 $result = $this->controller->login($request, $response);
243
244 static::assertSame(302, $result->getStatusCode());
245 static::assertSame('/subfolder/admin/shaare', $result->getHeader('location')[0]);
246 }
247
248 /**
249 * Test processing login with remember me session enabled.
250 */
251 public function testProcessLoginLongLastingSession(): void
252 {
253 $parameters = [
254 'longlastingsession' => true,
255 ];
256 $request = $this->createMock(Request::class);
257 $request
258 ->expects(static::atLeastOnce())
259 ->method('getParam')
260 ->willReturnCallback(function (string $key) use ($parameters) {
261 return $parameters[$key] ?? null;
262 })
263 ;
264 $response = new Response();
265
266 $this->container->loginManager->method('canLogin')->willReturn(true);
267 $this->container->loginManager->expects(static::once())->method('handleSuccessfulLogin');
268 $this->container->loginManager->expects(static::once())->method('checkCredentials')->willReturn(true);
269 $this->container->loginManager->method('getStaySignedInToken')->willReturn(bin2hex(random_bytes(8)));
270
271 $this->container->sessionManager->expects(static::once())->method('destroy');
272 $this->container->sessionManager
273 ->expects(static::once())
274 ->method('cookieParameters')
275 ->with(42, '/subfolder/', 'shaarli')
276 ;
277 $this->container->sessionManager->expects(static::once())->method('start');
278 $this->container->sessionManager->expects(static::once())->method('regenerateId')->with(true);
279 $this->container->sessionManager->expects(static::once())->method('extendSession')->willReturn(42);
280
281 $this->container->cookieManager = $this->createMock(CookieManager::class);
282 $this->container->cookieManager
283 ->expects(static::once())
284 ->method('setCookieParameter')
285 ->willReturnCallback(function (string $name): CookieManager {
286 static::assertSame(CookieManager::STAY_SIGNED_IN, $name);
287
288 return $this->container->cookieManager;
289 })
290 ;
291
292 $result = $this->controller->login($request, $response);
293
294 static::assertSame(302, $result->getStatusCode());
295 static::assertSame('/subfolder/', $result->getHeader('location')[0]);
296 }
297
298 /**
299 * Test processing login with invalid credentials
300 */
301 public function testProcessLoginWrongCredentials(): void
302 {
303 $parameters = [
304 'returnurl' => 'http://shaarli/subfolder/admin/shaare',
305 ];
306 $request = $this->createMock(Request::class);
307 $request
308 ->expects(static::atLeastOnce())
309 ->method('getParam')
310 ->willReturnCallback(function (string $key) use ($parameters) {
311 return $parameters[$key] ?? null;
312 })
313 ;
314 $response = new Response();
315
316 $this->container->loginManager->method('canLogin')->willReturn(true);
317 $this->container->loginManager->expects(static::once())->method('handleFailedLogin');
318 $this->container->loginManager->expects(static::once())->method('checkCredentials')->willReturn(false);
319
320 $this->container->sessionManager
321 ->expects(static::once())
322 ->method('setSessionParameter')
323 ->with(SessionManager::KEY_ERROR_MESSAGES, ['Wrong login/password.'])
324 ;
325
326 $result = $this->controller->login($request, $response);
327
328 static::assertSame(200, $result->getStatusCode());
329 static::assertSame(TemplatePage::LOGIN, (string) $result->getBody());
330 }
331
332 /**
333 * Test processing login with wrong token
334 */
335 public function testProcessLoginWrongToken(): void
336 {
337 $request = $this->createMock(Request::class);
338 $response = new Response();
339
340 $this->container->sessionManager = $this->createMock(SessionManager::class);
341 $this->container->sessionManager->method('checkToken')->willReturn(false);
342
343 $this->expectException(WrongTokenException::class);
344
345 $this->controller->login($request, $response);
346 }
347
348 /**
349 * Test processing login with wrong token
350 */
351 public function testProcessLoginAlreadyLoggedIn(): void
352 {
353 $request = $this->createMock(Request::class);
354 $response = new Response();
355
356 $this->container->loginManager->method('isLoggedIn')->willReturn(true);
357 $this->container->loginManager->expects(static::never())->method('handleSuccessfulLogin');
358 $this->container->loginManager->expects(static::never())->method('handleFailedLogin');
359
360 $result = $this->controller->login($request, $response);
361
362 static::assertSame(302, $result->getStatusCode());
363 static::assertSame('/subfolder/', $result->getHeader('location')[0]);
364 }
365
366 /**
367 * Test processing login with wrong token
368 */
369 public function testProcessLoginInOpenShaarli(): void
370 {
371 $request = $this->createMock(Request::class);
372 $response = new Response();
373
374 $this->container->conf = $this->createMock(ConfigManager::class);
375 $this->container->conf->method('get')->willReturnCallback(function (string $key, $value) {
376 return 'security.open_shaarli' === $key ? true : $value;
377 });
378
379 $this->container->loginManager->expects(static::never())->method('handleSuccessfulLogin');
380 $this->container->loginManager->expects(static::never())->method('handleFailedLogin');
381
382 $result = $this->controller->login($request, $response);
383
384 static::assertSame(302, $result->getStatusCode());
385 static::assertSame('/subfolder/', $result->getHeader('location')[0]);
386 }
387
388 /**
389 * Test processing login while being banned
390 */
391 public function testProcessLoginWhileBanned(): void
392 {
393 $request = $this->createMock(Request::class);
394 $response = new Response();
395
396 $this->container->loginManager->method('canLogin')->willReturn(false);
397 $this->container->loginManager->expects(static::never())->method('handleSuccessfulLogin');
398 $this->container->loginManager->expects(static::never())->method('handleFailedLogin');
399
400 $this->expectException(LoginBannedException::class);
401
402 $this->controller->login($request, $response);
403 }
404}
diff --git a/tests/front/controller/visitor/OpenSearchControllerTest.php b/tests/front/controller/visitor/OpenSearchControllerTest.php
new file mode 100644
index 00000000..42d876c3
--- /dev/null
+++ b/tests/front/controller/visitor/OpenSearchControllerTest.php
@@ -0,0 +1,44 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\TestCase;
8use Slim\Http\Request;
9use Slim\Http\Response;
10
11class OpenSearchControllerTest extends TestCase
12{
13 use FrontControllerMockHelper;
14
15 /** @var OpenSearchController */
16 protected $controller;
17
18 public function setUp(): void
19 {
20 $this->createContainer();
21
22 $this->controller = new OpenSearchController($this->container);
23 }
24
25 public function testOpenSearchController(): void
26 {
27 $request = $this->createMock(Request::class);
28 $response = new Response();
29
30 // Save RainTPL assigned variables
31 $assignedVariables = [];
32 $this->assignTemplateVars($assignedVariables);
33
34 $result = $this->controller->index($request, $response);
35
36 static::assertSame(200, $result->getStatusCode());
37 static::assertStringContainsString(
38 'application/opensearchdescription+xml',
39 $result->getHeader('Content-Type')[0]
40 );
41 static::assertSame('opensearch', (string) $result->getBody());
42 static::assertSame('http://shaarli/subfolder/', $assignedVariables['serverurl']);
43 }
44}
diff --git a/tests/front/controller/visitor/PictureWallControllerTest.php b/tests/front/controller/visitor/PictureWallControllerTest.php
new file mode 100644
index 00000000..b868231d
--- /dev/null
+++ b/tests/front/controller/visitor/PictureWallControllerTest.php
@@ -0,0 +1,123 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Bookmark\Bookmark;
8use Shaarli\Config\ConfigManager;
9use Shaarli\Front\Exception\ThumbnailsDisabledException;
10use Shaarli\TestCase;
11use Shaarli\Thumbnailer;
12use Slim\Http\Request;
13use Slim\Http\Response;
14
15class PictureWallControllerTest extends TestCase
16{
17 use FrontControllerMockHelper;
18
19 /** @var PictureWallController */
20 protected $controller;
21
22 public function setUp(): void
23 {
24 $this->createContainer();
25
26 $this->controller = new PictureWallController($this->container);
27 }
28
29 public function testValidControllerInvokeDefault(): void
30 {
31 $request = $this->createMock(Request::class);
32 $request->expects(static::once())->method('getQueryParams')->willReturn([]);
33 $response = new Response();
34
35 // ConfigManager: thumbnails are enabled
36 $this->container->conf = $this->createMock(ConfigManager::class);
37 $this->container->conf->method('get')->willReturnCallback(function (string $parameter, $default) {
38 if ($parameter === 'thumbnails.mode') {
39 return Thumbnailer::MODE_COMMON;
40 }
41
42 return $default;
43 });
44
45 // Save RainTPL assigned variables
46 $assignedVariables = [];
47 $this->assignTemplateVars($assignedVariables);
48
49 // Links dataset: 2 links with thumbnails
50 $this->container->bookmarkService
51 ->expects(static::once())
52 ->method('search')
53 ->willReturnCallback(function (array $parameters, ?string $visibility): array {
54 // Visibility is set through the container, not the call
55 static::assertNull($visibility);
56
57 // No query parameters
58 if (count($parameters) === 0) {
59 return [
60 (new Bookmark())->setId(1)->setUrl('http://url.tld')->setThumbnail('thumb1'),
61 (new Bookmark())->setId(2)->setUrl('http://url2.tld'),
62 (new Bookmark())->setId(3)->setUrl('http://url3.tld')->setThumbnail('thumb2'),
63 ];
64 }
65 })
66 ;
67
68 // Make sure that PluginManager hook is triggered
69 $this->container->pluginManager
70 ->expects(static::atLeastOnce())
71 ->method('executeHooks')
72 ->withConsecutive(['render_picwall'])
73 ->willReturnCallback(function (string $hook, array $data, array $param): array {
74 if ('render_picwall' === $hook) {
75 static::assertArrayHasKey('linksToDisplay', $data);
76 static::assertCount(2, $data['linksToDisplay']);
77 static::assertSame(1, $data['linksToDisplay'][0]['id']);
78 static::assertSame(3, $data['linksToDisplay'][1]['id']);
79 static::assertArrayHasKey('loggedin', $param);
80 }
81
82 return $data;
83 });
84
85 $result = $this->controller->index($request, $response);
86
87 static::assertSame(200, $result->getStatusCode());
88 static::assertSame('picwall', (string) $result->getBody());
89 static::assertSame('Picture wall - Shaarli', $assignedVariables['pagetitle']);
90 static::assertCount(2, $assignedVariables['linksToDisplay']);
91
92 $link = $assignedVariables['linksToDisplay'][0];
93
94 static::assertSame(1, $link['id']);
95 static::assertSame('http://url.tld', $link['url']);
96 static::assertSame('thumb1', $link['thumbnail']);
97
98 $link = $assignedVariables['linksToDisplay'][1];
99
100 static::assertSame(3, $link['id']);
101 static::assertSame('http://url3.tld', $link['url']);
102 static::assertSame('thumb2', $link['thumbnail']);
103 }
104
105 public function testControllerWithThumbnailsDisabled(): void
106 {
107 $this->expectException(ThumbnailsDisabledException::class);
108
109 $request = $this->createMock(Request::class);
110 $response = new Response();
111
112 // ConfigManager: thumbnails are disabled
113 $this->container->conf->method('get')->willReturnCallback(function (string $parameter, $default) {
114 if ($parameter === 'thumbnails.mode') {
115 return Thumbnailer::MODE_NONE;
116 }
117
118 return $default;
119 });
120
121 $this->controller->index($request, $response);
122 }
123}
diff --git a/tests/front/controller/visitor/PublicSessionFilterControllerTest.php b/tests/front/controller/visitor/PublicSessionFilterControllerTest.php
new file mode 100644
index 00000000..7e3b00af
--- /dev/null
+++ b/tests/front/controller/visitor/PublicSessionFilterControllerTest.php
@@ -0,0 +1,122 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Security\SessionManager;
8use Shaarli\TestCase;
9use Slim\Http\Request;
10use Slim\Http\Response;
11
12class PublicSessionFilterControllerTest extends TestCase
13{
14 use FrontControllerMockHelper;
15
16 /** @var PublicSessionFilterController */
17 protected $controller;
18
19 public function setUp(): void
20 {
21 $this->createContainer();
22
23 $this->controller = new PublicSessionFilterController($this->container);
24 }
25
26 /**
27 * Link per page - Default call with valid parameter and a referer.
28 */
29 public function testLinksPerPage(): void
30 {
31 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller/?searchtag=abc';
32
33 $request = $this->createMock(Request::class);
34 $request->method('getParam')->with('nb')->willReturn('8');
35 $response = new Response();
36
37 $this->container->sessionManager
38 ->expects(static::once())
39 ->method('setSessionParameter')
40 ->with(SessionManager::KEY_LINKS_PER_PAGE, 8)
41 ;
42
43 $result = $this->controller->linksPerPage($request, $response);
44
45 static::assertInstanceOf(Response::class, $result);
46 static::assertSame(302, $result->getStatusCode());
47 static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location'));
48 }
49
50 /**
51 * Link per page - Invalid value, should use default value (20)
52 */
53 public function testLinksPerPageNotValid(): void
54 {
55 $request = $this->createMock(Request::class);
56 $request->method('getParam')->with('nb')->willReturn('test');
57 $response = new Response();
58
59 $this->container->sessionManager
60 ->expects(static::once())
61 ->method('setSessionParameter')
62 ->with(SessionManager::KEY_LINKS_PER_PAGE, 20)
63 ;
64
65 $result = $this->controller->linksPerPage($request, $response);
66
67 static::assertInstanceOf(Response::class, $result);
68 static::assertSame(302, $result->getStatusCode());
69 static::assertSame(['/subfolder/'], $result->getHeader('location'));
70 }
71
72 /**
73 * Untagged only - valid call
74 */
75 public function testUntaggedOnly(): void
76 {
77 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller/?searchtag=abc';
78
79 $request = $this->createMock(Request::class);
80 $response = new Response();
81
82 $this->container->sessionManager
83 ->expects(static::once())
84 ->method('setSessionParameter')
85 ->with(SessionManager::KEY_UNTAGGED_ONLY, true)
86 ;
87
88 $result = $this->controller->untaggedOnly($request, $response);
89
90 static::assertInstanceOf(Response::class, $result);
91 static::assertSame(302, $result->getStatusCode());
92 static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location'));
93 }
94
95 /**
96 * Untagged only - toggle off
97 */
98 public function testUntaggedOnlyToggleOff(): void
99 {
100 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller/?searchtag=abc';
101
102 $request = $this->createMock(Request::class);
103 $response = new Response();
104
105 $this->container->sessionManager
106 ->method('getSessionParameter')
107 ->with(SessionManager::KEY_UNTAGGED_ONLY)
108 ->willReturn(true)
109 ;
110 $this->container->sessionManager
111 ->expects(static::once())
112 ->method('setSessionParameter')
113 ->with(SessionManager::KEY_UNTAGGED_ONLY, false)
114 ;
115
116 $result = $this->controller->untaggedOnly($request, $response);
117
118 static::assertInstanceOf(Response::class, $result);
119 static::assertSame(302, $result->getStatusCode());
120 static::assertSame(['/subfolder/controller/?searchtag=abc'], $result->getHeader('location'));
121 }
122}
diff --git a/tests/front/controller/visitor/ShaarliVisitorControllerTest.php b/tests/front/controller/visitor/ShaarliVisitorControllerTest.php
new file mode 100644
index 00000000..935ec24e
--- /dev/null
+++ b/tests/front/controller/visitor/ShaarliVisitorControllerTest.php
@@ -0,0 +1,246 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Bookmark\BookmarkFilter;
8use Shaarli\TestCase;
9use Slim\Http\Request;
10use Slim\Http\Response;
11
12/**
13 * Class ShaarliControllerTest
14 *
15 * This class is used to test default behavior of ShaarliVisitorController abstract class.
16 * It uses a dummy non abstract controller.
17 */
18class ShaarliVisitorControllerTest extends TestCase
19{
20 use FrontControllerMockHelper;
21
22 /** @var LoginController */
23 protected $controller;
24
25 /** @var mixed[] List of variable assigned to the template */
26 protected $assignedValues;
27
28 /** @var Request */
29 protected $request;
30
31 public function setUp(): void
32 {
33 $this->createContainer();
34
35 $this->controller = new class($this->container) extends ShaarliVisitorController
36 {
37 public function assignView(string $key, $value): ShaarliVisitorController
38 {
39 return parent::assignView($key, $value);
40 }
41
42 public function render(string $template): string
43 {
44 return parent::render($template);
45 }
46
47 public function redirectFromReferer(
48 Request $request,
49 Response $response,
50 array $loopTerms = [],
51 array $clearParams = [],
52 string $anchor = null
53 ): Response {
54 return parent::redirectFromReferer($request, $response, $loopTerms, $clearParams, $anchor);
55 }
56 };
57 $this->assignedValues = [];
58
59 $this->request = $this->createMock(Request::class);
60 }
61
62 public function testAssignView(): void
63 {
64 $this->assignTemplateVars($this->assignedValues);
65
66 $self = $this->controller->assignView('variableName', 'variableValue');
67
68 static::assertInstanceOf(ShaarliVisitorController::class, $self);
69 static::assertSame('variableValue', $this->assignedValues['variableName']);
70 }
71
72 public function testRender(): void
73 {
74 $this->assignTemplateVars($this->assignedValues);
75
76 $this->container->bookmarkService
77 ->method('count')
78 ->willReturnCallback(function (string $visibility): int {
79 return $visibility === BookmarkFilter::$PRIVATE ? 5 : 10;
80 })
81 ;
82
83 $this->container->pluginManager
84 ->method('executeHooks')
85 ->willReturnCallback(function (string $hook, array &$data, array $params): array {
86 return $data[$hook] = $params;
87 });
88 $this->container->pluginManager->method('getErrors')->willReturn(['error']);
89
90 $this->container->loginManager->method('isLoggedIn')->willReturn(true);
91
92 $render = $this->controller->render('templateName');
93
94 static::assertSame('templateName', $render);
95
96 static::assertSame(10, $this->assignedValues['linkcount']);
97 static::assertSame(5, $this->assignedValues['privateLinkcount']);
98 static::assertSame(['error'], $this->assignedValues['plugin_errors']);
99
100 static::assertSame('templateName', $this->assignedValues['plugins_includes']['render_includes']['target']);
101 static::assertTrue($this->assignedValues['plugins_includes']['render_includes']['loggedin']);
102 static::assertSame('templateName', $this->assignedValues['plugins_header']['render_header']['target']);
103 static::assertTrue($this->assignedValues['plugins_header']['render_header']['loggedin']);
104 static::assertSame('templateName', $this->assignedValues['plugins_footer']['render_footer']['target']);
105 static::assertTrue($this->assignedValues['plugins_footer']['render_footer']['loggedin']);
106 }
107
108 /**
109 * Test redirectFromReferer() - Default behaviour
110 */
111 public function testRedirectFromRefererDefault(): void
112 {
113 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
114
115 $response = new Response();
116
117 $result = $this->controller->redirectFromReferer($this->request, $response);
118
119 static::assertSame(302, $result->getStatusCode());
120 static::assertSame(['/subfolder/controller?query=param&other=2'], $result->getHeader('location'));
121 }
122
123 /**
124 * Test redirectFromReferer() - With a loop term not matched in the referer
125 */
126 public function testRedirectFromRefererWithUnmatchedLoopTerm(): void
127 {
128 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
129
130 $response = new Response();
131
132 $result = $this->controller->redirectFromReferer($this->request, $response, ['nope']);
133
134 static::assertSame(302, $result->getStatusCode());
135 static::assertSame(['/subfolder/controller?query=param&other=2'], $result->getHeader('location'));
136 }
137
138 /**
139 * Test redirectFromReferer() - With a loop term matching the referer in its path -> redirect to default
140 */
141 public function testRedirectFromRefererWithMatchingLoopTermInPath(): void
142 {
143 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
144
145 $response = new Response();
146
147 $result = $this->controller->redirectFromReferer($this->request, $response, ['nope', 'controller']);
148
149 static::assertSame(302, $result->getStatusCode());
150 static::assertSame(['/subfolder/'], $result->getHeader('location'));
151 }
152
153 /**
154 * Test redirectFromReferer() - With a loop term matching the referer in its query parameters -> redirect to default
155 */
156 public function testRedirectFromRefererWithMatchingLoopTermInQueryParam(): void
157 {
158 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
159
160 $response = new Response();
161
162 $result = $this->controller->redirectFromReferer($this->request, $response, ['nope', 'other']);
163
164 static::assertSame(302, $result->getStatusCode());
165 static::assertSame(['/subfolder/'], $result->getHeader('location'));
166 }
167
168 /**
169 * Test redirectFromReferer() - With a loop term matching the referer in its query value
170 * -> we do not block redirection for query parameter values.
171 */
172 public function testRedirectFromRefererWithMatchingLoopTermInQueryValue(): void
173 {
174 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
175
176 $response = new Response();
177
178 $result = $this->controller->redirectFromReferer($this->request, $response, ['nope', 'param']);
179
180 static::assertSame(302, $result->getStatusCode());
181 static::assertSame(['/subfolder/controller?query=param&other=2'], $result->getHeader('location'));
182 }
183
184 /**
185 * Test redirectFromReferer() - With a loop term matching the referer in its domain name
186 * -> we do not block redirection for shaarli's hosts
187 */
188 public function testRedirectFromRefererWithLoopTermInDomain(): void
189 {
190 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
191
192 $response = new Response();
193
194 $result = $this->controller->redirectFromReferer($this->request, $response, ['shaarli']);
195
196 static::assertSame(302, $result->getStatusCode());
197 static::assertSame(['/subfolder/controller?query=param&other=2'], $result->getHeader('location'));
198 }
199
200 /**
201 * Test redirectFromReferer() - With a loop term matching a query parameter AND clear this query param
202 * -> the param should be cleared before checking if it matches the redir loop terms
203 */
204 public function testRedirectFromRefererWithMatchingClearedParam(): void
205 {
206 $this->container->environment['HTTP_REFERER'] = 'http://shaarli/subfolder/controller?query=param&other=2';
207
208 $response = new Response();
209
210 $result = $this->controller->redirectFromReferer($this->request, $response, ['query'], ['query']);
211
212 static::assertSame(302, $result->getStatusCode());
213 static::assertSame(['/subfolder/controller?other=2'], $result->getHeader('location'));
214 }
215
216 /**
217 * Test redirectFromReferer() - From another domain -> we ignore the given referrer.
218 */
219 public function testRedirectExternalReferer(): void
220 {
221 $this->container->environment['HTTP_REFERER'] = 'http://other.domain.tld/controller?query=param&other=2';
222
223 $response = new Response();
224
225 $result = $this->controller->redirectFromReferer($this->request, $response, ['query'], ['query']);
226
227 static::assertSame(302, $result->getStatusCode());
228 static::assertSame(['/subfolder/'], $result->getHeader('location'));
229 }
230
231 /**
232 * Test redirectFromReferer() - From another domain -> we ignore the given referrer.
233 */
234 public function testRedirectExternalRefererExplicitDomainName(): void
235 {
236 $this->container->environment['SERVER_NAME'] = 'my.shaarli.tld';
237 $this->container->environment['HTTP_REFERER'] = 'http://your.shaarli.tld/controller?query=param&other=2';
238
239 $response = new Response();
240
241 $result = $this->controller->redirectFromReferer($this->request, $response, ['query'], ['query']);
242
243 static::assertSame(302, $result->getStatusCode());
244 static::assertSame(['/subfolder/'], $result->getHeader('location'));
245 }
246}
diff --git a/tests/front/controller/visitor/TagCloudControllerTest.php b/tests/front/controller/visitor/TagCloudControllerTest.php
new file mode 100644
index 00000000..9305612e
--- /dev/null
+++ b/tests/front/controller/visitor/TagCloudControllerTest.php
@@ -0,0 +1,381 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\Bookmark\BookmarkFilter;
8use Shaarli\TestCase;
9use Slim\Http\Request;
10use Slim\Http\Response;
11
12class TagCloudControllerTest extends TestCase
13{
14 use FrontControllerMockHelper;
15
16 /** @var TagCloudController */
17 protected $controller;
18
19 public function setUp(): void
20 {
21 $this->createContainer();
22
23 $this->controller = new TagCloudController($this->container);
24 }
25
26 /**
27 * Tag Cloud - default parameters
28 */
29 public function testValidCloudControllerInvokeDefault(): void
30 {
31 $allTags = [
32 'ghi' => 1,
33 'abc' => 3,
34 'def' => 12,
35 ];
36 $expectedOrder = ['abc', 'def', 'ghi'];
37
38 $request = $this->createMock(Request::class);
39 $response = new Response();
40
41 // Save RainTPL assigned variables
42 $assignedVariables = [];
43 $this->assignTemplateVars($assignedVariables);
44
45 $this->container->bookmarkService
46 ->expects(static::once())
47 ->method('bookmarksCountPerTag')
48 ->with([], null)
49 ->willReturnCallback(function () use ($allTags): array {
50 return $allTags;
51 })
52 ;
53
54 // Make sure that PluginManager hook is triggered
55 $this->container->pluginManager
56 ->expects(static::atLeastOnce())
57 ->method('executeHooks')
58 ->withConsecutive(['render_tagcloud'])
59 ->willReturnCallback(function (string $hook, array $data, array $param): array {
60 if ('render_tagcloud' === $hook) {
61 static::assertSame('', $data['search_tags']);
62 static::assertCount(3, $data['tags']);
63
64 static::assertArrayHasKey('loggedin', $param);
65 }
66
67 return $data;
68 })
69 ;
70
71 $result = $this->controller->cloud($request, $response);
72
73 static::assertSame(200, $result->getStatusCode());
74 static::assertSame('tag.cloud', (string) $result->getBody());
75 static::assertSame('Tag cloud - Shaarli', $assignedVariables['pagetitle']);
76
77 static::assertSame('', $assignedVariables['search_tags']);
78 static::assertCount(3, $assignedVariables['tags']);
79 static::assertSame($expectedOrder, array_keys($assignedVariables['tags']));
80
81 foreach ($allTags as $tag => $count) {
82 static::assertArrayHasKey($tag, $assignedVariables['tags']);
83 static::assertSame($count, $assignedVariables['tags'][$tag]['count']);
84 static::assertGreaterThan(0, $assignedVariables['tags'][$tag]['size']);
85 static::assertLessThan(5, $assignedVariables['tags'][$tag]['size']);
86 }
87 }
88
89 /**
90 * Tag Cloud - Additional parameters:
91 * - logged in
92 * - visibility private
93 * - search tags: `ghi` and `def` (note that filtered tags are not displayed anymore)
94 */
95 public function testValidCloudControllerInvokeWithParameters(): void
96 {
97 $request = $this->createMock(Request::class);
98 $request
99 ->method('getQueryParam')
100 ->with()
101 ->willReturnCallback(function (string $key): ?string {
102 if ('searchtags' === $key) {
103 return 'ghi def';
104 }
105
106 return null;
107 })
108 ;
109 $response = new Response();
110
111 // Save RainTPL assigned variables
112 $assignedVariables = [];
113 $this->assignTemplateVars($assignedVariables);
114
115 $this->container->loginManager->method('isLoggedin')->willReturn(true);
116 $this->container->sessionManager->expects(static::once())->method('getSessionParameter')->willReturn('private');
117
118 $this->container->bookmarkService
119 ->expects(static::once())
120 ->method('bookmarksCountPerTag')
121 ->with(['ghi', 'def'], BookmarkFilter::$PRIVATE)
122 ->willReturnCallback(function (): array {
123 return ['abc' => 3];
124 })
125 ;
126
127 // Make sure that PluginManager hook is triggered
128 $this->container->pluginManager
129 ->expects(static::atLeastOnce())
130 ->method('executeHooks')
131 ->withConsecutive(['render_tagcloud'])
132 ->willReturnCallback(function (string $hook, array $data, array $param): array {
133 if ('render_tagcloud' === $hook) {
134 static::assertSame('ghi def', $data['search_tags']);
135 static::assertCount(1, $data['tags']);
136
137 static::assertArrayHasKey('loggedin', $param);
138 }
139
140 return $data;
141 })
142 ;
143
144 $result = $this->controller->cloud($request, $response);
145
146 static::assertSame(200, $result->getStatusCode());
147 static::assertSame('tag.cloud', (string) $result->getBody());
148 static::assertSame('ghi def - Tag cloud - Shaarli', $assignedVariables['pagetitle']);
149
150 static::assertSame('ghi def', $assignedVariables['search_tags']);
151 static::assertCount(1, $assignedVariables['tags']);
152
153 static::assertArrayHasKey('abc', $assignedVariables['tags']);
154 static::assertSame(3, $assignedVariables['tags']['abc']['count']);
155 static::assertGreaterThan(0, $assignedVariables['tags']['abc']['size']);
156 static::assertLessThan(5, $assignedVariables['tags']['abc']['size']);
157 }
158
159 /**
160 * Tag Cloud - empty
161 */
162 public function testEmptyCloud(): void
163 {
164 $request = $this->createMock(Request::class);
165 $response = new Response();
166
167 // Save RainTPL assigned variables
168 $assignedVariables = [];
169 $this->assignTemplateVars($assignedVariables);
170
171 $this->container->bookmarkService
172 ->expects(static::once())
173 ->method('bookmarksCountPerTag')
174 ->with([], null)
175 ->willReturnCallback(function (array $parameters, ?string $visibility): array {
176 return [];
177 })
178 ;
179
180 // Make sure that PluginManager hook is triggered
181 $this->container->pluginManager
182 ->expects(static::atLeastOnce())
183 ->method('executeHooks')
184 ->withConsecutive(['render_tagcloud'])
185 ->willReturnCallback(function (string $hook, array $data, array $param): array {
186 if ('render_tagcloud' === $hook) {
187 static::assertSame('', $data['search_tags']);
188 static::assertCount(0, $data['tags']);
189
190 static::assertArrayHasKey('loggedin', $param);
191 }
192
193 return $data;
194 })
195 ;
196
197 $result = $this->controller->cloud($request, $response);
198
199 static::assertSame(200, $result->getStatusCode());
200 static::assertSame('tag.cloud', (string) $result->getBody());
201 static::assertSame('Tag cloud - Shaarli', $assignedVariables['pagetitle']);
202
203 static::assertSame('', $assignedVariables['search_tags']);
204 static::assertCount(0, $assignedVariables['tags']);
205 }
206
207 /**
208 * Tag List - Default sort is by usage DESC
209 */
210 public function testValidListControllerInvokeDefault(): void
211 {
212 $allTags = [
213 'def' => 12,
214 'abc' => 3,
215 'ghi' => 1,
216 ];
217
218 $request = $this->createMock(Request::class);
219 $response = new Response();
220
221 // Save RainTPL assigned variables
222 $assignedVariables = [];
223 $this->assignTemplateVars($assignedVariables);
224
225 $this->container->bookmarkService
226 ->expects(static::once())
227 ->method('bookmarksCountPerTag')
228 ->with([], null)
229 ->willReturnCallback(function () use ($allTags): array {
230 return $allTags;
231 })
232 ;
233
234 // Make sure that PluginManager hook is triggered
235 $this->container->pluginManager
236 ->expects(static::atLeastOnce())
237 ->method('executeHooks')
238 ->withConsecutive(['render_taglist'])
239 ->willReturnCallback(function (string $hook, array $data, array $param): array {
240 if ('render_taglist' === $hook) {
241 static::assertSame('', $data['search_tags']);
242 static::assertCount(3, $data['tags']);
243
244 static::assertArrayHasKey('loggedin', $param);
245 }
246
247 return $data;
248 })
249 ;
250
251 $result = $this->controller->list($request, $response);
252
253 static::assertSame(200, $result->getStatusCode());
254 static::assertSame('tag.list', (string) $result->getBody());
255 static::assertSame('Tag list - Shaarli', $assignedVariables['pagetitle']);
256
257 static::assertSame('', $assignedVariables['search_tags']);
258 static::assertCount(3, $assignedVariables['tags']);
259
260 foreach ($allTags as $tag => $count) {
261 static::assertSame($count, $assignedVariables['tags'][$tag]);
262 }
263 }
264
265 /**
266 * Tag List - Additional parameters:
267 * - logged in
268 * - visibility private
269 * - search tags: `ghi` and `def` (note that filtered tags are not displayed anymore)
270 * - sort alphabetically
271 */
272 public function testValidListControllerInvokeWithParameters(): void
273 {
274 $request = $this->createMock(Request::class);
275 $request
276 ->method('getQueryParam')
277 ->with()
278 ->willReturnCallback(function (string $key): ?string {
279 if ('searchtags' === $key) {
280 return 'ghi def';
281 } elseif ('sort' === $key) {
282 return 'alpha';
283 }
284
285 return null;
286 })
287 ;
288 $response = new Response();
289
290 // Save RainTPL assigned variables
291 $assignedVariables = [];
292 $this->assignTemplateVars($assignedVariables);
293
294 $this->container->loginManager->method('isLoggedin')->willReturn(true);
295 $this->container->sessionManager->expects(static::once())->method('getSessionParameter')->willReturn('private');
296
297 $this->container->bookmarkService
298 ->expects(static::once())
299 ->method('bookmarksCountPerTag')
300 ->with(['ghi', 'def'], BookmarkFilter::$PRIVATE)
301 ->willReturnCallback(function (): array {
302 return ['abc' => 3];
303 })
304 ;
305
306 // Make sure that PluginManager hook is triggered
307 $this->container->pluginManager
308 ->expects(static::atLeastOnce())
309 ->method('executeHooks')
310 ->withConsecutive(['render_taglist'])
311 ->willReturnCallback(function (string $hook, array $data, array $param): array {
312 if ('render_taglist' === $hook) {
313 static::assertSame('ghi def', $data['search_tags']);
314 static::assertCount(1, $data['tags']);
315
316 static::assertArrayHasKey('loggedin', $param);
317 }
318
319 return $data;
320 })
321 ;
322
323 $result = $this->controller->list($request, $response);
324
325 static::assertSame(200, $result->getStatusCode());
326 static::assertSame('tag.list', (string) $result->getBody());
327 static::assertSame('ghi def - Tag list - Shaarli', $assignedVariables['pagetitle']);
328
329 static::assertSame('ghi def', $assignedVariables['search_tags']);
330 static::assertCount(1, $assignedVariables['tags']);
331 static::assertSame(3, $assignedVariables['tags']['abc']);
332 }
333
334 /**
335 * Tag List - empty
336 */
337 public function testEmptyList(): void
338 {
339 $request = $this->createMock(Request::class);
340 $response = new Response();
341
342 // Save RainTPL assigned variables
343 $assignedVariables = [];
344 $this->assignTemplateVars($assignedVariables);
345
346 $this->container->bookmarkService
347 ->expects(static::once())
348 ->method('bookmarksCountPerTag')
349 ->with([], null)
350 ->willReturnCallback(function (array $parameters, ?string $visibility): array {
351 return [];
352 })
353 ;
354
355 // Make sure that PluginManager hook is triggered
356 $this->container->pluginManager
357 ->expects(static::atLeastOnce())
358 ->method('executeHooks')
359 ->withConsecutive(['render_taglist'])
360 ->willReturnCallback(function (string $hook, array $data, array $param): array {
361 if ('render_taglist' === $hook) {
362 static::assertSame('', $data['search_tags']);
363 static::assertCount(0, $data['tags']);
364
365 static::assertArrayHasKey('loggedin', $param);
366 }
367
368 return $data;
369 })
370 ;
371
372 $result = $this->controller->list($request, $response);
373
374 static::assertSame(200, $result->getStatusCode());
375 static::assertSame('tag.list', (string) $result->getBody());
376 static::assertSame('Tag list - Shaarli', $assignedVariables['pagetitle']);
377
378 static::assertSame('', $assignedVariables['search_tags']);
379 static::assertCount(0, $assignedVariables['tags']);
380 }
381}
diff --git a/tests/front/controller/visitor/TagControllerTest.php b/tests/front/controller/visitor/TagControllerTest.php
new file mode 100644
index 00000000..750ea02d
--- /dev/null
+++ b/tests/front/controller/visitor/TagControllerTest.php
@@ -0,0 +1,215 @@
1<?php
2
3declare(strict_types=1);
4
5namespace Shaarli\Front\Controller\Visitor;
6
7use Shaarli\TestCase;
8use Slim\Http\Request;
9use Slim\Http\Response;
10
11class TagControllerTest extends TestCase
12{
13 use FrontControllerMockHelper;
14
15 /** @var TagController */ protected $controller;
16
17 public function setUp(): void
18 {
19 $this->createContainer();
20
21 $this->controller = new TagController($this->container);
22 }
23
24 public function testAddTagWithReferer(): void
25 {
26 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/'];
27
28 $request = $this->createMock(Request::class);
29 $response = new Response();
30
31 $tags = ['newTag' => 'abc'];
32
33 $result = $this->controller->addTag($request, $response, $tags);
34
35 static::assertInstanceOf(Response::class, $result);
36 static::assertSame(302, $result->getStatusCode());
37 static::assertSame(['/controller/?searchtags=abc'], $result->getHeader('location'));
38 }
39
40 public function testAddTagWithRefererAndExistingSearch(): void
41 {
42 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtags=def'];
43
44 $request = $this->createMock(Request::class);
45 $response = new Response();
46
47 $tags = ['newTag' => 'abc'];
48
49 $result = $this->controller->addTag($request, $response, $tags);
50
51 static::assertInstanceOf(Response::class, $result);
52 static::assertSame(302, $result->getStatusCode());
53 static::assertSame(['/controller/?searchtags=def+abc'], $result->getHeader('location'));
54 }
55
56 public function testAddTagWithoutRefererAndExistingSearch(): void
57 {
58 $request = $this->createMock(Request::class);
59 $response = new Response();
60
61 $tags = ['newTag' => 'abc'];
62
63 $result = $this->controller->addTag($request, $response, $tags);
64
65 static::assertInstanceOf(Response::class, $result);
66 static::assertSame(302, $result->getStatusCode());
67 static::assertSame(['/subfolder/?searchtags=abc'], $result->getHeader('location'));
68 }
69
70 public function testAddTagRemoveLegacyQueryParam(): void
71 {
72 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtags=def&addtag=abc'];
73
74 $request = $this->createMock(Request::class);
75 $response = new Response();
76
77 $tags = ['newTag' => 'abc'];
78
79 $result = $this->controller->addTag($request, $response, $tags);
80
81 static::assertInstanceOf(Response::class, $result);
82 static::assertSame(302, $result->getStatusCode());
83 static::assertSame(['/controller/?searchtags=def+abc'], $result->getHeader('location'));
84 }
85
86 public function testAddTagResetPagination(): void
87 {
88 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtags=def&page=12'];
89
90 $request = $this->createMock(Request::class);
91 $response = new Response();
92
93 $tags = ['newTag' => 'abc'];
94
95 $result = $this->controller->addTag($request, $response, $tags);
96
97 static::assertInstanceOf(Response::class, $result);
98 static::assertSame(302, $result->getStatusCode());
99 static::assertSame(['/controller/?searchtags=def+abc'], $result->getHeader('location'));
100 }
101
102 public function testAddTagWithRefererAndEmptySearch(): void
103 {
104 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtags='];
105
106 $request = $this->createMock(Request::class);
107 $response = new Response();
108
109 $tags = ['newTag' => 'abc'];
110
111 $result = $this->controller->addTag($request, $response, $tags);
112
113 static::assertInstanceOf(Response::class, $result);
114 static::assertSame(302, $result->getStatusCode());
115 static::assertSame(['/controller/?searchtags=abc'], $result->getHeader('location'));
116 }
117
118 public function testAddTagWithoutNewTagWithReferer(): void
119 {
120 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtags=def'];
121
122 $request = $this->createMock(Request::class);
123 $response = new Response();
124
125 $result = $this->controller->addTag($request, $response, []);
126
127 static::assertInstanceOf(Response::class, $result);
128 static::assertSame(302, $result->getStatusCode());
129 static::assertSame(['/controller/?searchtags=def'], $result->getHeader('location'));
130 }
131
132 public function testAddTagWithoutNewTagWithoutReferer(): void
133 {
134 $request = $this->createMock(Request::class);
135 $response = new Response();
136
137 $result = $this->controller->addTag($request, $response, []);
138
139 static::assertInstanceOf(Response::class, $result);
140 static::assertSame(302, $result->getStatusCode());
141 static::assertSame(['/subfolder/'], $result->getHeader('location'));
142 }
143
144 public function testRemoveTagWithoutMatchingTag(): void
145 {
146 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtags=def'];
147
148 $request = $this->createMock(Request::class);
149 $response = new Response();
150
151 $tags = ['tag' => 'abc'];
152
153 $result = $this->controller->removeTag($request, $response, $tags);
154
155 static::assertInstanceOf(Response::class, $result);
156 static::assertSame(302, $result->getStatusCode());
157 static::assertSame(['/controller/?searchtags=def'], $result->getHeader('location'));
158 }
159
160 public function testRemoveTagWithoutTagsearch(): void
161 {
162 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/'];
163
164 $request = $this->createMock(Request::class);
165 $response = new Response();
166
167 $tags = ['tag' => 'abc'];
168
169 $result = $this->controller->removeTag($request, $response, $tags);
170
171 static::assertInstanceOf(Response::class, $result);
172 static::assertSame(302, $result->getStatusCode());
173 static::assertSame(['/controller/'], $result->getHeader('location'));
174 }
175
176 public function testRemoveTagWithoutReferer(): void
177 {
178 $request = $this->createMock(Request::class);
179 $response = new Response();
180
181 $tags = ['tag' => 'abc'];
182
183 $result = $this->controller->removeTag($request, $response, $tags);
184
185 static::assertInstanceOf(Response::class, $result);
186 static::assertSame(302, $result->getStatusCode());
187 static::assertSame(['/subfolder/'], $result->getHeader('location'));
188 }
189
190 public function testRemoveTagWithoutTag(): void
191 {
192 $this->container->environment = ['HTTP_REFERER' => 'http://shaarli/controller/?searchtag=abc'];
193
194 $request = $this->createMock(Request::class);
195 $response = new Response();
196
197 $result = $this->controller->removeTag($request, $response, []);
198
199 static::assertInstanceOf(Response::class, $result);
200 static::assertSame(302, $result->getStatusCode());
201 static::assertSame(['/controller/?searchtag=abc'], $result->getHeader('location'));
202 }
203
204 public function testRemoveTagWithoutTagWithoutReferer(): void
205 {
206 $request = $this->createMock(Request::class);
207 $response = new Response();
208
209 $result = $this->controller->removeTag($request, $response, []);
210
211 static::assertInstanceOf(Response::class, $result);
212 static::assertSame(302, $result->getStatusCode());
213 static::assertSame(['/subfolder/'], $result->getHeader('location'));
214 }
215}