-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathtest_validation.py
More file actions
984 lines (840 loc) · 35.4 KB
/
Copy pathtest_validation.py
File metadata and controls
984 lines (840 loc) · 35.4 KB
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
import os.path
import shutil
import warnings
import pytest
from base import BaseTest
from datashuttle import quick_validate_project
from datashuttle.utils import formatting, validation
from datashuttle.utils.custom_exceptions import NeuroBlueprintError
# -----------------------------------------------------------------------------
# Inconsistent sub or ses value lengths
# -----------------------------------------------------------------------------
class TestValidation(BaseTest):
@pytest.mark.parametrize(
"sub_name",
["sub-001", "sub-999_@DATE@", "sub-001_random-tag_another-tag"],
)
@pytest.mark.parametrize(
"bad_sub_name",
[
"sub-3",
"sub-04",
"sub-0004",
"sub-07_@DATE@",
"sub-1321",
"sub-22",
"sub-234234453_@DATETIME@",
],
)
def test_warn_on_inconsistent_sub_value_lengths(
self, project, sub_name, bad_sub_name
):
"""
This test checks that inconsistent sub value lengths are properly
detected across the project. This is performed with an assortment
of possible filenames and leading zero conflicts.
These conflicts are detected across the project (i.e. if you have
sub-03 in remote and sub-004 in local, a warning should be shown).
Therefore this function tests every combination of conflict across
local and central).
Note SSH version is not tested, but the core functionality detecting
inconsistent leading zeros is agnostic to SSH, and SSH file searching
is tested elsewhere.
"""
# First make conflicting leading zero subject names in the local repo
sub_name = formatting.format_names([sub_name], "sub")[0]
bad_sub_name = formatting.format_names([bad_sub_name], "sub")[0]
os.makedirs(project.cfg["local_path"] / "rawdata" / sub_name)
os.makedirs(project.cfg["local_path"] / "rawdata" / bad_sub_name)
self.check_inconsistent_sub_or_ses_value_length_warning(
project, include_central=False
)
# Now, have conflicting subject names,
# but one in local and one in central
new_central_path = (
project.cfg["local_path"].parent / "central" / project.project_name
)
os.makedirs(new_central_path, exist_ok=True)
project.update_config_file(central_path=new_central_path)
os.makedirs(project.cfg["central_path"] / "rawdata" / bad_sub_name)
shutil.rmtree(project.cfg["local_path"] / "rawdata" / bad_sub_name)
self.check_inconsistent_sub_or_ses_value_length_warning(project)
# Have conflicting subject names both in central.
shutil.rmtree(project.cfg["local_path"] / "rawdata" / sub_name)
os.makedirs(project.cfg["central_path"] / "rawdata" / sub_name)
self.check_inconsistent_sub_or_ses_value_length_warning(project)
@pytest.mark.parametrize(
"ses_name",
["ses-01", "ses-99_@DATE@", "ses-01_random-tag_another-tag"],
)
@pytest.mark.parametrize(
"bad_ses_name",
[
"ses-3",
"ses-004",
"ses-0004",
"ses-007_@DATE@",
"ses-1453_@DATETIME@",
"ses-234234234",
],
)
def test_warn_on_inconsistent_ses_value_lengths(
self, project, ses_name, bad_ses_name
):
"""
This function is exactly the same as
`test_warn_on_inconsistent_sub_value_lengths()` but operates at the
session level. This is extreme code duplication, but
factoring the main logic out got very messy and hard to follow.
"""
ses_name = formatting.format_names([ses_name], "ses")[0]
bad_ses_name = formatting.format_names([bad_ses_name], "ses")[0]
# Have conflicting session names (in different subject directories)
# on the local filesystem
os.makedirs(
project.cfg["local_path"] / "rawdata" / "sub-001" / ses_name
)
os.makedirs(
project.cfg["local_path"] / "rawdata" / "sub-002" / bad_ses_name
)
self.check_inconsistent_sub_or_ses_value_length_warning(
project, include_central=False
)
# Now, have conflicting session names (in different subject
# directories) where one subject directory is local and the
# other is central.
new_central_path = (
project.cfg["local_path"].parent / "central" / project.project_name
)
os.makedirs(new_central_path, exist_ok=True)
project.update_config_file(central_path=new_central_path)
os.makedirs(
project.cfg["central_path"] / "rawdata" / "sub-001" / bad_ses_name
)
shutil.rmtree(project.cfg["local_path"] / "rawdata" / "sub-002")
self.check_inconsistent_sub_or_ses_value_length_warning(project)
# Test the case where conflicting session names are both on central.
shutil.rmtree(project.cfg["local_path"] / "rawdata" / "sub-001")
os.makedirs(
project.cfg["central_path"] / "rawdata" / "sub-001" / ses_name
)
self.check_inconsistent_sub_or_ses_value_length_warning(project)
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_warn_on_inconsistent_sub_and_ses_value_lengths(self, project):
"""
Test that warning is shown for both subject and session when
inconsistent zeros are found in both.
"""
os.makedirs(
project.cfg["local_path"] / "rawdata" / "sub-001" / "ses-01"
)
os.makedirs(
project.cfg["local_path"] / "rawdata" / "sub-03" / "ses-002"
)
self.check_inconsistent_sub_or_ses_value_length_warning(
project, include_central=False
)
self.check_inconsistent_sub_or_ses_value_length_warning(
project, warn_idx=1, include_central=False
)
def check_inconsistent_sub_or_ses_value_length_warning(
self, project, warn_idx=0, include_central=True
):
""""""
with pytest.warns(UserWarning) as w:
project.validate_project(
"rawdata", display_mode="warn", include_central=include_central
)
assert "VALUE_LENGTH" in str(w[warn_idx].message)
# -------------------------------------------------------------------------
# Test duplicates when making folders
# -------------------------------------------------------------------------
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_duplicate_ses_or_sub_key_value_pair(self, project):
"""
Test the check that if a duplicate key is attempt to be made
when making a folder e.g. sub-001 exists, then make sub-001_id-123.
After this check, make a folder that can be made (e.g. sub-003)
just to make sure it does not raise error.
Then, within an already made subject, try and make a session
with a ses that already exists and check.
"""
# Check trying to make sub only
subs = ["sub-001_id-123", "sub-002_id-124"]
project.create_folders("rawdata", subs)
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", "sub-001_id-125")
assert "DUPLICATE_NAME" in str(e.value)
project.create_folders("rawdata", "sub-003")
# check try and make ses within a sub
sessions = ["ses-001_date-20241105", "ses-002_date-20241106"]
project.create_folders("rawdata", subs, sessions)
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders(
"rawdata", "sub-001_id-123", "ses-002_date-20241107"
)
assert "DUPLICATE_NAME" in str(e.value)
project.create_folders("rawdata", "sub-001_id-123", "ses-003")
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_duplicate_sub_and_ses_num_leading_zeros(self, project):
"""
Very similar to test_duplicate_ses_or_sub_key_value_pair(),
but explicitly check that error is raised if the same
number is used with different number of leading zeros.
"""
project.create_folders("rawdata", "sub-1")
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", "sub-001")
assert "VALUE_LENGTH" in str(e.value)
project.create_folders("rawdata", "sub-1", "ses-3")
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", "sub-1", "ses-003")
assert "DUPLICATE_NAME" in str(e.value)
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_duplicate_sub_when_creating_session(self, project):
"""
Check the unique case that a duplicate subject is
introduced when the session is made.
"""
project.create_folders("rawdata", "sub-001")
for bad_sub_name in ["sub-001_@DATE@", "sub-001_extra-key"]:
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", bad_sub_name, "ses-001")
assert "DUPLICATE_NAME" in str(e.value)
project.create_folders("rawdata", "sub-001", "ses-001")
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders(
"rawdata", "sub-001", "ses-001_extra-key", "behav"
)
assert "DUPLICATE_NAME" in str(e.value)
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders(
"rawdata", "sub-001_extra-key", "ses-001", "behav"
)
assert "DUPLICATE_NAME" in str(e.value)
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders(
"rawdata", "sub-001_extra-key", "ses-001_@DATE@", "behav"
)
assert "DUPLICATE_NAME" in str(e.value)
project.create_folders("rawdata", "sub-001", "ses-001", "behav")
project.create_folders("rawdata", "sub-001", ["ses-001", "ses-002"])
# Finally check that in a list of subjects, only the correct subject
# with duplicate session is caught.
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders(
"rawdata", ["sub-001", "sub-002"], "ses-002_@DATE@", "ephys"
)
assert "DUPLICATE_NAME" in str(e.value)
def test_duplicate_ses_across_subjects(self, project):
"""
Quick test that duplicate session folders only raise
an error when they are in the same subject.
"""
project.create_folders("rawdata", "sub-001", "ses-001")
project.create_folders("rawdata", "sub-002", "ses-001_@DATE@")
project.validate_project(
"rawdata", display_mode="error", include_central=False
)
with pytest.raises(NeuroBlueprintError):
project.create_folders("rawdata", "sub-001", "ses-001_@DATE@")
# -------------------------------------------------------------------------
# Bad underscore order
# -------------------------------------------------------------------------
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_invalid_sub_and_ses_name(self, project):
"""
This is a slightly weird case, the name is successfully
prefixed as 'sub-sub_100` but when the value if `sub-` is
extracted, it is also "sub" and so an error is raised.
"""
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", "sub_100")
assert (
"BAD_VALUE: The value for prefix sub in name sub-sub_100 is not an integer."
== str(e.value)
)
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", "sub-001", "ses_100")
assert (
"BAD_VALUE: The value for prefix ses in name ses-ses_100 is not an integer."
== str(e.value)
)
# -------------------------------------------------------------------------
# Test validate project
# -------------------------------------------------------------------------
def test_validate_project(self, project):
"""
Test the `validate_project` function over all it's arguments.
Note not every validation case is tested exhaustively, these
are tested in `test_validation_unit.py` elsewhere here.
"""
for sub in ["sub-001", "sub-002"]:
os.makedirs(
project.cfg["central_path"] / "rawdata" / sub, exist_ok=True
)
project.create_folders("rawdata", ["sub-002_id-11"])
# The bad sub name is not caught when testing locally only.
project.validate_project(
"rawdata", display_mode="error", include_central=False
)
project.create_folders("rawdata", "sub-001")
# Now the bad sub is caught as we check against central also.
with pytest.raises(NeuroBlueprintError) as e:
project.validate_project(
"rawdata", display_mode="error", include_central=True
)
assert "DUPLICATE_NAME" in str(e.value)
assert "Path" in str(e.value) # cursory check Path is returned
# Now check warnings are shown when there are multiple validation
# issues across local and central.
os.makedirs(
project.cfg["central_path"] / "rawdata" / "sub-3", exist_ok=True
)
with pytest.warns(UserWarning) as w:
project.validate_project(
"rawdata", display_mode="warn", include_central=True
)
assert "DUPLICATE_NAME" in str(w[0].message)
assert "DUPLICATE_NAME" in str(w[1].message)
assert "VALUE_LENGTH" in str(w[2].message)
# Finally, check that some bad sessions (ses-01) are caught.
project.create_folders(
"rawdata", "sub-001", ["ses-0001_id-11", "ses-0002"]
)
os.makedirs(
project.cfg["central_path"]
/ "rawdata"
/ "sub-004"
/ "ses-01_id-11",
exist_ok=True,
)
with pytest.warns(UserWarning) as w:
project.validate_project(
"rawdata", display_mode="warn", include_central=True
)
assert (
"VALUE_LENGTH: Inconsistent value lengths for the prefix: sub"
in str(w[2].message)
)
assert (
"VALUE_LENGTH: Inconsistent value lengths for the prefix: ses"
in str(w[3].message)
)
assert "Path" not in str(
w[3].message
) # no path in VALUE_LENGTH errors
@pytest.mark.parametrize("prefix", ["sub", "ses"])
def test_validate_project_returned_list(self, project, prefix):
""" """
bad_names = [
f"{prefix}-001",
f"{prefix}-001_@DATE@",
f"{prefix}_002_id_1",
f"{prefix}-02",
f"{prefix}-002_date-1",
]
if prefix == "sub":
project.create_folders(
"rawdata", bad_names, bypass_validation=True
)
else:
project.create_folders(
"rawdata", "sub-001", bad_names, bypass_validation=True
)
warnings.filterwarnings("ignore")
error_messages = project.validate_project(
"rawdata", "warn", include_central=False
)
warnings.filterwarnings("default")
concat_error = "".join(error_messages)
assert "DATETIME" in concat_error
assert "BAD_VALUE" in concat_error
assert "DUPLICATE_NAME" in concat_error
assert "VALUE_LENGTH" in concat_error
def test_output_paths_are_valid(self, project):
""" """
sub_name = "sub-001x"
ses_name = "ses-001x"
project.create_folders(
"rawdata", sub_name, ses_name, bypass_validation=True
)
warnings.filterwarnings("ignore")
error_messages = project.validate_project(
"rawdata", "warn", include_central=False
)
warnings.filterwarnings("default")
sub_path = error_messages[0].split("Path: ")[-1]
ses_path = error_messages[1].split("Path: ")[-1]
assert (
sub_path
== (project.cfg["local_path"] / "rawdata" / sub_name).as_posix()
)
assert (
ses_path
== (
project.cfg["local_path"] / "rawdata" / sub_name / ses_name
).as_posix()
)
# -------------------------------------------------------------------------
# Test validate names against project
# -------------------------------------------------------------------------
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_validate_names_against_project_with_bad_existing_names(
self, project
):
"""
When using `validate_names_against_project()` there are
three possible classes of error:
1) error in the passed names.
2) an error already exists in the project.
3) an error in the 'interaction' between names and project (e.g.
all names are okay, all project names are okay, but new names duplicate
an existing name).
`validate_names_against_project()` is only interested in catching 1) and 2)
but not reporting errors for names that already exist in the project.
This checks that the validation of names is not affected by existing
bad names in the project. The only case where this matters is if
within the project, the subject or session value length is inconsistent.
Then we don't know what to validate the names against and an
error indicating this specific problem is raised.
"""
# Make some bad project names. We will check these don't interfere
# with the validation of the passed names.
project.create_folders(
"rawdata", "sub-abc", "ses-abc", bypass_validation=True
)
# Check the bad names do not interference with an example
# bad validation within the names list.
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg, "rawdata", ["sab-001"], include_central=False
)
assert (
"MISSING_PREFIX: The prefix sub was not found in the name: sab-001"
in str(e.value)
)
# Now check the bad names don't interfere with
# inconsistent value lengths or duplicate names.
project.create_folders("rawdata", "sub-004", "ses-001")
# Inconsistent value lengths
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg, "rawdata", ["sub-0002"], include_central=False
)
assert (
"VALUE_LENGTH: Inconsistent value lengths for the prefix: sub"
in str(e.value)
)
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
["sub-004"],
["ses-0002"],
include_central=False,
)
assert (
"VALUE_LENGTH: Inconsistent value lengths for the prefix: ses"
in str(e.value)
)
# Duplicate names
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
["sub-004_id-123"],
include_central=False,
)
assert (
"DUPLICATE_NAME: The prefix for sub-004_id-123 duplicates the name: sub-004"
in str(e.value)
)
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
["sub-004"],
["ses-001_date-121212"],
include_central=False,
)
assert (
"DUPLICATE_NAME: The prefix for ses-001_date-121212 duplicates the name: ses-001"
in str(e.value)
)
assert "Path" in str(e.value) # quick check Path is included
# Finally make folders within the existing project that have
# inconsistent value lengths, and check the correct error is raised.
# First for session
project.create_folders(
"rawdata",
["sub-001"],
["ses-01", "ses-002"],
bypass_validation=True,
)
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
["sub-001"],
["ses-03"],
include_central=False,
)
assert (
"Cannot check names for inconsistent value lengths because the session value"
in str(e.value)
)
# Then subject
project.create_folders("rawdata", ["sub-02"], bypass_validation=True)
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
["sub-003"],
include_central=False,
display_mode="error",
)
assert (
"Cannot check names for inconsistent value lengths because the subject value"
in str(e.value)
)
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_validate_names_against_project_interactions(self, project):
"""
Check that interactions between the list of names and existing
project are caught. This includes duplicate subject / session
names as well as inconsistent subject / session value lengths.
"""
project.create_folders(
"rawdata", ["sub-1_id-abc", "sub-2_id-b", "sub-3_id-c"]
)
# Check an exact match passes
sub_names = ["sub-1_id-abc"]
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
include_central=False,
display_mode="error",
)
# Now check a clashing subject (sub-1) throws an error
sub_names = ["sub-2_id-b", "sub-1_id-11", "sub-3_id-c"]
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
include_central=False,
display_mode="error",
)
assert "DUPLICATE_NAME" in str(e.value)
# Now check multiple different types of error are warned about
sub_names = ["sub-002", "sub-1_id-11", "sub-3_id-c", "sub-4"]
with pytest.warns(UserWarning) as w:
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
include_central=False,
display_mode="warn",
)
# this warning arises from inconsistent value lengths within the
# passed sub_names
assert "VALUE_LENGTH" in str(w[0].message)
# This warning arises from inconstant value lengths between
# sub_names and the rest of the project. This behaviour could be optimisHed.
assert "VALUE_LENGTH" in str(w[1].message)
assert "DUPLICATE_NAME" in str(w[2].message)
assert "DUPLICATE_NAME" in str(w[3].message)
if project.is_local_project():
return
# Now make some new paths on central. Pass a bad new subject name
# (sub-4) and check no error is raised when local_only is `True`
# but the error is discovered when `False`.
os.makedirs(
project.cfg["central_path"] / "rawdata" / "sub-4_date-20231215"
)
sub_names = ["sub-4", "sub-5"]
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
include_central=False,
display_mode="error",
)
with pytest.raises(NeuroBlueprintError) as e:
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
include_central=True,
display_mode="error",
)
assert "DUPLICATE_NAME" in str(e.value)
# Now, make some sessions locally and on central. Check that
# the correct errors are warned when we check at the subject level.
# Now that session checks are performed per-subject.
os.makedirs(
project.cfg["central_path"]
/ "rawdata"
/ "sub-4_date-20231215"
/ "ses-003"
)
project.create_folders("rawdata", "sub-2_id-b", ["ses-001", "ses-002"])
# Check no error is raised for exact match.
sub_names = ["sub-1_id-abc", "sub-2_id-b", "sub-4_date-20231215"]
ses_names = ["ses-001", "ses-002"]
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
ses_names,
include_central=True,
display_mode="error",
)
# ses-002 is bad for sub-2, ses-003 is bad for sub-4
sub_names = ["sub-1_id-abc", "sub-2_id-b", "sub-4_date-20231215"]
ses_names = ["ses-002_id-11", "ses-003_id-random"]
with pytest.warns(UserWarning) as w:
validation.validate_names_against_project(
project.cfg,
"rawdata",
sub_names,
ses_names,
include_central=True,
display_mode="warn",
)
assert "DUPLICATE_NAME" in str(w[0].message)
assert "DUPLICATE_NAME" in str(w[1].message)
@pytest.mark.parametrize("project", ["local", "full"], indirect=True)
def test_tags_in_name_templates_pass_validation(self, project):
"""
It is useful to allow tags in the `name_templates` as it means
auto-completion in the TUI can use tags for automatic name
generation. Because all subject and session names are
fully formatted (e.g. @DATE@ converted to actual dates)
prior to validation, the regexp must also have @DATE@
and other tags with their regexp equivalent. Check
this behaviour here.
"""
name_templates = {
"on": True,
"sub": r"sub-\d\d_@DATE@",
"ses": r"ses-\d\d\d@DATETIME@",
}
project.set_name_templates(name_templates)
# Standard behaviour, should not raise
project.create_folders(
"rawdata",
"sub-01_date-20240101",
"ses-001_datetime-20240101T142323",
)
# added tags, should not raise
project.create_folders("rawdata", "sub-02@DATE@", "ses-001_@DATETIME@")
# break the name template validation, for sub, should raise
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders("rawdata", "sub-03_datex-202401")
assert "TEMPLATE: The name: sub-03_datex-202401" in str(e.value)
# break the name template validation, for ses, should raise
with pytest.raises(NeuroBlueprintError) as e:
project.create_folders(
"rawdata", "sub-03_date-20240101", "ses-001_datex-20241212"
)
assert "TEMPLATE: The name: ses-001_datex-20241212" in str(e.value)
# Do a quick test for time
name_templates["sub"] = r"sub-\d\d_@TIME@"
project.set_name_templates(name_templates)
# use time tag, should not raise
project.create_folders(
"rawdata",
"sub-03@TIME@",
)
# use misspelled time tag, should raise
with pytest.raises(NeuroBlueprintError):
project.create_folders("rawdata", "sub-03_mime_010101")
assert "TEMPLATE: The name: ses-001_datex-20241212" in str(e.value)
def test_name_templates_validate_project(self, project):
# set up name templates
name_templates = {
"on": True,
"sub": r"sub-\d\d_id-\d.?",
"ses": r"ses-\d\d_id-\d.?",
}
project.set_name_templates(name_templates)
# Create names that match, check this does not error
project.create_folders(
"rawdata", "sub-01_id-2b", "ses-01_id-1a", bypass_validation=True
)
project.validate_project("rawdata", "error", include_central=False)
# Create names that don't match, check they error
project.create_folders(
"rawdata", "sub-02_id-a1", "ses-02_id-aa", bypass_validation=True
)
with pytest.warns(UserWarning) as w:
project.validate_project("rawdata", "warn", include_central=False)
assert (
"TEMPLATE: The name: sub-02_id-a1 does not match the template: sub-\\d\\d_id-\\d.?"
in str(w[0].message)
)
assert (
"TEMPLATE: The name: ses-02_id-aa does not match the template: ses-\\d\\d_id-\\d.?"
in str(w[1].message)
)
# ----------------------------------------------------------------------------------
# Test Quick Validation Function
# ----------------------------------------------------------------------------------
def test_quick_validation(self, mocker, project):
""" """
project.create_folders("rawdata", "sub-1")
os.makedirs(project.cfg["local_path"] / "rawdata" / "sub-02")
project.create_folders("derivatives", "sub-1")
os.makedirs(project.cfg["local_path"] / "derivatives" / "sub-02")
with pytest.warns(UserWarning) as w:
quick_validate_project(
project.get_local_path(),
display_mode="warn",
top_level_folder=None,
)
assert "VALUE_LENGTH" in str(w[0].message)
assert "VALUE_LENGTH" in str(w[1].message)
assert len(w) == 2
# For good measure, monkeypatch and change all defaults,
# ensuring they are propagated to the validate_project
# function (which is tested above)
import datashuttle
spy_validate_func = mocker.spy(
datashuttle.datashuttle_functions.validation, "validate_project"
)
quick_validate_project(
project.get_local_path(),
display_mode="print",
top_level_folder="derivatives",
name_templates={"on": False},
)
_, kwargs = spy_validate_func.call_args_list[0]
assert kwargs["display_mode"] == "print"
assert kwargs["top_level_folder_list"] == ["derivatives"]
assert kwargs["name_templates"] == {"on": False}
def test_quick_validation_top_level_folder(self, project):
"""
Test that errors are raised as expected on
bad project path input.
"""
with pytest.raises(FileNotFoundError) as e:
quick_validate_project(
project.get_local_path() / "does not exist",
display_mode="error",
)
assert (
"Cannot perform validation. No file or folder found at `project_path`:"
in str(e.value)
)
# ----------------------------------------------------------------------------------
# Test Strict Validation and High-Level Checks
# ----------------------------------------------------------------------------------
@pytest.mark.parametrize("top_level_folder", ["rawdata", "derivatives"])
def test_strict_mode_validation(self, project, top_level_folder):
""" """
project.create_folders(
top_level_folder,
["sub-001", "sub-002"],
["ses-001", "ses-002"],
["ephys", "behav"],
)
project.validate_project(
top_level_folder, "error", include_central=False, strict_mode=True
)
os.makedirs(
project.cfg["local_path"] / top_level_folder / "bad_sub_name"
)
os.makedirs(
project.cfg["local_path"]
/ top_level_folder
/ "sub-001"
/ "bad_sesname"
)
os.makedirs(
project.cfg["local_path"]
/ top_level_folder
/ "sub-002"
/ "ses-002"
/ "bad_datatype_name"
)
with pytest.warns(UserWarning) as w:
project.validate_project(
top_level_folder,
"warn",
include_central=False,
strict_mode=True,
)
assert (
"BAD_NAME: The name: bad_sub_name of type: sub is not valid"
in str(w[0].message)
)
assert (
"BAD_NAME: The name: bad_sesname of type: ses is not valid."
in str(w[1].message)
)
assert (
"DATATYPE: bad_datatype_name is not a valid datatype name."
in str(w[2].message)
)
assert len(w) == 3
with pytest.raises(ValueError) as e:
project.validate_project(
top_level_folder,
"warn",
include_central=True,
strict_mode=True,
)
assert (
"`strict_mode` is currently only available for `include_central=False`."
in str(e.value)
)
@pytest.mark.parametrize("top_level_folder", ["rawdata", "derivatives"])
def test_check_high_level_project_structure(
self, project, top_level_folder
):
"""
Check that local and central project names are properly formatted
and that
"""
with pytest.warns(UserWarning) as w:
project.validate_project(
top_level_folder, "warn", include_central=True
)
assert len(w) == 2
assert "TOP_LEVEL_FOLDER: The local project" in str(w[0].message)
assert "TOP_LEVEL_FOLDER: The central project" in str(w[1].message)
project.create_folders("rawdata", "sub-001")
with pytest.warns(UserWarning) as w:
project.validate_project(
top_level_folder, "warn", include_central=True
)
assert len(w) == 1
assert "TOP_LEVEL_FOLDER: The central project" in str(w[0].message)
# Should be fine now that both folders have rawdata or derivatives
os.makedirs(project.get_central_path() / "derivatives")
project.validate_project(
top_level_folder, "error", include_central=True
)
# Make a bad project name and check its caught
project.cfg["local_path"] = (
project.cfg["local_path"].parent / "bad@project@name@"
)
project.cfg["central_path"] = (
project.cfg["central_path"].parent / "bad@project@name@"
)
(project.cfg["local_path"] / "rawdata").mkdir(parents=True)
(project.cfg["central_path"] / "rawdata").mkdir(parents=True)
with pytest.warns(UserWarning) as w:
project.validate_project("rawdata", "warn", include_central=True)
assert len(w) == 2
assert (
"PROJECT_NAME: The local project name folder bad@project@name@"
in str(w[0].message)
)
assert (
"PROJECT_NAME: The central project name folder bad@project@name@"
in str(w[1].message)
)