aboutsummaryrefslogtreecommitdiffhomepage
path: root/tests/bookmark/BookmarkFileServiceTest.php
blob: d1af3fb04f6fffa71813ab4161d02ea6a500d0eb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
<?php
/**
 * Link datastore tests
 */

namespace Shaarli\Bookmark;

use DateTime;
use malkusch\lock\mutex\NoMutex;
use ReferenceLinkDB;
use ReflectionClass;
use Shaarli;
use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
use Shaarli\Config\ConfigManager;
use Shaarli\Formatter\BookmarkMarkdownFormatter;
use Shaarli\History;
use Shaarli\TestCase;

/**
 * Unitary tests for LegacyLinkDBTest
 */
class BookmarkFileServiceTest extends TestCase
{
    // datastore to test write operations
    protected static $testDatastore = 'sandbox/datastore.php';

    protected static $testConf = 'sandbox/config';

    protected static $testUpdates = 'sandbox/updates.txt';

    /**
     * @var ConfigManager instance.
     */
    protected $conf;

    /**
     * @var History instance.
     */
    protected $history;

    /**
     * @var ReferenceLinkDB instance.
     */
    protected $refDB = null;

    /**
     * @var BookmarkFileService public LinkDB instance.
     */
    protected $publicLinkDB = null;

    /**
     * @var BookmarkFileService private LinkDB instance.
     */
    protected $privateLinkDB = null;

    /** @var NoMutex */
    protected $mutex;

