-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
executable file
·1634 lines (1299 loc) · 51.5 KB
/
tests.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 python
# -*- coding: utf-8 -*-
"""
Tests for notefile.
Tests are run as if from the CLI but run in Python for the sake of test coverage
Generally, with the new design, there is reuse of capabilities given by argument
groups. So these test commands and argument groups. Once an argument group is tested in
one (e.g. search), it is not restest for search and find.
"""
import os, io, sys
import shutil
import shlex
import hashlib
import glob
import itertools
import copy
from pathlib import Path
import time
import json
import warnings
import unicodedata
import pickle
import notefile # this *should* import the local version even if it is installed
import notefile.cli
Notefile = notefile.Notefile
print("version", notefile.__version__)
print("path", notefile.__file__) # This is just to see that it imported the right now
notefile.DEBUG = False
import pytest
TESTDIR = Path("testdirs").resolve()
TESTDIR.mkdir(parents=True, exist_ok=True)
with (TESTDIR / ".ignore").open("wt") as f:
pass
class SysExitError(ValueError):
pass
def call(s, capture=False):
try:
if capture:
try:
o, e = sys.stdout, sys.stderr
sys.stdout = io.StringIO()
sys.stdout.buffer = sys.stdout
sys.stderr = io.StringIO()
sys.stderr.buffer = sys.stderr
notefile.cli.cli(shlex.split(s))
sys.stdout.flush()
sys.stderr.flush()
return sys.stdout.getvalue(), sys.stderr.getvalue()
finally:
sys.stdout, sys.stderr = o, e
sys.stdout.flush()
sys.stderr.flush()
return notefile.cli.cli(shlex.split(s))
except SystemExit:
raise SysExitError()
class CaptureDebug:
def __init__(self):
self.stdout = None
self.stderr = None
def __enter__(self):
self._o, self._e = sys.stdout, sys.stderr
sys.stdout = io.StringIO()
sys.stdout.buffer = sys.stdout
sys.stderr = io.StringIO()
sys.stderr.buffer = sys.stderr
self._d = notefile.DEBUG
notefile.DEBUG = True
return self
def __exit__(self, type, value, traceback):
notefile.DEBUG = self._d
sys.stdout.flush()
sys.stderr.flush()
self.stdout = sys.stdout.getvalue()
self.stderr = sys.stderr.getvalue()
sys.stdout, sys.stderr = self._o, self._e
sys.stdout.flush()
sys.stderr.flush()
def cleanmkdir(dirpath):
notefile.DEBUG = False # Reset this
try:
shutil.rmtree(dirpath)
except:
pass
Path(dirpath).mkdir(parents=True)
def writefile(filepath, text="", append=False):
filepath = Path(filepath)
filepath.parent.mkdir(parents=True, exist_ok=True)
if append:
with filepath.open(mode="at") as f:
f.write("\n" + text)
else:
filepath.write_text(text)
def readout(out):
with open(out, "rb") as f:
lines = f.read().replace(b"\x00", b"\n").decode().split("\n")
return {l for l in lines if l.strip()}
def readtags(out):
with open(out) as f:
tags = notefile.nfyaml.load_yaml(f.read())
return {tag: (set(files) if isinstance(files, list) else files) for tag, files in tags.items()}
def is_hidden(filename, check_dupe=True):
"""
returns whether a file exists and is hidden.
Will assert that (a) the file exists and (b) there
aren't a hidden and visible if check_dupe
"""
_, vis, hid = notefile.get_filenames(filename)
if check_dupe and os.path.exists(vis) and os.path.exists(hid):
assert False, "Duplicate hidden and visible"
check_vis = os.path.exists(vis) or os.path.islink(vis) # broken links still are fine
check_hid = os.path.exists(hid) or os.path.islink(hid) # broken links still are fine
if not (check_hid or check_vis):
assert False, "Neither file exists"
return check_hid
def test_mod():
"""
Test CLI mod
"""
os.chdir(TESTDIR)
dirpath = TESTDIR / "mod"
cleanmkdir(dirpath)
os.chdir(dirpath)
writefile("file1.txt", "file1.")
call('mod -t tag1 -t tag2 -n"note1" file1.txt')
note1 = Notefile("file1.txt").read()
assert note1.data.notes == "note1"
assert set(note1.data.tags) == {"tag1", "tag2"}
call('mod -t tag3 -r tag1 -n"more" file1.txt')
note1 = Notefile("file1.txt").read()
assert note1.data.notes == "note1\nmore"
assert set(note1.data.tags) == {"tag3", "tag2"}
# Test adding via commas
call('mod -t "tag4,tag 5" -t tag6,tag7 -r "tag2, tag3" file1.txt')
note1 = Notefile("file1.txt").read()
assert set(note1.data.tags) == {"tag 5", "tag4", "tag6", "tag7"}
note1.data.tags = "tag3", "tag2" # Reset
note1.write()
call('mod --replace --note "new" file1.txt')
note1 = Notefile("file1.txt").read()
assert note1.data.notes == "new"
# Monkey patch stdin
try:
stdin0 = sys.stdin
import io
sys.stdin = io.StringIO("stdin str")
call('mod -s -n"worked?" file1.txt')
finally:
sys.stdin = stdin0
note1 = Notefile("file1.txt").read()
assert note1.data.notes == "new\nstdin str\nworked?"
# This will run through the code for edit but with a special flag just for testing
try:
# Regular
notefile.notefile._TESTEDIT = "test note"
note1.interactive_edit()
assert note1.data.notes == "test note"
# full
note2 = copy.deepcopy(note1)
note2.data.notes = "mod full"
note2.data.tags = ["tag1"]
note2.data.other = {"other": "data"}
notefile.notefile._TESTEDIT = note2.writes()
del note2 # not needed but to make sure I do not mess up
note1.interactive_edit(full=True)
assert note1.data.other == {"other": "data"}
assert set(note1.data.tags) == {"tag1"}
assert note1.data.notes == "mod full"
finally:
notefile.notefile._TESTEDIT = False
os.chdir(TESTDIR)
def test_create_opts():
"""
Test "new" options
"""
os.chdir(TESTDIR)
dirpath = TESTDIR / "create"
cleanmkdir(dirpath)
os.chdir(dirpath)
## --hidden and --visible
writefile("file1.txt", "file1.")
writefile("file2.txt", "file2..")
writefile("file3.txt", "file3...")
call('mod -n "note" file1.txt')
call('mod -n "note" -V file2.txt')
call('mod -n "note" -H file3.txt')
assert os.path.exists("file1.txt.notes.yaml") and not os.path.exists(".file1.txt.notes.yaml")
assert os.path.exists("file2.txt.notes.yaml") and not os.path.exists(".file2.txt.notes.yaml")
assert os.path.exists(".file3.txt.notes.yaml") and not os.path.exists("file3.txt.notes.yaml")
## --no-hash
writefile("file4.txt", "file4....")
call('mod -n "note" file4.txt --no-hash')
note3 = Notefile("file3.txt").read()
note4 = Notefile("file4.txt").read()
assert "sha256" in note3.data and "sha256" not in note4.data
## --no-refresh
writefile("file5.txt", "file5.....")
call('mod -n "note" file5.txt')
h1 = Notefile("file5.txt").read().data.sha256
writefile("file5.txt", "a", append=True)
call('mod -n "note2" file5.txt')
h2 = Notefile("file5.txt").read().data.sha256
assert h1 != h2
writefile("file5.txt", "a", append=True)
call('mod -n "note3" file5.txt --no-refresh')
h3 = Notefile("file5.txt").read().data.sha256
assert h2 == h3
## Refresh after --no-hash
writefile("file6.txt", "file6......")
call('mod -n "note" file6.txt --no-hash')
assert "sha256" not in Notefile("file6.txt").read().data
call('mod -n "note2" file6.txt')
assert "sha256" not in Notefile("file6.txt").read().data
# Modifying the file SHOULD make it compute the hash unless --no-refresh is set again
writefile("file6.txt", "line", append=True)
call('mod -n "note3" file6.txt --no-refresh')
assert "sha256" not in Notefile("file6.txt").read().data
writefile("file6.txt", "line3", append=True)
call('mod -n "note4" file6.txt')
assert "sha256" in Notefile("file6.txt").read().data # refreshed
## Link mode
# Visible
writefile("file7.txt", "file7.......")
writefile("file8.txt", "file8........")
writefile("file9.txt", "file9.........")
os.symlink("file7.txt", "link7.txt")
os.symlink("file8.txt", "link8.txt")
os.symlink("file9.txt", "link9.txt")
call("mod -t link link7.txt --link both")
call("mod -t link link8.txt --link symlink")
call("mod -t link link9.txt --link source")
assert os.path.exists("link7.txt.notes.yaml") and os.path.exists("file7.txt.notes.yaml")
assert os.path.exists("link8.txt.notes.yaml") and not os.path.exists("file8.txt.notes.yaml")
assert not os.path.exists("link9.txt.notes.yaml") and os.path.exists("file9.txt.notes.yaml")
# Hidden
writefile("file10.txt", "file10..........")
writefile("file11.txt", "file11...........")
writefile("file12.txt", "file12............")
os.symlink("file10.txt", "link10.txt")
os.symlink("file11.txt", "link11.txt")
os.symlink("file12.txt", "link12.txt")
call("mod -t link link10.txt --hidden --link both")
call("mod -t link link11.txt --hidden --link symlink")
call("mod -t link link12.txt --hidden --link source")
assert os.path.exists(".link10.txt.notes.yaml") and os.path.exists(".file10.txt.notes.yaml")
assert os.path.exists(".link11.txt.notes.yaml") and not os.path.exists(".file11.txt.notes.yaml")
assert not os.path.exists(".link12.txt.notes.yaml") and os.path.exists(".file12.txt.notes.yaml")
# Visible on existing hidden
os.symlink("file10.txt", "link10-V.txt")
os.symlink("file11.txt", "link11-V.txt")
os.symlink("file12.txt", "link12-V.txt")
call("mod -t link2 link10-V.txt --visible --link both")
call("mod -t link2 link11-V.txt --visible --link symlink")
call("mod -t link2 link12-V.txt --visible --link source")
assert os.path.exists("link10-V.txt.notes.yaml") and os.path.exists(".file10.txt.notes.yaml")
assert os.path.exists("link11-V.txt.notes.yaml") and not os.path.exists(
".file11.txt.notes.yaml"
)
assert not os.path.exists("link12-V.txt.notes.yaml") and os.path.exists(
".file12.txt.notes.yaml"
)
assert (
Notefile("link10-V.txt").read().data.tags
== Notefile("link10.txt").read().data.tags
== Notefile("file10.txt").read().data.tags
)
assert Notefile("link11-V.txt").read().data.tags == ["link2"]
assert Notefile("link11.txt").read().data.tags == ["link"]
assert Notefile("file11.txt").read().data.tags == []
assert (
Notefile("link12-V.txt").read().data.tags
== Notefile("link12.txt").read().data.tags
== Notefile("file12.txt").read().data.tags
)
## --format and rewrite-format
writefile("file13.txt", "file13.............")
call("mod -t note file13.txt --format json")
assert Notefile("file13.txt").read().format == "json"
call("mod -t note2 file13.txt --format yaml") # should NOT change format
assert Notefile("file13.txt").read().format == "json"
call("mod -t note3 file13.txt --format yaml --rewrite-format") # should now change format
assert Notefile("file13.txt").read().format == "yaml"
os.chdir(TESTDIR)
def test_copy():
os.chdir(TESTDIR)
dirpath = TESTDIR / "copy"
cleanmkdir(dirpath)
os.chdir(dirpath)
writefile("file1.txt", "file1.")
writefile("file2.txt", "file2..")
writefile("file3.txt", "file3...")
call('mod -t tag1 -n"this note" file1.txt')
call("copy -H file1.txt file2.txt file3.txt") # also test -H again
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
note3 = Notefile("file3.txt").read()
for key in set(note1.data).difference(notefile.notefile.METADATA):
assert note1.data[key] == note2.data[key] == note3.data[key], f"failed {key}"
assert note2.is_hidden == note3.is_hidden == True
try:
call("copy file1.txt file2.txt --debug") # --debug to get the error
assert False
except ValueError:
pass
os.chdir(TESTDIR)
def test_replace():
os.chdir(TESTDIR)
dirpath = TESTDIR / "replace"
cleanmkdir(dirpath)
os.chdir(dirpath)
## Regular
writefile("file1.txt", "file1.")
writefile("file2.txt", "file2..")
writefile("file3.txt", "file3...")
writefile("file4.txt", "file4....")
call('mod -t tag1 -t tagshared -n"note file 1" file1.txt')
call('mod -t tag2 -t tagshared -n"note FILE 2" file2.txt')
call('mod -t tag3 -t tagshared -n"note FiLe 3" file3.txt')
call('mod -t tag4 -t tagshared -n"NOTE FiLe 4" file4.txt')
call("replace file1.txt file2.txt")
call("replace file1.txt file3.txt --field tags")
call("replace file1.txt file4.txt --all-fields")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
note3 = Notefile("file3.txt").read()
note4 = Notefile("file4.txt").read()
assert note1.data.notes == note2.data.notes
assert note1.data.tags != note2.data.tags
assert note1.data.notes != note3.data.notes
assert note1.data.tags == note3.data.tags
assert note1.data.notes == note4.data.notes
assert note1.data.tags == note4.data.tags
## Appends
writefile("file5.txt", "file5.....")
call("replace file1.txt file5.txt")
call("replace file3.txt file5.txt --append")
note5 = Notefile("file5.txt").read()
assert note5.data.notes == "note file 1\nnote FiLe 3" # appended notes
call("mod -t newtag file5.txt")
call("replace file1.txt file5.txt --field tags --append")
note5 = Notefile("file5.txt").read()
assert set(note5.data.tags) == {"newtag", "tag1", "tagshared"} # kep newtag
## Appends on non-text fields
writefile("file6.txt", "file6......")
writefile("file7.txt", "file7.......")
note6 = Notefile("file6.txt").read()
note6.data.newstring = "this is a string field"
note6.data.newdict = {"this is": "a dict"}
note6.data.newlist = ["this is", "a", "list"]
note6.write()
call(
"replace file6.txt file7.txt --all-fields --append"
) # This will work since new(dict/list() doesn't yet exists_action()
note7 = Notefile("file7.txt").read()
for key in {
"newdict",
"newstring",
"notes",
"newlist",
"tags",
}: # set(note6.data).difference(notefile.notefile.METADATA)
assert note6.data[key] == note7.data[key], f"failed {key}"
call("replace file6.txt file7.txt --field newstring --append")
note7 = Notefile("file7.txt").read()
assert note7.data.newstring == "this is a string field\nthis is a string field"
try:
call("replace file6.txt file7.txt --field newdict --append --debug")
assert False
except TypeError:
pass
try:
call("replace file6.txt file7.txt --field newlist --append --debug")
assert False
except TypeError:
pass
# Non-existing fields
call(
"replace file1.txt file7.txt --field newlist --append"
) # even though newlist is on file7, it isn't on 1 so ignore
call("replace file1.txt file7.txt --field allnew --append") # Not on either. Do nothing
os.chdir(TESTDIR)
@pytest.mark.parametrize("vis", (True, False))
def test_change_viz_and_format(vis):
"""
Test changing viz and also formats. If vis will keep the legacy "vis" commands
"""
vis = "vis" if vis else ""
os.chdir(TESTDIR)
dirpath = TESTDIR / "formats"
cleanmkdir(dirpath)
os.chdir(dirpath)
# Viz first
writefile("file1.txt", "file1.")
writefile("file2.txt", "file2..")
call("mod -V -t tag -n note file1.txt")
call("mod -H -t tag -n note file2.txt")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert not note1.is_hidden and note2.is_hidden
# verify the built-in settings
assert os.path.exists("file1.txt.notes.yaml")
assert not os.path.exists(".file1.txt.notes.yaml")
assert os.path.exists(".file2.txt.notes.yaml")
assert not os.path.exists("file2.txt.notes.yaml")
# Make sure they do not change
call(f"{vis} show file1.txt") # already vis
call(f"{vis} hide file2.txt") # already hidden
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert not note1.is_hidden and note2.is_hidden
# Change one
call(f"{vis} show file2.txt")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert not note1.is_hidden and not note2.is_hidden
# Change both
call(f"{vis} hide")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert note1.is_hidden and note2.is_hidden
call(f"{vis} show --dry-run")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert note1.is_hidden and note2.is_hidden
shutil.copy(".file1.txt.notes.yaml", "file1.txt.notes.yaml")
with pytest.raises(notefile.notefile.MultipleNotesError):
call("vis --debug show file1.txt", capture=True)
os.unlink("file1.txt.notes.yaml")
## JSON vs YAML
# Verify the mode.
try:
with open(note1.destnote) as f:
json.load(f)
assert False
except json.decoder.JSONDecodeError:
assert True # Not JSON
try:
with open(note2.destnote) as f:
json.load(f)
assert False
except json.decoder.JSONDecodeError:
assert True # Not JSON
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert note1.format == note2.format == "yaml"
call("format json file1.txt")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert note1.format == "json" and note2.format == "yaml"
try:
with open(note1.destnote) as f:
json.load(f)
assert True
except json.decoder.JSONDecodeError:
assert False # Not JSON
call("format json")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert note1.format == note2.format == "json"
call("format yaml --dry-run")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert note1.format == note2.format == "json"
os.chdir(TESTDIR)
def test_change_tag():
"""
Test changing viz and also formats
"""
os.chdir(TESTDIR)
dirpath = TESTDIR / "change-tag"
cleanmkdir(dirpath)
os.chdir(dirpath)
# Viz first
writefile("file1.txt", "file1.")
writefile("file2.txt", "file2..")
call("mod -t tag -t tag1 file1.txt")
call("mod -t tag -t tag2 file2.txt")
call("change-tag tag1 tag11 --dry-run -o tmp")
assert Path("tmp").read_text() == "# DRY RUN\nfile1.txt\n"
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert set(note1.data.tags) == {"tag", "tag1"}
assert set(note2.data.tags) == {"tag", "tag2"}
call("change-tag tag1 tag11 -o tmp -p file2.txt")
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert set(note1.data.tags) == {"tag", "tag1"}
assert set(note2.data.tags) == {"tag", "tag2"}
call(r"change-tag tag1 tag11 tag\ 1 -o tmp")
assert Path("tmp").read_text() == "file1.txt\n"
note1 = Notefile("file1.txt").read()
note2 = Notefile("file2.txt").read()
assert set(note1.data.tags) == {"tag", "tag11", "tag 1"}
assert set(note2.data.tags) == {"tag", "tag2"}
os.chdir(TESTDIR)
def test_find_exclusions():
"""
Test all of the find exclusions that play into search, grep, query, and tags
"""
os.chdir(TESTDIR)
dirpath = TESTDIR / "find"
cleanmkdir(dirpath)
os.chdir(dirpath)
files = {
"file1.txt",
"sub/file2.txt",
"sub/file3.exc",
"sub/exd/file4.txt",
"exd/file5.txt",
"dup/file1.txt",
"endxd",
}
for i, file in enumerate(files):
file = Path(file)
file.parent.mkdir(exist_ok=True, parents=True)
file.write_text(f"{file}")
note = Notefile(file).read()
note.add_note(f"this is a note for {file}")
note.modify_tags(add="tag1").modify_tags((f"tag_{i}", "tag2"))
note.write()
assert {n.filename for n in notefile.find()} == files
call("find -o tmp")
assert readout("tmp") == files
# Single exclusion
f = {
"dup/file1.txt",
"endxd",
"exd/file5.txt",
"file1.txt",
"sub/exd/file4.txt",
"sub/file2.txt",
}
assert {n.filename for n in notefile.find(excludes="*.exc")} == f
assert {n.filename for n in notefile.find(path="sub", excludes="*.exc")} == {
"sub/exd/file4.txt",
"sub/file2.txt",
}
assert {n.filename for n in notefile.find(path=Path("sub"), excludes="*.exc")} == {
"sub/exd/file4.txt",
"sub/file2.txt",
}
call('find --exclude "*.exc" -o tmp')
assert readout("tmp") == f
# Single exclusion with dir
call('find --exclude "*xd" -o tmp')
assert readout("tmp") == {
"sub/file3.exc",
"file1.txt",
"sub/file2.txt",
"dup/file1.txt",
}
call('find --exclude "*xd/" -o tmp')
assert readout("tmp") == {
"endxd",
"sub/file3.exc",
"file1.txt",
"sub/file2.txt",
"dup/file1.txt",
}
# Match case
call('find --exclude "*.TXT" -o tmp')
assert readout("tmp") == {"sub/file3.exc", "endxd"}
call('find --exclude "*.TXT" -o tmp --match-exclude-case ')
assert readout("tmp") == files
# Test path
call("find -p sub -o tmp")
assert readout("tmp") == {"sub/file3.exc", "sub/file2.txt", "sub/exd/file4.txt"}
# max-depth
call("find --max-depth 0 -o tmp")
assert readout("tmp") == {"endxd", "file1.txt"}
# test links. Add one now
os.symlink("dup/file1.txt", "link1.lnk")
Notefile("link1.lnk").read().write() # Make the links
call('find --exclude "*.txt" -o tmp')
assert readout("tmp") == {"link1.lnk", "endxd", "sub/file3.exc"}
call('find --exclude "*.txt" -o tmp')
assert readout("tmp") == {"link1.lnk", "endxd", "sub/file3.exc"}
call('find --exclude "*.txt" --exclude-links -o tmp')
assert readout("tmp") == {"endxd", "sub/file3.exc"}
os.chdir(TESTDIR)
def test_outputs_export():
os.chdir(TESTDIR)
dirpath = TESTDIR / "outputs"
cleanmkdir(dirpath)
os.chdir(dirpath)
files = {"file1.txt", "sub/file1.txt", "sub2/file3.exc"}
for i, file in enumerate(sorted(files)):
file = Path(file)
file.parent.mkdir(exist_ok=True, parents=True)
file.write_text(f"{file}")
note = Notefile(file).read()
note.add_note(f"this is a note for {file}")
note.modify_tags(add=("tag1", f"tag_{i}"))
note.write()
## Test outputs
call("find -0 -o tmp")
with open("tmp", "rb") as f:
dat = f.read()
assert b"\n" not in dat
assert b"\x00" in dat
call("find --tag-mode -o tmp")
assert set(readtags("tmp")) == {"tag_1", "tag1", "tag_0", "tag_2"}
# Other tag modes like --tag-counts and --tag-count-order are in test_search()
## export
for format in ["yaml", "json", "jsonl"]:
call(f"export -o tmp --export-format {format}")
if format == "yaml":
with open("tmp") as f:
export = notefile.nfyaml.load_yaml(f.read())
elif format == "json":
# Explicitly check that json can load it
with open("tmp") as f:
export = json.load(f)
assert export.pop("__comment", False)
else:
with open("tmp") as fp:
export = [json.loads(line) for line in fp]
comment = export.pop(0)
assert comment.pop("__comment", False)
export0, export = export, {}
export.update(comment)
export["notes"] = {}
for line in export0:
export["notes"][line.pop("__filename")] = line
assert set(export.keys()) == {"notefile version", "notes", "description", "time"}
assert set(export["notes"]) == {"sub/file1.txt", "sub2/file3.exc", "file1.txt"}
tags = set()
for data in export["notes"].values():
tags.update(data["tags"])
assert tags == {"tag1", "tag_0", "tag_2", "tag_1"}
## symlinks
call("find --symlink links")
links = {}
for link in os.listdir("links"):
links[link] = os.readlink(f"links/{link}")
assert links == {
"file1.txt": "../file1.txt",
"file1.1.txt": "../sub/file1.txt",
"file3.exc": "../sub2/file3.exc",
}
# Symlinks with tags
shutil.rmtree("links")
o, e = call("find --tag-mode --symlink links --debug", capture=True)
# There is a duplicate. Check it works right
assert e == "WARNING: links/tag1/file1.txt exists. Changing to links/tag1/file1.1.txt\n"
# Check them. Note that the ordering may not be deterministic of the repeat so handle
# that properly
links = {str(p): os.readlink(p) for p in Path("links").rglob("*") if p.is_file()}
file1 = links.pop("links/tag1/file1.txt") # Will error if not in there
file1p1 = links.pop("links/tag1/file1.1.txt")
assert {file1, file1p1} == {
"../../sub/file1.txt",
"../../file1.txt",
} # use set to ignore order
assert links == {
"links/tag1/file3.exc": "../../sub2/file3.exc",
"links/tag_0/file1.txt": "../../file1.txt",
"links/tag_1/file1.txt": "../../sub/file1.txt",
"links/tag_2/file3.exc": "../../sub2/file3.exc",
}
os.chdir(dirpath)
def test_search():
"""
Test the different queries and searches. No need to test exclusions, etc
as they are tested as part of find
"""
os.chdir(TESTDIR)
dirpath = TESTDIR / "search"
cleanmkdir(dirpath)
os.chdir(dirpath)
writefile("file1.txt", "file1")
call('mod file1.txt -t xcommon -t file1 -n"match me or you"')
writefile("file2.txt", "file2")
call('mod file2.txt -t xcommon -t other -n"match you"')
writefile("file3.txt", "file2")
call('mod file3.txt -t xcommon -t third -t other -n"what about me"')
# Test a few greps and also query and search
call("grep match -o tmp")
assert readout("tmp") == {"file1.txt", "file2.txt"}
call("search --grep match -o tmp")
assert readout("tmp") == {"file1.txt", "file2.txt"}
call("query 'g(\"match\")' -o tmp")
assert readout("tmp") == {"file1.txt", "file2.txt"}
call("search --query 'g(\"match\")' -o tmp")
assert readout("tmp") == {"file1.txt", "file2.txt"}
# Regex
call('grep "wh.*t" -o tmp')
assert readout("tmp") == {"file3.txt"}
# Multiple
call("grep me you -o tmp")
assert readout("tmp") == {"file1.txt", "file2.txt", "file3.txt"}
call("grep me you --all -o tmp")
assert readout("tmp") == {"file1.txt"}
## --full-note tests. Look for 'xcommon' since it'll just be in the tags
call("grep xcommon -o tmpnew")
assert not os.path.exists("tmpnew") # Make sure it's not there
call("grep --full-note xcommon -o tmp")
assert readout("tmp") == {"file1.txt", "file2.txt", "file3.txt"}
call("""query --full-note "g('xcommon')" -o tmp""")
assert readout("tmp") == {"file1.txt", "file2.txt", "file3.txt"}
call("""query "'xcommon' in text" -o tmp""")
assert readout("tmp") == {"file1.txt", "file2.txt", "file3.txt"}
## Test grep with regex
writefile("file4.txt", "wt", "FILE 4")
writefile("file5.txt", "wt", "FILE 5")
writefile("file6.txt", "wt", "FILE 6")
writefile("file7.txt", "wt", "FILE 7")
call('mod file4.txt -n "this is a te.*st"')
call('mod file5.txt -n "This is a teblablabast"')
call('mod file6.txt -n "These are their words"')
call('mod file7.txt -n "these are the words"')
call('grep -o tmp "te.*st"')
assert readout("tmp") == {"file4.txt", "file5.txt"}
call("""search -o tmp --query 'g("te.*st")'""")
assert readout("tmp") == {"file4.txt", "file5.txt"}
call('grep -o tmp --fixed-strings "te.*st"')
assert readout("tmp") == {"file4.txt"}
call("""query -o tmp --fixed-strings 'g("te.*st")' """) # Make sure the flags work in query
assert readout("tmp") == {"file4.txt"}
# Or passing kwargs including override
call("""query -o tmp 'g("te.*st",fixed_strings=True)'""")
assert readout("tmp") == {"file4.txt"}
call("""query -o tmp --fixed-strings 'g("te.*st",fixed_strings=False)' """)
assert readout("tmp") == {"file4.txt", "file5.txt"}
call("grep -o tmp the")
assert readout("tmp") == {"file6.txt", "file7.txt"}
call("grep -o tmp --full-word the")
assert readout("tmp") == {"file7.txt"}
call("query -o tmp --full-word 'g(\"the\")' ")
assert readout("tmp") == {"file7.txt"}
# Multiple in query
# any
call("""query "g('the','words')" -o tmp""") # default
assert readout("tmp") == {"file6.txt", "file7.txt"}
call("""query "g('the','words')" --full-word -o tmp""") # Baseline for below
assert readout("tmp") == {"file6.txt", "file7.txt"}
call("""query "g('the','words',match_any=True)" --full-word --all -o tmp""") # kw overides CLI
assert readout("tmp") == {"file6.txt", "file7.txt"}
call("""query "gany('the','words')" --full-word --all -o tmp""") # gany overides CLI
assert readout("tmp") == {"file6.txt", "file7.txt"}
# all
call("""query "g('the','words')" --all --full-word -o tmp""") # cli --all
assert readout("tmp") == {"file7.txt"}
call("""query "g('the','words',match_any=False)" --full-word -o tmp""") # kw all
assert readout("tmp") == {"file7.txt"}
call("""query "gall('the','words')" --full-word -o tmp""") # implied with gall
assert readout("tmp") == {"file7.txt"}
call(
"""query "gall('the','words',match_any=True)" --full-word -o tmp"""
) # implied with gall but again overwritten with kw
assert readout("tmp") == {"file6.txt", "file7.txt"}
## Tags
call("tags -o tmp")
assert readtags("tmp") == {
"xcommon": {"file2.txt", "file1.txt", "file3.txt"},
"file1": {"file1.txt"},
"other": {"file2.txt", "file3.txt"},
"third": {"file3.txt"},
}
call("search --tag-mode -o tmp1") # search tag mode calls
call("find --tag-mode -o tmp2")
assert readtags("tmp") == readtags("tmp1") == readtags("tmp2")
call("tags third other -o tmp")
call("""query "t('third') or t('other')" --tag-mode -o tmp2""")
call("""search --query "t('third')" --query "t('other')" --tag-mode -o tmp3""")
assert (
readtags("tmp")
== readtags("tmp2")
== readtags("tmp3")
== {
"xcommon": {"file2.txt", "file3.txt"},
"other": {"file2.txt", "file3.txt"},
"third": {"file3.txt"},
}
)
call("""query "t('third') or t('other')" -o tmp""")
assert readout("tmp") == {"file2.txt", "file3.txt"}
call("tags --tag-counts -o tmp")
readtags("tmp") == {"xcommon": 3, "file1": 1, "other": 2, "third": 1}
# Multiple (all) with some mix and match
call("tags --tag-all third other -o tmp")
call("""query "t('third') and t('other')" --tag-mode -o tmp2""")
call("""search --query "t('third')" --query "t('other')" --all --tag-mode -o tmp3""")
call("""search --tag other --query 't("third")' --all --tag-mode -o tmp4""")
assert (
readtags("tmp")
== readtags("tmp2")
== readtags("tmp3")
== {"xcommon": {"file3.txt"}, "other": {"file3.txt"}, "third": {"file3.txt"}}
)
# Ordering
call("tags -o tmp")
assert list(readtags("tmp")) == ["file1", "other", "third", "xcommon"]
call("tags --tag-count-order -o tmp")
call("tags --tag-count-order --tag-counts -o tmp2")
call("""search --query "t('third')" --query "t('other')" --all --tag-mode -o tmp3""")
assert set(readtags("tmp")) == set(readtags("tmp2")) == {"xcommon", "other", "file1", "third"}