-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy pathtest_bukuDb.py
1951 lines (1713 loc) · 77.9 KB
/
test_bukuDb.py
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
#!/usr/bin/env python3
#
# Unit test cases for buku
#
import math
import os
import re
import sqlite3
import sys
import unittest
from tempfile import NamedTemporaryFile, TemporaryDirectory
from random import shuffle
from unittest import mock
from genericpath import exists
import pytest
import yaml
from hypothesis import example, given, settings
from hypothesis import strategies as st
from buku import PERMANENT_REDIRECTS, BukuDb, FetchResult, BookmarkVar, bookmark_vars, parse_tags, prompt
from tests.util import mock_http, mock_fetch, _add_rec, _tagset
def get_temp_dir_path():
with TemporaryDirectory(prefix="bukutest_") as dir_obj:
return dir_obj
TEST_TEMP_DIR_PATH = get_temp_dir_path()
TEST_TEMP_DBDIR_PATH = os.path.join(TEST_TEMP_DIR_PATH, "buku")
TEST_TEMP_DBFILE_PATH = os.path.join(TEST_TEMP_DBDIR_PATH, "bookmarks.db")
MAX_SQLITE_INT = int(math.pow(2, 63) - 1)
TEST_PRINT_REC = ("https://example.com", "", parse_tags(["cat,ant,bee,1"]), "")
TEST_BOOKMARKS = [
[
"http://slashdot.org",
"SLASHDOT",
parse_tags(["old,news"]),
"News for old nerds, stuff that doesn't matter",
],
[
"http://www.zażółćgęśląjaźń.pl/",
"ZAŻÓŁĆ",
parse_tags(["zażółć,gęślą,jaźń"]),
"Testing UTF-8, zażółć gęślą jaźń.",
],
[
"http://example.com/",
"test",
parse_tags(["test,tes,est,es"]),
"a case for replace_tag test",
],
]
only_python_3_5 = pytest.mark.skipif(
sys.version_info < (3, 5), reason="requires Python 3.5 or later"
)
@pytest.fixture(scope="module")
def vcr_cassette_dir(request):
# Put all cassettes in vhs/{module}/{test}.yaml
return os.path.join("tests", "vcr_cassettes", request.module.__name__)
def rmdb(*bdbs):
for bdb in bdbs:
try:
bdb.cur.close()
bdb.conn.close()
except Exception:
pass
if exists(TEST_TEMP_DBFILE_PATH):
os.remove(TEST_TEMP_DBFILE_PATH)
@pytest.fixture()
def bukuDb():
os.environ["XDG_DATA_HOME"] = TEST_TEMP_DIR_PATH
# start every test from a clean state
rmdb()
bdbs = []
def _bukuDb(*args, **kwargs):
nonlocal bdbs
bdbs += [BukuDb(*args, **kwargs)]
return bdbs[-1]
yield _bukuDb
rmdb(*bdbs)
class PrettySafeLoader(
yaml.SafeLoader
): # pylint: disable=too-many-ancestors,too-few-public-methods
def construct_python_tuple(self, node):
return tuple(self.construct_sequence(node))
PrettySafeLoader.add_constructor(
"tag:yaml.org,2002:python/tuple", PrettySafeLoader.construct_python_tuple
)
class TestBukuDb(unittest.TestCase):
def setUp(self):
os.environ["XDG_DATA_HOME"] = TEST_TEMP_DIR_PATH
# start every test from a clean state
rmdb()
self.bookmarks = TEST_BOOKMARKS
self.bdb = BukuDb()
def tearDown(self):
os.environ["XDG_DATA_HOME"] = TEST_TEMP_DIR_PATH
rmdb(self.bdb)
@pytest.mark.non_tox
def test_get_default_dbdir(self):
dbdir_expected = TEST_TEMP_DBDIR_PATH
home = os.path.expanduser("~")
dbdir_local_expected = (os.path.join(home, ".local", "share", "buku") if sys.platform != 'win32' else
os.path.join(home, "AppData", "Roaming", "buku"))
dbdir_relative_expected = os.path.abspath(".")
# desktop linux
self.assertEqual(dbdir_expected, BukuDb.get_default_dbdir())
# desktop generic
os.environ.pop("XDG_DATA_HOME")
self.assertEqual(dbdir_local_expected, BukuDb.get_default_dbdir())
# no desktop
# -- home is defined differently on various platforms.
# -- keep a copy and set it back once done
originals = {}
for env_var in ["HOME", "HOMEPATH", "HOMEDIR", "APPDATA"]:
if env_var in os.environ:
originals[env_var] = os.environ.pop(env_var)
try:
self.assertEqual(dbdir_relative_expected, BukuDb.get_default_dbdir())
finally:
os.environ.update(originals)
# # not sure how to test this in nondestructive manner
# def test_move_legacy_dbfile(self):
# self.fail()
def test_initdb(self):
rmdb(self.bdb)
self.assertIs(False, exists(TEST_TEMP_DBFILE_PATH))
try:
conn, curr = BukuDb.initdb()
self.assertIsInstance(conn, sqlite3.Connection)
self.assertIsInstance(curr, sqlite3.Cursor)
self.assertIs(True, exists(TEST_TEMP_DBFILE_PATH))
finally:
curr.close()
conn.close()
def test_get_rec_by_id(self):
for bookmark in self.bookmarks:
# adding bookmark from self.bookmarks
_add_rec(self.bdb, *bookmark)
# the expected bookmark
expected = (1,) + tuple(TEST_BOOKMARKS[0]) + (0,)
bookmark_from_db = self.bdb.get_rec_by_id(1)
# asserting bookmark matches expected
self.assertEqual(expected, bookmark_from_db)
# asserting None returned if index out of range
self.assertIsNone(self.bdb.get_rec_by_id(len(self.bookmarks[0]) + 1))
def test_get_rec_all_by_ids(self):
for bookmark in self.bookmarks:
# adding bookmark from self.bookmarks
_add_rec(self.bdb, *bookmark)
expected = [(i+1,) + tuple(TEST_BOOKMARKS[i]) + (0,) for i in [0, 2]]
bookmarks_from_db = self.bdb.get_rec_all_by_ids([3, 1, 1, 3, 5]) # ignoring order and duplicates
self.assertEqual(expected, bookmarks_from_db)
def test_get_rec_id(self):
for idx, bookmark in enumerate(self.bookmarks):
# adding bookmark from self.bookmarks to database
_add_rec(self.bdb, *bookmark)
# asserting index is in order
idx_from_db = self.bdb.get_rec_id(bookmark[0])
self.assertEqual(idx + 1, idx_from_db)
# asserting None is returned for nonexistent url
idx_from_db = self.bdb.get_rec_id("http://nonexistent.url")
self.assertIsNone(idx_from_db)
def test_add_rec(self):
for bookmark in self.bookmarks:
# adding bookmark from self.bookmarks to database
self.bdb.add_rec(*bookmark, fetch=False)
# retrieving bookmark from database
index = self.bdb.get_rec_id(bookmark[0])
from_db = self.bdb.get_rec_by_id(index)
self.assertIsNotNone(from_db)
# comparing data
for pair in zip(from_db[1:], bookmark):
self.assertEqual(*pair)
def test_swap_recs(self):
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
for id1, id2 in [(0, 1), (1, 4), (1, 1)]:
self.assertFalse(self.bdb.swap_recs(id1, id2), 'Not a valid index pair: (%d, %d)' % (id1, id2))
self.assertTrue(self.bdb.swap_recs(1, 3), 'This one should be valid') # 3, 2, 1
self.assertEqual([x[0] for x in reversed(self.bookmarks)], [x.url for x in self.bdb.get_rec_all()])
# TODO: tags should be passed to the api as a sequence...
def test_suggest_tags(self):
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
tagstr = ",test,old,"
with mock.patch("builtins.input", return_value="1 2 3"):
expected_results = ",es,est,news,old,test,"
suggested_results = self.bdb.suggest_similar_tag(tagstr)
self.assertEqual(expected_results, suggested_results)
# returns user supplied tags if none are in the DB
tagstr = ",uniquetag1,uniquetag2,"
expected_results = tagstr
suggested_results = self.bdb.suggest_similar_tag(tagstr)
self.assertEqual(expected_results, suggested_results)
def test_update_rec(self):
old_values = self.bookmarks[0]
new_values = self.bookmarks[1]
# adding bookmark and getting index
_add_rec(self.bdb, *old_values)
index = self.bdb.get_rec_id(old_values[0])
# updating with new values
self.bdb.update_rec(index, *new_values)
# retrieving bookmark from database
from_db = self.bdb.get_rec_by_id(index)
self.assertIsNotNone(from_db)
# checking if values are updated
for pair in zip(from_db[1:], new_values):
self.assertEqual(*pair)
def test_append_tag_at_index(self):
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
# tags to add
old_tags = self.bdb.get_rec_by_id(1)[3]
new_tags = ",foo,bar,baz"
self.bdb.append_tag_at_index(1, new_tags)
# updated list of tags
from_db = self.bdb.get_rec_by_id(1)[3]
# checking if new tags were added to the bookmark
self.assertTrue(split_and_test_membership(new_tags, from_db))
# checking if old tags still exist
self.assertTrue(split_and_test_membership(old_tags, from_db))
def test_append_tag_at_all_indices(self):
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
# tags to add
new_tags = ",foo,bar,baz"
# record of original tags for each bookmark
old_tagsets = {
i: self.bdb.get_rec_by_id(i)[3]
for i in inclusive_range(1, len(self.bookmarks))
}
with mock.patch("builtins.input", return_value="y"):
self.bdb.append_tag_at_index(0, new_tags)
# updated tags for each bookmark
from_db = [
(i, self.bdb.get_rec_by_id(i)[3])
for i in inclusive_range(1, len(self.bookmarks))
]
for index, tagset in from_db:
# checking if new tags added to bookmark
self.assertTrue(split_and_test_membership(new_tags, tagset))
# checking if old tags still exist for bookmark
self.assertTrue(split_and_test_membership(old_tagsets[index], tagset))
def test_delete_tag_at_index(self):
# adding bookmarks
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
get_tags_at_idx = lambda i: self.bdb.get_rec_by_id(i)[3]
# list of two-tuples, each containing bookmark index and corresponding tags
tags_by_index = [
(i, get_tags_at_idx(i)) for i in inclusive_range(1, len(self.bookmarks))
]
for i, tags in tags_by_index:
# get the first tag from the bookmark
to_delete = re.match(",.*?,", tags).group(0)
self.bdb.delete_tag_at_index(i, to_delete)
# get updated tags from db
from_db = get_tags_at_idx(i)
self.assertNotIn(to_delete, from_db)
def test_search_keywords_and_filter_by_tags(self):
# adding bookmark
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
with mock.patch("buku.prompt"):
expected = [
(
3,
"http://example.com/",
"test",
",es,est,tes,test,",
"a case for replace_tag test",
0,
)
]
results = self.bdb.search_keywords_and_filter_by_tags(
["News", "case"],
False,
False,
False,
["est"],
)
self.assertIn(expected[0], results)
expected = [
(
3,
"http://example.com/",
"test",
",es,est,tes,test,",
"a case for replace_tag test",
0,
),
(
2,
"http://www.zażółćgęśląjaźń.pl/",
"ZAŻÓŁĆ",
",gęślą,jaźń,zażółć,",
"Testing UTF-8, zażółć gęślą jaźń.",
0,
),
]
results = self.bdb.search_keywords_and_filter_by_tags(
["UTF-8", "case"],
False,
False,
False,
"jaźń, test",
)
self.assertIn(expected[0], results)
self.assertIn(expected[1], results)
def test_searchdb(self):
# adding bookmarks
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
get_first_tag = lambda x: "".join(x[2].split(",")[:2])
for i, bookmark in enumerate(self.bookmarks):
tag_search = get_first_tag(bookmark)
# search by the domain name for url
url_search = re.match(r"https?://(.*)?\..*", bookmark[0]).group(1)
title_search = bookmark[1]
# Expect a five-tuple containing all bookmark data
# db index, URL, title, tags, description
expected = [(i + 1,) + tuple(bookmark)]
expected[0] += tuple([0])
# search db by tag, url (domain name), and title
for keyword in (tag_search, url_search, title_search):
with mock.patch("buku.prompt"):
# search by keyword
results = self.bdb.searchdb([keyword])
self.assertEqual(results, expected)
def test_search_by_tag(self):
# adding bookmarks
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
with mock.patch("buku.prompt"):
get_first_tag = lambda x: "".join(x[2].split(",")[:2])
for i, bookmark in enumerate(self.bookmarks):
# search for bookmark with a tag that is known to exist
results = self.bdb.search_by_tag(get_first_tag(bookmark))
# Expect a five-tuple containing all bookmark data
# db index, URL, title, tags, description
expected = [(i + 1,) + tuple(bookmark)]
expected[0] += tuple([0])
self.assertEqual(results, expected)
@pytest.mark.slow
@pytest.mark.vcr("tests/vcr_cassettes/test_search_by_multiple_tags_search_any.yaml")
def test_search_by_multiple_tags_search_any(self):
# adding bookmarks
for bookmark in self.bookmarks:
self.bdb.add_rec(*bookmark)
new_bookmark = [
"https://newbookmark.com",
"New Bookmark",
parse_tags(["test,old,new"]),
"additional bookmark to test multiple tag search",
0,
]
self.bdb.add_rec(*new_bookmark)
with mock.patch("buku.prompt"):
# search for bookmarks matching ANY of the supplied tags
results = self.bdb.search_by_tag("test, old")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description, ordered by records with
# the most number of matches.
expected = [
(
4,
"https://newbookmark.com",
"New Bookmark",
parse_tags([",test,old,new,"]),
"additional bookmark to test multiple tag search",
0,
),
(
1,
"http://slashdot.org",
"SLASHDOT",
parse_tags([",news,old,"]),
"News for old nerds, stuff that doesn't matter",
0,
),
(
3,
"http://example.com/",
"test",
",es,est,tes,test,",
"a case for replace_tag test",
0,
),
]
self.assertEqual(results, expected)
@pytest.mark.slow
@pytest.mark.vcr("tests/vcr_cassettes/test_search_by_multiple_tags_search_all.yaml")
def test_search_by_multiple_tags_search_all(self):
# adding bookmarks
for bookmark in self.bookmarks:
self.bdb.add_rec(*bookmark)
new_bookmark = [
"https://newbookmark.com",
"New Bookmark",
parse_tags(["test,old,new"]),
"additional bookmark to test multiple tag search",
]
self.bdb.add_rec(*new_bookmark)
with mock.patch("buku.prompt"):
# search for bookmarks matching ALL of the supplied tags
results = self.bdb.search_by_tag("test + old")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description
expected = [
(
4,
"https://newbookmark.com",
"New Bookmark",
parse_tags([",test,old,new,"]),
"additional bookmark to test multiple tag search",
0,
)
]
self.assertEqual(results, expected)
def test_search_by_tags_enforces_space_seprations_search_all(self):
bookmark1 = [
"https://bookmark1.com",
"Bookmark One",
parse_tags(["tag, two,tag+two"]),
"test case for bookmark with '+' in tag",
]
bookmark2 = [
"https://bookmark2.com",
"Bookmark Two",
parse_tags(["tag,two, tag-two"]),
"test case for bookmark with hyphenated tag",
]
_add_rec(self.bdb, *bookmark1)
_add_rec(self.bdb, *bookmark2)
with mock.patch("buku.prompt"):
# check that space separation for ' + ' operator is enforced
results = self.bdb.search_by_tag("tag+two")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description
expected = [
(
1,
"https://bookmark1.com",
"Bookmark One",
parse_tags([",tag,two,tag+two,"]),
"test case for bookmark with '+' in tag",
0,
)
]
self.assertEqual(results, expected)
results = self.bdb.search_by_tag("tag + two")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description
expected = [
(
1,
"https://bookmark1.com",
"Bookmark One",
parse_tags([",tag,two,tag+two,"]),
"test case for bookmark with '+' in tag",
0,
),
(
2,
"https://bookmark2.com",
"Bookmark Two",
parse_tags([",tag,two,tag-two,"]),
"test case for bookmark with hyphenated tag",
0,
),
]
self.assertEqual(results, expected)
def test_search_by_tags_exclusion(self):
# adding bookmarks
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
new_bookmark = [
"https://newbookmark.com",
"New Bookmark",
parse_tags(["test,old,new"]),
"additional bookmark to test multiple tag search",
]
_add_rec(self.bdb, *new_bookmark)
with mock.patch("buku.prompt"):
# search for bookmarks matching ANY of the supplied tags
# while excluding bookmarks from results that match a given tag
results = self.bdb.search_by_tag("test, old - est")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description
expected = [
(
4,
"https://newbookmark.com",
"New Bookmark",
parse_tags([",test,old,new,"]),
"additional bookmark to test multiple tag search",
0,
),
(
1,
"http://slashdot.org",
"SLASHDOT",
parse_tags([",news,old,"]),
"News for old nerds, stuff that doesn't matter",
0,
),
]
self.assertEqual(results, expected)
@pytest.mark.vcr("tests/vcr_cassettes/test_search_by_tags_enforces_space_seprations_exclusion.yaml")
def test_search_by_tags_enforces_space_seprations_exclusion(self):
bookmark1 = [
"https://bookmark1.com",
"Bookmark One",
parse_tags(["tag, two,tag+two"]),
"test case for bookmark with '+' in tag",
]
bookmark2 = [
"https://bookmark2.com",
"Bookmark Two",
parse_tags(["tag,two, tag-two"]),
"test case for bookmark with hyphenated tag",
]
bookmark3 = [
"https://bookmark3.com",
"Bookmark Three",
parse_tags(["tag, tag three"]),
"second test case for bookmark with hyphenated tag",
]
self.bdb.add_rec(*bookmark1)
self.bdb.add_rec(*bookmark2)
self.bdb.add_rec(*bookmark3)
with mock.patch("buku.prompt"):
# check that space separation for ' - ' operator is enforced
results = self.bdb.search_by_tag("tag-two")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description
expected = [
(
2,
"https://bookmark2.com",
"Bookmark Two",
parse_tags([",tag,two,tag-two,"]),
"test case for bookmark with hyphenated tag",
0,
),
]
self.assertEqual(results, expected)
results = self.bdb.search_by_tag("tag - two")
# Expect a list of five-element tuples containing all bookmark data
# db index, URL, title, tags, description
expected = [
(
3,
"https://bookmark3.com",
"Bookmark Three",
parse_tags([",tag,tag three,"]),
"second test case for bookmark with hyphenated tag",
0,
),
]
self.assertEqual(results, expected)
def test_search_and_open_in_browser_by_range(self):
# adding bookmarks
for bookmark in self.bookmarks:
_add_rec(self.bdb, *bookmark)
# simulate user input, select range of indices 1-3
index_range = "1-%s" % len(self.bookmarks)
with mock.patch("builtins.input", side_effect=[index_range]):
with mock.patch("buku.browse") as mock_browse:
try:
# search the db with keywords from each bookmark
# searching using the first tag from bookmarks
get_first_tag = lambda x: x[2].split(",")[1]
results = self.bdb.searchdb(
[get_first_tag(bm) for bm in self.bookmarks]
)
prompt(self.bdb, results)
except StopIteration:
# catch exception thrown by reaching the end of the side effect iterable
pass
# collect arguments passed to browse
arg_list = [args[0] for args, _ in mock_browse.call_args_list]
# expect a list of one-tuples that are bookmark URLs
expected = [x[0] for x in self.bookmarks]
# checking if browse called with expected arguments
self.assertEqual(arg_list, expected)
@pytest.mark.slow
@pytest.mark.vcr("tests/vcr_cassettes/test_search_and_open_all_in_browser.yaml")
def test_search_and_open_all_in_browser(self):
# adding bookmarks
for bookmark in self.bookmarks:
self.bdb.add_rec(*bookmark)
# simulate user input, select 'a' to open all bookmarks in results
with mock.patch("builtins.input", side_effect=["a"]):
with mock.patch("buku.browse") as mock_browse:
try:
# search the db with keywords from each bookmark
# searching using the first tag from bookmarks
get_first_tag = lambda x: x[2].split(",")[1]
results = self.bdb.searchdb(
[get_first_tag(bm) for bm in self.bookmarks[:2]]
)
prompt(self.bdb, results)
except StopIteration:
# catch exception thrown by reaching the end of the side effect iterable
pass
# collect arguments passed to browse
arg_list = [args[0] for args, _ in mock_browse.call_args_list]
# expect a list of one-tuples that are bookmark URLs
expected = [x[0] for x in self.bookmarks][:2]
# checking if browse called with expected arguments
self.assertEqual(arg_list, expected)
def test_delete_rec(self):
# adding bookmark and getting index
_add_rec(self.bdb, *self.bookmarks[0])
index = self.bdb.get_rec_id(self.bookmarks[0][0])
# deleting bookmark
self.bdb.delete_rec(index)
# asserting it doesn't exist
from_db = self.bdb.get_rec_by_id(index)
self.assertIsNone(from_db)
def test_delete_rec_yes(self):
# checking that "y" response causes delete_rec to return True
with mock.patch("builtins.input", return_value="y"):
self.assertTrue(self.bdb.delete_rec(0))
def test_delete_rec_no(self):
# checking that non-"y" response causes delete_rec to return None
with mock.patch("builtins.input", return_value="n"):
self.assertFalse(self.bdb.delete_rec(0))
def test_cleardb(self):
# adding bookmarks
_add_rec(self.bdb, *self.bookmarks[0])
# deleting all bookmarks
with mock.patch("builtins.input", return_value="y"):
self.bdb.cleardb()
# assert table has been dropped
assert self.bdb.get_rec_by_id(0) is None
def test_replace_tag(self):
indices = []
for bookmark in self.bookmarks:
# adding bookmark, getting index
_add_rec(self.bdb, *bookmark)
index = self.bdb.get_rec_id(bookmark[0])
indices += [index]
# replacing tags
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("news", ["__01"])
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("zażółć", ["__02,__03"])
# replacing tag which is also a substring of other tag
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("es", ["__04"])
# removing tags
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("gęślą")
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("old")
# removing non-existent tag
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("_")
# removing nonexistent tag which is also a substring of other tag
with mock.patch("builtins.input", return_value="y"):
self.bdb.replace_tag("e")
for url, title, _, _ in self.bookmarks:
# retrieving from db
index = self.bdb.get_rec_id(url)
from_db = self.bdb.get_rec_by_id(index)
# asserting tags were replaced
if title == "SLASHDOT":
self.assertEqual(from_db[3], parse_tags(["__01"]))
elif title == "ZAŻÓŁĆ":
self.assertEqual(from_db[3], parse_tags(["__02,__03,jaźń"]))
elif title == "test":
self.assertEqual(from_db[3], parse_tags(["test,tes,est,__04"]))
def test_tnyfy_url(self):
tny, full = 'http://tny.im/yt', 'https://www.google.com'
# shorten a well-known url
with mock_http(tny, status=200):
shorturl = self.bdb.tnyfy_url(url=full, shorten=True)
self.assertEqual(shorturl, tny)
# expand a well-known short url
with mock_http(full, status=200):
url = self.bdb.tnyfy_url(url=tny, shorten=False)
self.assertEqual(url, full)
# def test_browse_by_index(self):
# self.fail()
def test_close_quit(self):
# quitting with no args
try:
self.bdb.close_quit()
except SystemExit as err:
self.assertEqual(err.args[0], 0)
# quitting with custom arg
try:
self.bdb.close_quit(1)
except SystemExit as err:
self.assertEqual(err.args[0], 1)
# def test_import_bookmark(self):
# self.fail()
@pytest.mark.parametrize('status', [None, 200, 302, 308, 404, 500])
@pytest.mark.parametrize('fetch, url_redirect, tag_redirect, tag_error, del_error', [
(False, False, False, False, None), # offline
(True, True, False, False, None), # url-redirect
(True, False, True, True, None), # tag-redirect, tag-error
(True, True, 'http-{}', 'error:{}', None), # url-redirect, fetch-tags (custom patterns)
(True, True, 'redirect', 'error', None), # ... (patterns without codes)
(True, True, 'redirect', False, range(400, 600)), # del-error (any errors)
(True, True, 'redirect', 'error', {404}), # ... (some errors)
])
def test_add_rec_fetch(bukuDb, caplog, fetch, url_redirect, tag_redirect, tag_error, del_error, status):
'''Testing add_rec() behaviour with fetch-status params'''
title_in, title, desc = 'Custom Title', 'Fetched Title', 'Fetched description.'
tags_in, url_in, url_new = ',custom,tags,', 'https://example.com', 'https://example.com/redirect'
url = (url_new if status in PERMANENT_REDIRECTS else url_in)
bdb = bukuDb()
with mock_fetch(url=url, title=title, desc=desc, fetch_status=status) as fetch_data:
index = bdb.add_rec(url=url_in, title_in=title_in, tags_in=tags_in, fetch=fetch,
url_redirect=url_redirect, tag_redirect=tag_redirect,
tag_error=tag_error, del_error=del_error)
# del-error?
if del_error and (not status or status in del_error):
assert index is None
assert bdb.get_max_id() is None
err = ('Network error' if not status else 'HTTP error {}'.format(status))
assert caplog.record_tuples == [('root', 40, 'add_rec(): '+err)]
return
rec = bdb.get_rec_by_id(index)
# offline?
if not fetch:
fetch_data.assert_not_called()
assert (rec.url, rec.title, rec.desc) == (url_in, title_in, '')
assert _tagset(rec.tags_raw) == _tagset(tags_in)
return
# url-redirect?
if url_redirect and status in PERMANENT_REDIRECTS:
assert rec.url == url_new
else:
assert rec.url == url_in
# custom title, fetched description
assert (rec.title, rec.desc) == (title_in, desc), 'custom title overrides fetched title'
# fetch-tags?
_tags = _tagset(tags_in)
if tag_redirect and status in PERMANENT_REDIRECTS:
_tags |= {('http:{}' if tag_redirect is True else tag_redirect).format(status).lower()}
if tag_error and (status or 0) >= 400:
_tags |= {('http:{}' if tag_error is True else tag_error).format(status).lower()}
assert _tagset(rec.tags) == _tags
@pytest.mark.parametrize('status, tags_fetched, tags_in, tags_except, expected', [
(None, None, 'foo,qux,foo bar,bar,baz', 'except,bar,foo,', ',baz,foo bar,qux,'),
(200, '', 'foo,qux,foo bar,bar,baz', None, ',bar,baz,foo,foo bar,qux,'),
(200, 'there,have been,some,tags,fetched', None,
'except,bar,tags,there,foo', ',fetched,have been,some,'),
(200, 'there,have been,some,tags,fetched', 'foo,qux,foo bar,bar,baz',
'except,bar,tags,there,foo', ',baz,fetched,foo bar,have been,qux,some,'),
(404, None, 'foo,foo bar,qux,bar,baz', 'except,bar,foo', ',baz,foo bar,http:error,qux,'),
(301, 'there,have been,some,tags,fetched', 'foo,foo bar,qux,bar,baz',
'except,bar,tags,there,foo', ',baz,fetched,foo bar,have been,http:redirect,qux,some,'),
(308, 'there,have been,some,tags,fetched', 'foo,foo bar,qux,bar,baz',
'except,http:redirect,bar,tags,there,foo', ',baz,fetched,foo bar,have been,qux,some,'),
])
def test_add_rec_tags(bukuDb, caplog, status, tags_fetched, tags_in, tags_except, expected):
'''Testing add_rec() behaviour with tags params'''
url, keywords = 'https://example.com', (',fetched,tags,' if tags_fetched is None else tags_fetched)
bdb = bukuDb()
with mock_fetch(url=url, title='Title', keywords=keywords, fetch_status=status):
index = bdb.add_rec(url=url, fetch=status is not None, tags_in=tags_in, tags_except=tags_except,
tags_fetch=tags_fetched is not None, tag_redirect='http:redirect', tag_error='http:error')
rec = bdb.get_rec_by_id(index)
assert rec.tags_raw == expected
@pytest.mark.parametrize('index', [1, {2, 3}, None])
@pytest.mark.parametrize('export_on', [None, PERMANENT_REDIRECTS, range(400, 600), PERMANENT_REDIRECTS | {404}])
@pytest.mark.parametrize('url_in, title_in, tags_in, url_redirect, tag_redirect, tag_error, del_error', [
(None, None, None, False, False, False, None), # fetched title/desc, no network test
(None, 'Custom Title', ',custom,tags,', False, False, False, None), # title, tags, no network test
('http://custom.url', None, None, False, False, False, None), # url, fetched title/desc, no network test
('http://custom.url', 'Custom Title', ',custom,tags,', False, False, False, None), # url, title, tags, no network test
(None, 'Custom Title', '+,custom,tags,', True, False, False, None), # title, +tags, url-redirect
('http://custom.url', 'Custom Title', '+,custom,tags,', False, True, True, None), # url, title, +tags, fetch-tags
(None, 'Custom Title', None, True, 'http-{}', 'error:{}', None), # title, url-redirect, fetch-tags (custom)
(None, None, '-,initial%,', True, 'redirect', 'error', None), # -tags, url-redirect, fetch-tags (no codes)
('http://custom.url', 'Custom Title', None, True, 'redirect', False, range(400, 600)), # url, title, url-redirect, del-error
(None, None, ',custom,tags,', True, 'redirect', 'error', {404}), # tags, url-redirect, fetch-tags, del-error
])
def test_update_rec_fetch(bukuDb, caplog, url_in, title_in, tags_in, url_redirect, tag_redirect, tag_error, del_error, export_on, index):
'''Testing update_rec() behaviour with fetch-status params'''
# redirected URL, nonexistent page, nonexistend domain
urls = {
'http://wikipedia.net': {'fetch_status': 301, 'url': 'https://www.wikipedia.org', 'title': 'Wikipedia',
'desc': 'Wikipedia is a free online encyclopedia, created and edited blah blah'},
'https://python.org/notfound': {'fetch_status': 404, 'title': 'Welcome to Python.org',
'desc': 'The official home of the Python Programming Language'},
'http://nonexistent.url': {'fetch_status': None}, # unable to resolve host address
}
# for the URL override
custom_url = {'fetch_status': 200, 'title': 'Fetched Title', 'desc': 'Fetched description.'}
def custom_fetch(url, http_head=False):
data = dict(urls.get(url, custom_url))
_url = data.pop('url', url)
return FetchResult(url_in or _url, **data)
# computed test parameters
title_initial, tags_initial, desc = 'Initial Title', ',initial%,tags,', 'Initial description.'
fetch_title = title_in is tags_in is None # when no custom params are passed (except for URL), titles are fetched
network_test = url_redirect or tag_redirect or tag_error or del_error or export_on or fetch_title
indices = ({index} if isinstance(index, int) else index or range(1, len(urls)+1))
tags = _tagset(tags_in if (tags_in or '').startswith(',') else tags_initial)
if not (tags_in or ',').startswith(','):
tags = (tags | _tagset(tags_in[1:]) if tags_in.startswith('+') else tags - _tagset(tags_in[1:]))
# setup
bdb = bukuDb()
for url_initial in urls:
_add_rec(bdb, url_initial, title_in=title_initial, tags_in=tags_initial, desc=desc)
assert bdb.get_max_id() == len(urls), 'expecting correct setup'
with mock_fetch(custom_fetch) as fetch_data:
with mock.patch('buku.read_in', return_value='y'):
ok = bdb.update_rec(index=index, url=url_in, title_in=title_in, tags_in=tags_in,
url_redirect=url_redirect, tag_redirect=tag_redirect,
tag_error=tag_error, del_error=del_error, export_on=export_on)
recs = bdb.get_rec_all()
# custom URL on multiple records?
if url_in and len(indices) != 1:
assert not ok, 'expected to fail'
assert caplog.record_tuples == [('root', 40, 'All URLs cannot be same')]
fetch_data.assert_not_called()
assert recs == [BookmarkVar(id, url, title_initial, tags_initial, desc)
for id, url in enumerate(urls, start=1)]
return
assert ok, 'expected to succeed'
# offline?
if not network_test and not (url_in and title_in is None):
_tags = ',' + ','.join(sorted(tags)) + ','
fetch_data.assert_not_called()
for rec, url in zip(recs, urls):
if rec.id in indices:
assert rec == BookmarkVar(rec.id, url_in or url, title_in or title_initial, _tags, desc)
else:
assert rec == BookmarkVar(rec.id, url, title_initial, tags_initial, desc)
return
# export-on (given HTTP codes)?
if not export_on:
assert bdb._to_export is None, f'expected no to_export backup: {bdb._to_export}'
else:
assert isinstance(bdb._to_export, dict), f'to_export backup is not a dict: {bdb._to_export}'
to_export = dict(bdb._to_export or {})
_urls, _recs = set(urls), {x.url: x for x in recs}
# one fetch per index
assert fetch_data.call_count == len(indices), f'expected {len(indices)} fetches, done {fetch_data.call_count}'
for call in fetch_data.call_args_list:
# determining fetched, original and redirected URLs, along with fetched data
url = call.args[0]
url_old = url if not url_in else list(urls)[index-1] # url_in applies to a single record
_urls -= {url_old}
data = urls.get(url, custom_url)
url_new = (url if not url_redirect else data.get('url', url))
rec = _recs.pop(url_new, None)
status = data.get('fetch_status')
# del-error? export-on?
old = to_export.pop(url_new, None)
if not export_on or status not in export_on:
assert old is None, f'{url_old}: backup not expected'
if del_error and status in del_error:
assert rec is None, f'{url_old}: HTTP error {status}, should delete'
if export_on and status in export_on:
assert isinstance(old, BookmarkVar), f'{url_old}: should backup old record'
assert (old.url, old.title, old.tags_raw, old.desc) == (url_old, title_initial, tags_initial, desc)
continue
if export_on and status in export_on:
assert old == url_old, f'{url_old}: should backup old url on redirect'
# url-redirect?
if url_redirect and status in PERMANENT_REDIRECTS:
assert url_new != url_old, f'{url_old}: redirect expected'
assert rec.url == url_new, f'{url_old}: should replace with {url_new}'
else:
assert url_new == rec.url, f'{url_old}: redirect not expected'
assert url_new == (url_in or url_old), f'{url_old}: URL should not be changed'
# title
if title_in or (fetch_title and 'title' in data):
assert rec.title == (title_in or data['title']), f'{url_old}: should update title'