    /**
     * Instantiates public and private LinkDBs with test data
     *
     * The reference datastore contains public and private bookmarks that
     * will be used to test LinkDB's methods:
     *  - access filtering (public/private),
     *  - link searches:
     *    - by day,
     *    - by tag,
     *    - by text,
     *  - etc.
     *
     * Resets test data for each test
     */
    protected function setUp(): void
    {
        $this->mutex = new NoMutex();

        if (file_exists(self::$testDatastore)) {
            unlink(self::$testDatastore);
        }

        if (file_exists(self::$testConf .'.json.php')) {
            unlink(self::$testConf .'.json.php');
        }

        if (file_exists(self::$testUpdates)) {
            unlink(self::$testUpdates);
        }

        copy('tests/utils/config/configJson.json.php', self::$testConf .'.json.php');
        $this->conf = new ConfigManager(self::$testConf);
        $this->conf->set('resource.datastore', self::$testDatastore);
        $this->conf->set('resource.updates', self::$testUpdates);
        $this->refDB = new \ReferenceLinkDB();
        $this->refDB->write(self::$testDatastore);
        $this->history = new History('sandbox/history.php');
        $this->publicLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, false);
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);
    }

    /**
     * Test migrate() method with a legacy datastore.
     */
    public function testDatabaseMigration()
    {
        if (!defined('SHAARLI_VERSION')) {
            define('SHAARLI_VERSION', 'dev');
        }

        $this->refDB = new \ReferenceLinkDB(true);
        $this->refDB->write(self::$testDatastore);
        $db = self::getMethod('migrate');
        $db->invokeArgs($this->privateLinkDB, []);

        $db = new \FakeBookmarkService($this->conf, $this->history, $this->mutex, true);
        $this->assertInstanceOf(BookmarkArray::class, $db->getBookmarks());
        $this->assertEquals($this->refDB->countLinks(), $db->count());
    }

    /**
     * Test get() method for a defined and saved bookmark
     */
    public function testGetDefinedSaved()
    {
        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle());
    }

    /**
     * Test get() method for a defined and not saved bookmark
     */
    public function testGetDefinedNotSaved()
    {
        $bookmark = new Bookmark();
        $this->privateLinkDB->add($bookmark);
        $createdBookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $createdBookmark->getId());
        $this->assertEmpty($createdBookmark->getDescription());
    }

    /**
     * Test get() method for an undefined bookmark
     */
    public function testGetUndefined()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\BookmarkNotFoundException::class);

        $this->privateLinkDB->get(666);
    }

    /**
     * Test add() method for a bookmark fully built
     */
    public function testAddFull()
    {
        $bookmark = new Bookmark();
        $bookmark->setUrl($url = 'https://domain.tld/index.php');
        $bookmark->setShortUrl('abc');
        $bookmark->setTitle($title = 'This a brand new bookmark');
        $bookmark->setDescription($desc = 'It should be created and written');
        $bookmark->setTags($tags = ['tag1', 'tagssss']);
        $bookmark->setThumbnail($thumb = 'http://thumb.tld/dle.png');
        $bookmark->setPrivate(true);
        $bookmark->setSticky(true);
        $bookmark->setCreated($created = DateTime::createFromFormat('Ymd_His', '20190518_140354'));
        $bookmark->setUpdated($updated = DateTime::createFromFormat('Ymd_His', '20190518_150354'));

        $this->privateLinkDB->add($bookmark);
        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());
        $this->assertEquals($url, $bookmark->getUrl());
        $this->assertEquals('abc', $bookmark->getShortUrl());
        $this->assertEquals($title, $bookmark->getTitle());
        $this->assertEquals($desc, $bookmark->getDescription());
        $this->assertEquals($tags, $bookmark->getTags());
        $this->assertEquals($thumb, $bookmark->getThumbnail());
        $this->assertTrue($bookmark->isPrivate());
        $this->assertTrue($bookmark->isSticky());
        $this->assertEquals($created, $bookmark->getCreated());
        $this->assertEquals($updated, $bookmark->getUpdated());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());
        $this->assertEquals($url, $bookmark->getUrl());
        $this->assertEquals('abc', $bookmark->getShortUrl());
        $this->assertEquals($title, $bookmark->getTitle());
        $this->assertEquals($desc, $bookmark->getDescription());
        $this->assertEquals($tags, $bookmark->getTags());
        $this->assertEquals($thumb, $bookmark->getThumbnail());
        $this->assertTrue($bookmark->isPrivate());
        $this->assertTrue($bookmark->isSticky());
        $this->assertEquals($created, $bookmark->getCreated());
        $this->assertEquals($updated, $bookmark->getUpdated());
    }

    /**
     * Test add() method for a bookmark without any field set
     */
    public function testAddMinimal()
    {
        $bookmark = new Bookmark();
        $this->privateLinkDB->add($bookmark);

        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());
        $this->assertRegExp('#/shaare/[\w\-]{6}#', $bookmark->getUrl());
        $this->assertRegExp('/[\w\-]{6}/', $bookmark->getShortUrl());
        $this->assertEquals($bookmark->getUrl(), $bookmark->getTitle());
        $this->assertEmpty($bookmark->getDescription());
        $this->assertEmpty($bookmark->getTags());
        $this->assertEmpty($bookmark->getThumbnail());
        $this->assertFalse($bookmark->isPrivate());
        $this->assertFalse($bookmark->isSticky());
        $this->assertTrue(new \DateTime('5 seconds ago') < $bookmark->getCreated());
        $this->assertNull($bookmark->getUpdated());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());
        $this->assertRegExp('#/shaare/[\w\-]{6}#', $bookmark->getUrl());
        $this->assertRegExp('/[\w\-]{6}/', $bookmark->getShortUrl());
        $this->assertEquals($bookmark->getUrl(), $bookmark->getTitle());
        $this->assertEmpty($bookmark->getDescription());
        $this->assertEmpty($bookmark->getTags());
        $this->assertEmpty($bookmark->getThumbnail());
        $this->assertFalse($bookmark->isPrivate());
        $this->assertFalse($bookmark->isSticky());
        $this->assertTrue(new \DateTime('5 seconds ago') < $bookmark->getCreated());
        $this->assertNull($bookmark->getUpdated());
    }

    /**
     * Test add() method for a bookmark without any field set and without writing the data store
     */
    public function testAddMinimalNoWrite()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\BookmarkNotFoundException::class);

        $bookmark = new Bookmark();
        $this->privateLinkDB->add($bookmark, false);

        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $this->privateLinkDB->get(43);
    }

    /**
     * Test add() method while logged out
     */
    public function testAddLoggedOut()
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('You\'re not authorized to alter the datastore');

        $this->publicLinkDB->add(new Bookmark());
    }

    /**
     * Test add() method with a Bookmark already containing an ID
     */
    public function testAddWithId()
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('This bookmarks already exists');

        $bookmark = new Bookmark();
        $bookmark->setId(43);
        $this->privateLinkDB->add($bookmark);
    }

    /**
     * Test set() method for a bookmark fully built
     */
    public function testSetFull()
    {
        $bookmark = $this->privateLinkDB->get(42);
        $bookmark->setUrl($url = 'https://domain.tld/index.php');
        $bookmark->setShortUrl('abc');
        $bookmark->setTitle($title = 'This a brand new bookmark');
        $bookmark->setDescription($desc = 'It should be created and written');
        $bookmark->setTags($tags = ['tag1', 'tagssss']);
        $bookmark->setThumbnail($thumb = 'http://thumb.tld/dle.png');
        $bookmark->setPrivate(true);
        $bookmark->setSticky(true);
        $bookmark->setCreated($created = DateTime::createFromFormat('Ymd_His', '20190518_140354'));
        $bookmark->setUpdated($updated = DateTime::createFromFormat('Ymd_His', '20190518_150354'));

        $this->privateLinkDB->set($bookmark);
        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals($url, $bookmark->getUrl());
        $this->assertEquals('abc', $bookmark->getShortUrl());
        $this->assertEquals($title, $bookmark->getTitle());
        $this->assertEquals($desc, $bookmark->getDescription());
        $this->assertEquals($tags, $bookmark->getTags());
        $this->assertEquals($thumb, $bookmark->getThumbnail());
        $this->assertTrue($bookmark->isPrivate());
        $this->assertTrue($bookmark->isSticky());
        $this->assertEquals($created, $bookmark->getCreated());
        $this->assertTrue(new \DateTime('5 seconds ago') < $bookmark->getUpdated());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals($url, $bookmark->getUrl());
        $this->assertEquals('abc', $bookmark->getShortUrl());
        $this->assertEquals($title, $bookmark->getTitle());
        $this->assertEquals($desc, $bookmark->getDescription());
        $this->assertEquals($tags, $bookmark->getTags());
        $this->assertEquals($thumb, $bookmark->getThumbnail());
        $this->assertTrue($bookmark->isPrivate());
        $this->assertTrue($bookmark->isSticky());
        $this->assertEquals($created, $bookmark->getCreated());
        $this->assertTrue(new \DateTime('5 seconds ago') < $bookmark->getUpdated());
    }

    /**
     * Test set() method for a bookmark without any field set
     */
    public function testSetMinimal()
    {
        $bookmark = $this->privateLinkDB->get(42);
        $this->privateLinkDB->set($bookmark);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals('/shaare/WDWyig', $bookmark->getUrl());
        $this->assertEquals('1eYJ1Q', $bookmark->getShortUrl());
        $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle());
        $this->assertEquals('Used to test bookmarks reordering.', $bookmark->getDescription());
        $this->assertEquals(['ut'], $bookmark->getTags());
        $this->assertFalse($bookmark->getThumbnail());
        $this->assertFalse($bookmark->isPrivate());
        $this->assertFalse($bookmark->isSticky());
        $this->assertEquals(
            DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20100310_101010'),
            $bookmark->getCreated()
        );
        $this->assertTrue(new \DateTime('5 seconds ago') < $bookmark->getUpdated());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals('/shaare/WDWyig', $bookmark->getUrl());
        $this->assertEquals('1eYJ1Q', $bookmark->getShortUrl());
        $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle());
        $this->assertEquals('Used to test bookmarks reordering.', $bookmark->getDescription());
        $this->assertEquals(['ut'], $bookmark->getTags());
        $this->assertFalse($bookmark->getThumbnail());
        $this->assertFalse($bookmark->isPrivate());
        $this->assertFalse($bookmark->isSticky());
        $this->assertEquals(
            DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, '20100310_101010'),
            $bookmark->getCreated()
        );
        $this->assertTrue(new \DateTime('5 seconds ago') < $bookmark->getUpdated());
    }

    /**
     * Test set() method for a bookmark without any field set and without writing the data store
     */
    public function testSetMinimalNoWrite()
    {
        $bookmark = $this->privateLinkDB->get(42);
        $bookmark->setTitle($title = 'hi!');
        $this->privateLinkDB->set($bookmark, false);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals($title, $bookmark->getTitle());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle());
    }

    /**
     * Test set() method while logged out
     */
    public function testSetLoggedOut()
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('You\'re not authorized to alter the datastore');

        $this->publicLinkDB->set(new Bookmark());
    }

    /**
     * Test set() method with a Bookmark without an ID defined.
     */
    public function testSetWithoutId()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\BookmarkNotFoundException::class);

        $bookmark = new Bookmark();
        $this->privateLinkDB->set($bookmark);
    }

    /**
     * Test set() method with a Bookmark with an unknow ID
     */
    public function testSetWithUnknownId()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\BookmarkNotFoundException::class);

        $bookmark = new Bookmark();
        $bookmark->setId(666);
        $this->privateLinkDB->set($bookmark);
    }

    /**
     * Test addOrSet() method with a new ID
     */
    public function testAddOrSetNew()
    {
        $bookmark = new Bookmark();
        $this->privateLinkDB->addOrSet($bookmark);

        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(43);
        $this->assertEquals(43, $bookmark->getId());
    }

    /**
     * Test addOrSet() method with an existing ID
     */
    public function testAddOrSetExisting()
    {
        $bookmark = $this->privateLinkDB->get(42);
        $bookmark->setTitle($title = 'hi!');
        $this->privateLinkDB->addOrSet($bookmark);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals($title, $bookmark->getTitle());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals($title, $bookmark->getTitle());
    }

    /**
     * Test addOrSet() method while logged out
     */
    public function testAddOrSetLoggedOut()
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('You\'re not authorized to alter the datastore');

        $this->publicLinkDB->addOrSet(new Bookmark());
    }

    /**
     * Test addOrSet() method for a bookmark without any field set and without writing the data store
     */
    public function testAddOrSetMinimalNoWrite()
    {
        $bookmark = $this->privateLinkDB->get(42);
        $bookmark->setTitle($title = 'hi!');
        $this->privateLinkDB->addOrSet($bookmark, false);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals($title, $bookmark->getTitle());

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $bookmark = $this->privateLinkDB->get(42);
        $this->assertEquals(42, $bookmark->getId());
        $this->assertEquals('Note: I have a big ID but an old date', $bookmark->getTitle());
    }

    /**
     * Test remove() method with an existing Bookmark
     */
    public function testRemoveExisting()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\BookmarkNotFoundException::class);

        $bookmark = $this->privateLinkDB->get(42);
        $this->privateLinkDB->remove($bookmark);

        $exception = null;
        try {
            $this->privateLinkDB->get(42);
        } catch (BookmarkNotFoundException $e) {
            $exception = $e;
        }
        $this->assertInstanceOf(BookmarkNotFoundException::class, $exception);

        // reload from file
        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);

        $this->privateLinkDB->get(42);
    }

    /**
     * Test remove() method while logged out
     */
    public function testRemoveLoggedOut()
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('You\'re not authorized to alter the datastore');

        $bookmark = $this->privateLinkDB->get(42);
        $this->publicLinkDB->remove($bookmark);
    }

    /**
     * Test remove() method with a Bookmark with an unknown ID
     */
    public function testRemoveWithUnknownId()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\BookmarkNotFoundException::class);

        $bookmark = new Bookmark();
        $bookmark->setId(666);
        $this->privateLinkDB->remove($bookmark);
    }

    /**
     * Test exists() method
     */
    public function testExists()
    {
        $this->assertTrue($this->privateLinkDB->exists(42)); // public
        $this->assertTrue($this->privateLinkDB->exists(6)); // private

        $this->assertTrue($this->privateLinkDB->exists(42, BookmarkFilter::$ALL));
        $this->assertTrue($this->privateLinkDB->exists(6, BookmarkFilter::$ALL));

        $this->assertTrue($this->privateLinkDB->exists(42, BookmarkFilter::$PUBLIC));
        $this->assertFalse($this->privateLinkDB->exists(6, BookmarkFilter::$PUBLIC));

        $this->assertFalse($this->privateLinkDB->exists(42, BookmarkFilter::$PRIVATE));
        $this->assertTrue($this->privateLinkDB->exists(6, BookmarkFilter::$PRIVATE));

        $this->assertTrue($this->publicLinkDB->exists(42));
        $this->assertFalse($this->publicLinkDB->exists(6));

        $this->assertTrue($this->publicLinkDB->exists(42, BookmarkFilter::$PUBLIC));
        $this->assertFalse($this->publicLinkDB->exists(6, BookmarkFilter::$PUBLIC));

        $this->assertFalse($this->publicLinkDB->exists(42, BookmarkFilter::$PRIVATE));
        $this->assertTrue($this->publicLinkDB->exists(6, BookmarkFilter::$PRIVATE));
    }

    /**
     * Test initialize() method
     */
    public function testInitialize()
    {
        $dbSize = $this->privateLinkDB->count();
        $this->privateLinkDB->initialize();
        $this->assertEquals($dbSize + 3, $this->privateLinkDB->count());
        $this->assertStringStartsWith(
            'Shaarli will automatically pick up the thumbnail for links to a variety of websites.',
            $this->privateLinkDB->get(43)->getDescription()
        );
        $this->assertStringStartsWith(
            'Adding a shaare without entering a URL creates a text-only "note" post such as this one.',
            $this->privateLinkDB->get(44)->getDescription()
        );
        $this->assertStringStartsWith(
            'Welcome to Shaarli!',
            $this->privateLinkDB->get(45)->getDescription()
        );
    }

    /*
     * The following tests have been taken from the legacy LinkDB test and adapted
     * to make sure that nothing have been broken in the migration process.
     * They mostly cover search/filters. Some of them might be redundant with the previous ones.
     */
    /**
     * Attempt to instantiate a LinkDB whereas the datastore is not writable
     */
    public function testConstructDatastoreNotWriteable()
    {
        $this->expectException(\Shaarli\Bookmark\Exception\NotWritableDataStoreException::class);
        $this->expectExceptionMessageRegExp('#Couldn\'t load data from the data store file "null".*#');

        $conf = new ConfigManager('tests/utils/config/configJson');
        $conf->set('resource.datastore', 'null/store.db');
        new BookmarkFileService($conf, $this->history, $this->mutex, true);
    }

    /**
     * The DB doesn't exist, ensure it is created with an empty datastore
     */
    public function testCheckDBNewLoggedIn()
    {
        unlink(self::$testDatastore);
        $this->assertFileNotExists(self::$testDatastore);
        new BookmarkFileService($this->conf, $this->history, $this->mutex, true);
        $this->assertFileExists(self::$testDatastore);

        // ensure the correct data has been written
        $this->assertGreaterThan(0, filesize(self::$testDatastore));
    }

    /**
     * The DB doesn't exist, but not logged in, ensure it initialized, but the file is not written
     */
    public function testCheckDBNewLoggedOut()
    {
        unlink(self::$testDatastore);
        $this->assertFileNotExists(self::$testDatastore);
        $db = new \FakeBookmarkService($this->conf, $this->history, $this->mutex, false);
        $this->assertFileNotExists(self::$testDatastore);
        $this->assertInstanceOf(BookmarkArray::class, $db->getBookmarks());
        $this->assertCount(0, $db->getBookmarks());
    }

    /**
     * Load public bookmarks from the DB
     */
    public function testReadPublicDB()
    {
        $this->assertEquals(
            $this->refDB->countPublicLinks(),
            $this->publicLinkDB->count()
        );
    }

    /**
     * Load public and private bookmarks from the DB
     */
    public function testReadPrivateDB()
    {
        $this->assertEquals(
            $this->refDB->countLinks(),
            $this->privateLinkDB->count()
        );
    }

    /**
     * Save the bookmarks to the DB
     */
    public function testSave()
    {
        $testDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);
        $dbSize = $testDB->count();

        $bookmark = new Bookmark();
        $testDB->add($bookmark);

        $testDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, true);
        $this->assertEquals($dbSize + 1, $testDB->count());
    }

    /**
     * Count existing bookmarks - public bookmarks hidden
     */
    public function testCountHiddenPublic()
    {
        $this->conf->set('privacy.hide_public_links', true);
        $linkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, false);

        $this->assertEquals(0, $linkDB->count());
    }

    /**
     * The URL corresponds to an existing entry in the DB
     */
    public function testGetKnownLinkFromURL()
    {
        $link = $this->publicLinkDB->findByUrl('http://mediagoblin.org/');

        $this->assertNotEquals(false, $link);
        $this->assertContainsPolyfill(
            'A free software media publishing platform',
            $link->getDescription()
        );
    }

    /**
     * The URL is not in the DB
     */
    public function testGetUnknownLinkFromURL()
    {
        $this->assertEquals(
            false,
            $this->publicLinkDB->findByUrl('http://dev.null')
        );
    }

    /**
     * Lists all tags
     */
    public function testAllTags()
    {
        $this->assertEquals(
            [
                'web' => 3,
                'cartoon' => 2,
                'gnu' => 2,
                'dev' => 1,
                'samba' => 1,
                'media' => 1,
                'software' => 1,
                'stallman' => 1,
                'free' => 1,
                '-exclude' => 1,
                'hashtag' => 2,
                // The DB contains a link with `sTuff` and another one with `stuff` tag.
                // They need to be grouped with the first case found - order by date DESC: `sTuff`.
                'sTuff' => 2,
                'ut' => 1,
                'assurance' => 1,
                'coding-style' => 1,
                'quality' => 1,
                'standards' => 1,
            ],
            $this->publicLinkDB->bookmarksCountPerTag()
        );

        $this->assertEquals(
            [
                'web' => 4,
                'cartoon' => 3,
                'gnu' => 2,
                'dev' => 2,
                'samba' => 1,
                'media' => 1,
                'software' => 1,
                'stallman' => 1,
                'free' => 1,
                'html' => 1,
                'w3c' => 1,
                'css' => 1,
                'Mercurial' => 1,
                'sTuff' => 2,
                '-exclude' => 1,
                '.hidden' => 1,
                'hashtag' => 2,
                'tag1' => 1,
                'tag2' => 1,
                'tag3' => 1,
                'tag4' => 1,
                'ut' => 1,
                'assurance' => 1,
                'coding-style' => 1,
                'quality' => 1,
                'standards' => 1,
            ],
            $this->privateLinkDB->bookmarksCountPerTag()
        );
        $this->assertEquals(
            [
                'cartoon' => 2,
                'gnu' => 1,
                'dev' => 1,
                'samba' => 1,
                'media' => 1,
                'html' => 1,
                'w3c' => 1,
                'css' => 1,
                'Mercurial' => 1,
                '.hidden' => 1,
                'hashtag' => 1,
            ],
            $this->privateLinkDB->bookmarksCountPerTag(['web'])
        );
        $this->assertEquals(
            [
                'html' => 1,
                'w3c' => 1,
                'css' => 1,
                'Mercurial' => 1,
            ],
            $this->privateLinkDB->bookmarksCountPerTag(['web'], 'private')
        );
    }

    /**
     * Test filter with string.
     */
    public function testFilterString()
    {
        $tags = 'dev cartoon';
        $request = ['searchtags' => $tags];
        $this->assertEquals(
            2,
            count($this->privateLinkDB->search($request, null, true)->getBookmarks())
        );
    }

    /**
     * Test filter with array.
     */
    public function testFilterArray()
    {
        $tags = ['dev', 'cartoon'];
        $request = ['searchtags' => $tags];
        $this->assertEquals(
            2,
            count($this->privateLinkDB->search($request, null, true)->getBookmarks())
        );
    }

    /**
     * Test hidden tags feature:
     *  tags starting with a dot '.' are only visible when logged in.
     */
    public function testHiddenTags()
    {
        $tags = '.hidden';
        $request = ['searchtags' => $tags];
        $this->assertEquals(
            1,
            count($this->privateLinkDB->search($request, 'all', true)->getBookmarks())
        );

        $this->assertEquals(
            0,
            count($this->publicLinkDB->search($request, 'public', true)->getBookmarks())
        );
    }

    /**
     * Test filterHash() with a valid smallhash.
     */
    public function testFilterHashValid()
    {
        $request = smallHash('20150310_114651');
        $this->assertSame(
            $request,
            $this->publicLinkDB->findByHash($request)->getShortUrl()
        );
        $request = smallHash('20150310_114633' . 8);
        $this->assertSame(
            $request,
            $this->publicLinkDB->findByHash($request)->getShortUrl()
        );
    }

    /**
     * Test filterHash() with an invalid smallhash.
     */
    public function testFilterHashInValid1()
    {
        $this->expectException(BookmarkNotFoundException::class);

        $request = 'blabla';
        $this->publicLinkDB->findByHash($request);
    }

    /**
     * Test filterHash() with an empty smallhash.
     */
    public function testFilterHashInValid()
    {
        $this->expectException(BookmarkNotFoundException::class);

        $this->publicLinkDB->findByHash('');
    }

    /**
     * Test filterHash() on a private bookmark while logged out.
     */
    public function testFilterHashPrivateWhileLoggedOut()
    {
        $this->expectException(BookmarkNotFoundException::class);
        $this->expectExceptionMessage('The link you are trying to reach does not exist or has been deleted');

        $hash = smallHash('20141125_084734' . 6);

        $this->publicLinkDB->findByHash($hash);
    }

    /**
     * Test filterHash() with private key.
     */
    public function testFilterHashWithPrivateKey()
    {
        $hash = smallHash('20141125_084734' . 6);
        $privateKey = 'this is usually auto generated';

        $bookmark = $this->privateLinkDB->findByHash($hash);
        $bookmark->addAdditionalContentEntry('private_key', $privateKey);
        $this->privateLinkDB->save();

        $this->privateLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, false);
        $bookmark = $this->privateLinkDB->findByHash($hash, $privateKey);

        static::assertSame(6, $bookmark->getId());
    }

    /**
     * Test linksCountPerTag all tags without filter.
     * Equal occurrences should be sorted alphabetically.
     */
    public function testCountLinkPerTagAllNoFilter()
    {
        $expected = [
            'web' => 4,
            'cartoon' => 3,
            'dev' => 2,
            'gnu' => 2,
            'hashtag' => 2,
            'sTuff' => 2,
            '-exclude' => 1,
            '.hidden' => 1,
            'Mercurial' => 1,
            'css' => 1,
            'free' => 1,
            'html' => 1,
            'media' => 1,
            'samba' => 1,
            'software' => 1,
            'stallman' => 1,
            'tag1' => 1,
            'tag2' => 1,
            'tag3' => 1,
            'tag4' => 1,
            'ut' => 1,
            'w3c' => 1,
            'assurance' => 1,
            'coding-style' => 1,
            'quality' => 1,
            'standards' => 1,
        ];
        $tags = $this->privateLinkDB->bookmarksCountPerTag();

        $this->assertEquals($expected, $tags, var_export($tags, true));
    }

    /**
     * Test linksCountPerTag all tags with filter.
     * Equal occurrences should be sorted alphabetically.
     */
    public function testCountLinkPerTagAllWithFilter()
    {
        $expected = [
            'hashtag' => 2,
            '-exclude' => 1,
            '.hidden' => 1,
            'free' => 1,
            'media' => 1,
            'software' => 1,
            'stallman' => 1,
            'stuff' => 1,
            'web' => 1,
        ];
        $tags = $this->privateLinkDB->bookmarksCountPerTag(['gnu']);

        $this->assertEquals($expected, $tags, var_export($tags, true));
    }

    /**
     * Test linksCountPerTag public tags with filter.
     * Equal occurrences should be sorted alphabetically.
     */
    public function testCountLinkPerTagPublicWithFilter()
    {
        $expected = [
            'hashtag' => 2,
            '-exclude' => 1,
            '.hidden' => 1,
            'free' => 1,
            'media' => 1,
            'software' => 1,
            'stallman' => 1,
            'stuff' => 1,
            'web' => 1,
        ];
        $tags = $this->privateLinkDB->bookmarksCountPerTag(['gnu'], 'public');

        $this->assertEquals($expected, $tags, var_export($tags, true));
    }

    /**
     * Test linksCountPerTag public tags with filter.
     * Equal occurrences should be sorted alphabetically.
     */
    public function testCountLinkPerTagPrivateWithFilter()
    {
        $expected = [
            'cartoon' => 1,
            'tag1' => 1,
            'tag2' => 1,
            'tag3' => 1,
            'tag4' => 1,
        ];
        $tags = $this->privateLinkDB->bookmarksCountPerTag(['dev'], 'private');

        $this->assertEquals($expected, $tags, var_export($tags, true));
    }

    /**
     * Test linksCountPerTag public tags with filter.
     * Equal occurrences should be sorted alphabetically.
     */
    public function testCountTagsNoMarkdown()
    {
        $expected = [
            'cartoon' => 3,
            'dev' => 2,
            'tag1' => 1,
            'tag2' => 1,
            'tag3' => 1,
            'tag4' => 1,
            'web' => 4,
            'gnu' => 2,
            'hashtag' => 2,
            'sTuff' => 2,
            '-exclude' => 1,
            '.hidden' => 1,
            'Mercurial' => 1,
            'css' => 1,
            'free' => 1,
            'html' => 1,
            'media' => 1,
            'newTagToCount' => 1,
            'samba' => 1,
            'software' => 1,
            'stallman' => 1,
            'ut' => 1,
            'w3c' => 1,
            'assurance' => 1,
            'coding-style' => 1,
            'quality' => 1,
            'standards' => 1,
        ];
        $bookmark = new Bookmark();
        $bookmark->setTags(['newTagToCount', BookmarkMarkdownFormatter::NO_MD_TAG]);
        $this->privateLinkDB->add($bookmark);

        $tags = $this->privateLinkDB->bookmarksCountPerTag();

        $this->assertEquals($expected, $tags, var_export($tags, true));
    }

    /**
     * Test find by dates in the middle of the datastore (sorted by dates) with a single bookmark as a result.
     */
    public function testFilterByDateMidTimePeriodSingleBookmark(): void
    {
        $bookmarks = $this->privateLinkDB->findByDate(
            DateTime::createFromFormat('Ymd_His', '20121206_150000'),
            DateTime::createFromFormat('Ymd_His', '20121206_160000'),
            $before,
            $after
        );

        static::assertCount(1, $bookmarks);

        static::assertSame(9, $bookmarks[0]->getId());
        static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_142300'), $before);
        static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_172539'), $after);
    }

    /**
     * Test find by dates in the middle of the datastore (sorted by dates) with a multiple bookmarks as a result.
     */
    public function testFilterByDateMidTimePeriodMultipleBookmarks(): void
    {
        $bookmarks = $this->privateLinkDB->findByDate(
            DateTime::createFromFormat('Ymd_His', '20121206_150000'),
            DateTime::createFromFormat('Ymd_His', '20121206_180000'),
            $before,
            $after
        );

        static::assertCount(2, $bookmarks);

        static::assertSame(1, $bookmarks[0]->getId());
        static::assertSame(9, $bookmarks[1]->getId());
        static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_142300'), $before);
        static::assertEquals(DateTime::createFromFormat('Ymd_His', '20121206_182539'), $after);
    }

    /**
     * Test find by dates at the end of the datastore (sorted by dates).
     */
    public function testFilterByDateLastTimePeriod(): void
    {
        $after = new DateTime();
        $bookmarks = $this->privateLinkDB->findByDate(
            DateTime::createFromFormat('Ymd_His', '20150310_114640'),
            DateTime::createFromFormat('Ymd_His', '20450101_010101'),
            $before,
            $after
        );

        static::assertCount(1, $bookmarks);

        static::assertSame(41, $bookmarks[0]->getId());
        static::assertEquals(DateTime::createFromFormat('Ymd_His', '20150310_114633'), $before);
        static::assertNull($after);
    }

    /**
     * Test find by dates at the beginning of the datastore (sorted by dates).
     */
    public function testFilterByDateFirstTimePeriod(): void
    {
        $before = new DateTime();
        $bookmarks = $this->privateLinkDB->findByDate(
            DateTime::createFromFormat('Ymd_His', '20000101_101010'),
            DateTime::createFromFormat('Ymd_His', '20100309_110000'),
            $before,
            $after
        );

        static::assertCount(1, $bookmarks);

        static::assertSame(11, $bookmarks[0]->getId());
        static::assertNull($before);
        static::assertEquals(DateTime::createFromFormat('Ymd_His', '20100310_101010'), $after);
    }

    /**
     * Test getLatest with a sticky bookmark: it should be ignored and return the latest by creation date instead.
     */
    public function testGetLatestWithSticky(): void
    {
        $bookmark = $this->publicLinkDB->getLatest();

        static::assertSame(41, $bookmark->getId());
    }

    /**
     * Test getLatest with a sticky bookmark: it should be ignored and return the latest by creation date instead.
     */
    public function testGetLatestEmptyDatastore(): void
    {
        unlink($this->conf->get('resource.datastore'));
        $this->publicLinkDB = new BookmarkFileService($this->conf, $this->history, $this->mutex, false);

        $bookmark = $this->publicLinkDB->getLatest();

        static::assertNull($bookmark);
    }

    /**
     * Allows to test LinkDB's private methods
     *
     * @see
     *  https://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html
     *  http://stackoverflow.com/a/2798203
     */
    protected static function getMethod($name)
    {
        $class = new ReflectionClass('Shaarli\Bookmark\BookmarkFileService');
        $method = $class->getMethod($name);
        $method->setAccessible(true);
        return $method;
    }
}