/
test_datasets.py
2149 lines (1594 loc) · 87.1 KB
/
test_datasets.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
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test ``dataset`` command."""
import json
import os
import shutil
import textwrap
from pathlib import Path
import git
import pytest
from renku.cli import cli
from renku.core.commands.format.dataset_files import DATASET_FILES_COLUMNS, DATASET_FILES_FORMATS
from renku.core.commands.format.datasets import DATASETS_COLUMNS, DATASETS_FORMATS
from renku.core.commands.providers import DataverseProvider, ProviderFactory, ZenodoProvider
from renku.core.management.config import RENKU_HOME
from renku.core.management.repository import DEFAULT_DATA_DIR as DATA_DIR
from renku.core.models.dataset import Dataset
from renku.core.models.refs import LinkReference
from renku.core.utils.git import get_object_hash
from renku.core.utils.urls import get_slug
from tests.utils import assert_dataset_is_mutated, format_result_exception, write_and_commit_file
def test_datasets_create_clean(runner, project, client, load_dataset_with_injection):
"""Test creating a dataset in clean repository."""
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
dataset = load_dataset_with_injection("dataset", client)
assert isinstance(dataset, Dataset)
staged = client.repo.index.diff("HEAD")
for file_path in staged:
assert ".renku" not in file_path
untracked = client.repo.untracked_files
for file_path in untracked:
assert ".renku" not in file_path
def test_dataset_show(runner, client, subdirectory):
"""Test creating a dataset with metadata."""
metadata = {
"@id": "https://example.com/annotation1",
"@type": "https://schema.org/specialType",
"https://schema.org/specialProperty": "some_unique_value",
}
metadata_path = client.path / "metadata.json"
metadata_path.write_text(json.dumps(metadata))
result = runner.invoke(
cli,
[
"dataset",
"create",
"my-dataset",
"--title",
"Long Title",
"--description",
"# t1\n## t2\nsome description here",
"-c",
"John Doe <john.doe@mail.ch>",
"-c",
"John Smiths<john.smiths@mail.ch>",
"-k",
"keyword-1",
"-k",
"keyword-2",
"--metadata",
str(metadata_path),
],
)
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
result = runner.invoke(cli, ["dataset", "show", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "some description here" in result.output
assert "Long Title" in result.output
assert "keyword-1" in result.output
assert "keyword-2" in result.output
assert "Created: " in result.output
assert "Name: my-dataset" in result.output
assert "John Doe <john.doe@mail.ch>" in result.output
assert "some_unique_value" in result.output
assert "https://schema.org/specialProperty" in result.output
assert "https://example.com/annotation1" in result.output
assert "https://schema.org/specialType" in result.output
assert "##" not in result.output
def test_datasets_create_different_names(runner, client):
"""Test creating datasets with same title but different name."""
result = runner.invoke(cli, ["dataset", "create", "dataset-1", "--title", "title"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
result = runner.invoke(cli, ["dataset", "create", "dataset-2", "--title", "title"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
def test_datasets_create_with_same_name(runner, client):
"""Test creating datasets with same name."""
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 1 == result.exit_code
assert "Dataset exists: 'dataset'" in result.output
@pytest.mark.parametrize(
"name",
[
"any name /@#$!",
"name longer than 24 characters",
"semi valid-name",
"dataset/new",
"/dataset",
"dataset/",
"name ends in.lock",
],
)
def test_datasets_invalid_name(runner, client, name):
"""Test creating datasets with invalid name."""
result = runner.invoke(cli, ["dataset", "create", name])
assert 2 == result.exit_code
assert f'Dataset name "{name}" is not valid' in result.output
assert f'Hint: "{get_slug(name)}" is valid' in result.output
def test_datasets_create_dirty(runner, project, client, load_dataset_with_injection):
"""Test creating a dataset in dirty repository."""
# Create a file in root of the repository.
with (client.path / "a").open("w") as fp:
fp.write("a")
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
dataset = load_dataset_with_injection("dataset", client)
assert dataset
staged = client.repo.index.diff("HEAD")
for file_path in staged:
assert ".renku" not in file_path
untracked = client.repo.untracked_files
for file_path in untracked:
assert ".renku" not in file_path
def test_datasets_create_dirty_exception_untracked(runner, project, client):
"""Test exception raise for untracked file in renku directory."""
# 1. Create a problem.
datasets_dir = client.path / RENKU_HOME / client.database_path
if not datasets_dir.exists():
datasets_dir.mkdir()
with (datasets_dir / "a").open("w") as fp:
fp.write("a")
# 2. Ensure correct error has been raised.
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 1 == result.exit_code
assert ".renku contains uncommitted changes." in result.output
def test_datasets_create_dirty_exception_staged(runner, project, client):
"""Test exception raise for staged file in renku directory."""
# 1. Create a problem within .renku directory
datasets_dir = client.path / RENKU_HOME / client.database_path
if not datasets_dir.exists():
datasets_dir.mkdir()
with (datasets_dir / "a").open("w") as fp:
fp.write("a")
# 2. Stage a problem without committing it.
client.repo.git.add(datasets_dir / "a")
# 3. Ensure correct error has been raised.
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 1 == result.exit_code
assert ".renku contains uncommitted changes." in result.output
def test_dataset_create_dirty_exception_all_untracked(runner, project, client):
"""Test exception raise for all untracked files."""
# 1. Create unclean root to enforce ensure checks.
with (client.path / "a").open("w") as fp:
fp.write("a")
# 2. Create a problem.
datasets_dir = client.path / RENKU_HOME / client.database_path
if not datasets_dir.exists():
datasets_dir.mkdir()
with (datasets_dir / "a").open("w") as fp:
fp.write("a")
# 3. Ensure correct error has been raised.
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 1 == result.exit_code
assert ".renku contains uncommitted changes." in result.output
def test_datasets_create_dirty_exception_all_staged(runner, project, client):
"""Test exception raise for all staged files."""
# 1. Create unclean root to enforce ensure checks.
with (client.path / "a").open("w") as fp:
fp.write("a")
client.repo.git.add("a")
# 2. Create a problem.
datasets_dir = client.path / RENKU_HOME / client.database_path
if not datasets_dir.exists():
datasets_dir.mkdir()
with (datasets_dir / "a").open("w") as fp:
fp.write("a")
client.repo.git.add(datasets_dir / "a")
# 3. Ensure correct error has been raised.
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 1 == result.exit_code
assert ".renku contains uncommitted changes." in result.output
def test_dataset_create_exception_refs(runner, project, client):
"""Test untracked/unstaged exception raise in dirty renku home dir."""
with (client.path / "a").open("w") as fp:
fp.write("a")
datasets_dir = client.path / RENKU_HOME / client.database_path
if not datasets_dir.exists():
datasets_dir.mkdir()
with (datasets_dir / "a").open("w") as fp:
fp.write("a")
refs_dir = client.path / RENKU_HOME / LinkReference.REFS
if not refs_dir.exists():
refs_dir.mkdir()
with (refs_dir / "b").open("w") as fp:
fp.write("b")
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 1 == result.exit_code
assert "a" in result.output
@pytest.mark.parametrize(
"creator,field",
[
("John Doe", "Email"),
("John Doe<>", "Email"),
("<john.doe@mail.ch>", "Name"),
("John Doe<john.doe@mail>", "Email"),
],
)
def test_dataset_creator_is_invalid(client, runner, creator, field):
"""Test create dataset with invalid creator format."""
result = runner.invoke(cli, ["dataset", "create", "ds", "-c", creator])
assert 2 == result.exit_code
assert field + " is invalid" in result.output
@pytest.mark.parametrize("output_format", DATASETS_FORMATS.keys())
def test_datasets_list_empty(output_format, runner, project):
"""Test listing without datasets."""
format_option = "--format={0}".format(output_format)
result = runner.invoke(cli, ["dataset", "ls", format_option])
assert 0 == result.exit_code, format_result_exception(result)
@pytest.mark.parametrize("output_format", DATASETS_FORMATS.keys())
def test_datasets_list_non_empty(output_format, runner, project):
"""Test listing with datasets."""
format_option = "--format={0}".format(output_format)
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
result = runner.invoke(cli, ["dataset", "ls", format_option])
assert 0 == result.exit_code, format_result_exception(result)
assert "my-dataset" in result.output
@pytest.mark.parametrize(
"columns,headers,values",
[
("title,short_name", ["TITLE", "NAME"], ["my-dataset", "Long Title"]),
("title,name", ["TITLE", "NAME"], ["my-dataset", "Long Title"]),
("creators", ["CREATORS"], ["John Doe"]),
],
)
def test_datasets_list_with_columns(runner, project, columns, headers, values):
"""Test listing datasets with custom column name."""
result = runner.invoke(
cli, ["dataset", "create", "my-dataset", "--title", "Long Title", "-c", "John Doe <john.doe@mail.ch>"]
)
assert 0 == result.exit_code, format_result_exception(result)
result = runner.invoke(cli, ["dataset", "ls", "--columns", columns])
assert 0 == result.exit_code, format_result_exception(result)
assert headers == result.output.split("\n").pop(0).split()
for value in values:
assert value in result.output
@pytest.mark.parametrize("column", DATASETS_COLUMNS.keys())
def test_datasets_list_columns_correctly(runner, project, column):
"""Test dataset listing only shows requested columns."""
assert 0 == runner.invoke(cli, ["dataset", "create", "test"]).exit_code
result = runner.invoke(cli, ["dataset", "ls", "--columns", column])
assert 0 == result.exit_code, format_result_exception(result)
header = result.output.split("\n").pop(0)
name, display_name = DATASETS_COLUMNS[column]
display_name = display_name or name
assert display_name.upper() == header
@pytest.mark.parametrize("columns", ["invalid", "id,invalid"])
def test_datasets_list_invalid_column(runner, project, columns):
"""Test dataset listing invalid column name."""
result = runner.invoke(cli, ["dataset", "ls", "--columns", columns])
assert 2 == result.exit_code
assert 'Invalid column name: "invalid".' in result.output
def test_datasets_list_description(runner, project):
"""Test dataset description listing."""
description = "Very long description. " * 100
assert 0 == runner.invoke(cli, ["dataset", "create", "test", "-d", description]).exit_code
short_description = textwrap.wrap(description, width=64, max_lines=2)[0]
result = runner.invoke(cli, ["dataset", "ls", "--columns=name,description"])
assert 0 == result.exit_code, format_result_exception(result)
line = next(line for line in result.output.split("\n") if "test" in line)
assert short_description in line
assert description[: len(short_description) + 1] not in line
def test_add_and_create_dataset(directory_tree, runner, project, client, subdirectory, load_dataset_with_injection):
"""Test add data to a non-existing dataset."""
result = runner.invoke(cli, ["dataset", "add", "new-dataset", str(directory_tree)], catch_exceptions=False)
assert 1 == result.exit_code
assert 'Dataset "new-dataset" does not exist.' in result.output
# Add succeeds with --create
result = runner.invoke(
cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)], catch_exceptions=False
)
assert 0 == result.exit_code, format_result_exception(result)
path1 = os.path.join(client.path, DATA_DIR, "new-dataset", directory_tree.name, "file1")
path2 = os.path.join(client.path, DATA_DIR, "new-dataset", directory_tree.name, "dir1", "file2")
path3 = os.path.join(client.path, DATA_DIR, "new-dataset", directory_tree.name, "dir1", "file3")
assert os.stat(path1)
assert os.stat(path2)
assert os.stat(path3)
dataset = load_dataset_with_injection("new-dataset", client)
assert {os.path.relpath(p, client.path) for p in [path1, path2, path3]} == {f.entity.path for f in dataset.files}
# Further, add with --create fails
result = runner.invoke(cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)])
assert 1 == result.exit_code
def test_add_and_create_dataset_with_lfs_warning(directory_tree, runner, project, client_with_lfs_warning):
"""Test add data with lfs warning."""
# Add succeeds with --create
result = runner.invoke(
cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)], catch_exceptions=False
)
assert 0 == result.exit_code, format_result_exception(result)
assert "Adding these files to Git LFS" in result.output
assert "dir1/file2" in result.output
assert "file" in result.output
def test_add_to_dirty_repo(directory_tree, runner, project, client):
"""Test adding to a dataset in a dirty repo commits only added files."""
with (client.path / "tracked").open("w") as fp:
fp.write("tracked file")
client.repo.git.add("*")
client.repo.index.commit("tracked file")
with (client.path / "tracked").open("w") as fp:
fp.write("modified tracked file")
with (client.path / "untracked").open("w") as fp:
fp.write("untracked file")
result = runner.invoke(
cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)], catch_exceptions=False
)
assert 0 == result.exit_code, format_result_exception(result)
assert client.repo.is_dirty()
assert ["untracked"] == client.repo.untracked_files
# Add without making a change
result = runner.invoke(cli, ["dataset", "add", "new-dataset", str(directory_tree)], catch_exceptions=False)
assert 1 == result.exit_code
assert client.repo.is_dirty()
assert ["untracked"] == client.repo.untracked_files
def test_add_unicode_file(tmpdir, runner, project, client):
"""Test adding files with unicode special characters in their names."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
filename = "filéàèû爱ಠ_ಠ.txt"
new_file = tmpdir.join(filename)
new_file.write(str("test"))
# add data
result = runner.invoke(cli, ["dataset", "add", "my-dataset", str(new_file)])
assert 0 == result.exit_code, format_result_exception(result)
result = runner.invoke(cli, ["graph", "export", "--format", "json-ld", "--strict"])
assert 0 == result.exit_code, format_result_exception(result)
assert filename in result.output.encode("latin1").decode("unicode-escape")
def test_multiple_file_to_dataset(tmpdir, runner, project, client, load_dataset_with_injection):
"""Test importing multiple data into a dataset at once."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
dataset = load_dataset_with_injection("dataset", client)
assert dataset.title == "dataset"
paths = []
for i in range(3):
new_file = tmpdir.join("file_{0}".format(i))
new_file.write(str(i))
paths.append(str(new_file))
# add data
result = runner.invoke(cli, ["dataset", "add", "dataset"] + paths, catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
def test_repository_file_to_dataset(runner, client, subdirectory, load_dataset_with_injection):
"""Test adding a file from the repository into a dataset."""
# create a dataset
assert 0 == runner.invoke(cli, ["dataset", "create", "dataset"]).exit_code
a_path = client.path / "a"
a_path.write_text("a content")
client.repo.git.add(str(a_path))
client.repo.git.commit(message="Added file a", no_verify=True)
result = runner.invoke(cli, ["dataset", "add", "dataset", str(a_path)], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
dataset = load_dataset_with_injection("dataset", client)
assert dataset.title == "dataset"
assert dataset.find_file("a") is not None
def test_relative_import_to_dataset(tmpdir, runner, client, subdirectory, load_dataset_with_injection):
"""Test importing data from a directory structure."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
dataset = load_dataset_with_injection("dataset", client)
assert dataset.title == "dataset"
zero_data = tmpdir.join("zero.txt")
zero_data.write("zero")
first_level = tmpdir.mkdir("first")
second_level = first_level.mkdir("second")
first_data = first_level.join("first.txt")
first_data.write("first")
second_data = second_level.join("second.txt")
second_data.write("second")
paths = [str(zero_data), str(first_level), str(second_level)]
result = runner.invoke(cli, ["dataset", "add", "dataset"] + paths, catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
assert os.stat(client.path / DATA_DIR / "dataset" / "zero.txt")
assert os.stat(client.path / DATA_DIR / "dataset" / "first" / "first.txt")
assert os.stat(client.path / DATA_DIR / "dataset" / "first" / "second" / "second.txt")
@pytest.mark.parametrize(
"params,message",
[
(["-s", "file", "https://renkulab.io/"], 'Cannot use "--source" with URLs or local files.'),
(["-s", "file", "/some/local/path"], 'Cannot use "--source" with URLs or local files.'),
],
)
def test_usage_error_in_add_from_url(runner, client, params, message):
"""Test user's errors when adding URL/local file to a dataset."""
result = runner.invoke(cli, ["dataset", "add", "remote", "--create"] + params, catch_exceptions=False)
assert 2 == result.exit_code
assert message in result.output
def test_add_from_local_repo_warning(runner, client, data_repository, directory_tree):
"""Test a warning is printed when adding from a local git repo."""
result = runner.invoke(cli, ["dataset", "add", "dataset", "--create", str(directory_tree)], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
assert "Use remote's Git URL instead to enable lineage " in result.output
def test_add_data_directory(runner, client, directory_tree):
"""Test adding a dataset's data directory to it prints an error."""
result = runner.invoke(cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)])
assert 0 == result.exit_code, format_result_exception(result)
result = runner.invoke(cli, ["dataset", "add", "new-dataset", "data/new-dataset"], catch_exceptions=False)
assert 2 == result.exit_code
assert "Cannot add dataset's data directory recursively" in result.output
def test_dataset_add_with_copy(tmpdir, runner, project, client, load_dataset_with_injection):
"""Test adding data to dataset with copy."""
import os
import stat
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
paths = []
original_inodes = []
for i in range(3):
new_file = tmpdir.join("file_{0}".format(i))
new_file.write(str(i))
original_inodes.append(os.lstat(str(new_file))[stat.ST_INO])
paths.append(str(new_file))
# add data
result = runner.invoke(cli, ["dataset", "add", "my-dataset"] + paths)
assert 0 == result.exit_code, format_result_exception(result)
received_inodes = []
dataset = load_dataset_with_injection("my-dataset", client)
assert dataset.title == "my-dataset"
for file in dataset.files:
path = (client.path / file.entity.path).resolve()
received_inodes.append(os.lstat(path)[stat.ST_INO])
# check that original inodes are within created ones
for inode in received_inodes:
assert inode not in original_inodes
@pytest.mark.serial
def test_dataset_add_many(tmpdir, runner, project, client):
"""Test adding many files to dataset."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
paths = []
for i in range(1000):
new_file = tmpdir.join("file_{0}".format(i))
new_file.write(str(i))
paths.append(str(new_file))
# add data
result = runner.invoke(cli, ["dataset", "add", "my-dataset"] + paths)
assert 0 == result.exit_code, format_result_exception(result)
assert len(client.repo.head.commit.message) <= 100
def test_dataset_file_path_from_subdirectory(runner, client, subdirectory, load_dataset_with_injection):
"""Test adding a file into a dataset and check path independent
of the CWD"""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
a_path = client.path / "a"
a_path.write_text("a text")
client.repo.git.add(str(a_path))
client.repo.git.commit(message="Added file a")
# add data
result = runner.invoke(cli, ["dataset", "add", "dataset", str(a_path)], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
dataset = load_dataset_with_injection("dataset", client)
file = dataset.find_file("a")
assert file is not None
assert "a" == file.entity.path
def test_datasets_ls_files_tabular_empty(runner, project):
"""Test listing of data within empty dataset."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
# list all files in dataset
result = runner.invoke(cli, ["dataset", "ls-files", "--columns", "added,creators,dataset,path", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
# check output
output = result.output.split("\n")
assert output.pop(0).split() == ["ADDED", "CREATORS", "DATASET", "PATH"]
assert set(output.pop(0)) == {" ", "-"}
assert output.pop(0) == ""
assert not output
@pytest.mark.parametrize("output_format", DATASET_FILES_FORMATS.keys())
def test_datasets_ls_files_check_exit_code(output_format, runner, project):
"""Test file listing exit codes for different formats."""
format_option = "--format={0}".format(output_format)
result = runner.invoke(cli, ["dataset", "ls-files", format_option])
assert 0 == result.exit_code, format_result_exception(result)
def test_datasets_ls_files_lfs(tmpdir, large_file, runner, project):
"""Test file listing lfs status."""
# NOTE: create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
# NOTE: create some data
paths = []
new_file = tmpdir.join("file_1")
new_file.write(str(1))
paths.append(str(new_file))
paths.append(str(large_file))
# NOTE: add data to dataset
result = runner.invoke(cli, ["dataset", "add", "my-dataset"] + paths, catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
# NOTE: check files
result = runner.invoke(cli, ["dataset", "ls-files"])
assert 0 == result.exit_code, format_result_exception(result)
lines = result.output.split("\n")
file1_entry = next(line for line in lines if "file_1" in line)
file2_entry = next(line for line in lines if large_file.name in line)
assert file1_entry
assert file2_entry
assert not file1_entry.endswith("*")
assert file2_entry.endswith("*")
def test_datasets_ls_files_json(tmpdir, large_file, runner, project):
"""Test file listing lfs status."""
# NOTE: create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
# NOTE: create some data
paths = []
new_file = tmpdir.join("file_1")
new_file.write(str(1))
paths.append(str(new_file))
paths.append(str(large_file))
# NOTE: add data to dataset
result = runner.invoke(cli, ["dataset", "add", "my-dataset"] + paths, catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
# NOTE: check files
result = runner.invoke(cli, ["dataset", "ls-files", "--format", "json"])
assert 0 == result.exit_code, format_result_exception(result)
result = json.loads(result.output)
assert len(result) == 2
file1 = next((f for f in result if f["path"].endswith("file_1")))
file2 = next((f for f in result if f["path"].endswith(large_file.name)))
assert not file1["is_lfs"]
assert file2["is_lfs"]
assert file1["creators"]
assert file1["size"]
assert file1["dataset_name"]
assert file1["dataset_id"]
assert file2["creators"]
assert file2["size"]
assert file2["dataset_name"]
assert file2["dataset_id"]
@pytest.mark.parametrize("column", DATASET_FILES_COLUMNS.keys())
def test_datasets_ls_files_columns_correctly(runner, project, column, directory_tree):
"""Test file listing only shows requested columns."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree)]).exit_code
result = runner.invoke(cli, ["dataset", "ls-files", "--columns", column], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
header = result.output.split("\n").pop(0).strip()
name, display_name = DATASET_FILES_COLUMNS[column]
display_name = display_name or name
assert display_name.upper() == header
@pytest.mark.parametrize("columns", ["invalid", "path,invalid"])
def test_datasets_ls_files_invalid_column(runner, project, columns):
"""Test file listing with invalid column name."""
result = runner.invoke(cli, ["dataset", "ls-files", "--columns", columns])
assert 2 == result.exit_code
assert 'Invalid column name: "invalid".' in result.output
def test_datasets_ls_files_tabular_dataset_filter(runner, project, directory_tree):
"""Test listing of data within dataset."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree)]).exit_code
# list all files in non empty dataset
result = runner.invoke(cli, ["dataset", "ls-files", "--columns", "added,path", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
# check output from ls-files command
output = result.output.split("\n")
assert output.pop(0).split() == ["ADDED", "PATH"]
assert set(output.pop(0)) == {" ", "-"}
created_files = list(f.name for f in directory_tree.rglob("*file*"))
# check listing
added_at = []
for _ in range(3):
row = output.pop(0).split(" ")
assert Path(row.pop()).name in created_files
added_at.append(row.pop(0))
# check if sorted by added_at
assert added_at == sorted(added_at)
def test_datasets_ls_files_tabular_patterns(runner, project, directory_tree):
"""Test listing of data within dataset with include/exclude filters."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree)]).exit_code
# check include / exclude filters
result = runner.invoke(cli, ["dataset", "ls-files", "--include=**/file*", "--exclude=**/file2"])
assert 0 == result.exit_code, format_result_exception(result)
# check output
assert "file1" in result.output
assert "file2" not in result.output
assert "file3" in result.output
# check directory pattern
result = runner.invoke(cli, ["dataset", "ls-files", "--include=**/dir1/*"])
assert 0 == result.exit_code, format_result_exception(result)
# check output
assert "file1" not in result.output
assert "file2" in result.output
assert "file3" in result.output
def test_datasets_ls_files_tabular_creators(runner, client, directory_tree, load_dataset_with_injection):
"""Test listing of data within dataset with creators filters."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree)]).exit_code
creator = load_dataset_with_injection("my-dataset", client).creators[0].name
assert creator is not None
# check creators filters
result = runner.invoke(cli, ["dataset", "ls-files", "--creators={0}".format(creator)])
assert 0 == result.exit_code, format_result_exception(result)
# check output
for file_ in directory_tree.rglob("*file*"):
assert file_.name in result.output
def test_datasets_ls_files_correct_paths(runner, client, directory_tree):
"""Test listing of data within dataset and check that paths are correct."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree)]).exit_code
# check include / exclude filters
result = runner.invoke(cli, ["dataset", "ls-files", "--format=json-ld"])
assert 0 == result.exit_code, format_result_exception(result)
output = json.loads(result.output)
for record in output:
for entity in record:
path = entity.get("http://www.w3.org/ns/prov#atLocation")
if path:
path = path[0]["@value"]
assert (client.path / path).exists()
def test_datasets_ls_files_with_name(directory_tree, runner, project):
"""Test listing of data within dataset with include/exclude filters."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset", "--title", "Long Title"])
assert 0 == result.exit_code, format_result_exception(result)
# add data to dataset
result = runner.invoke(cli, ["dataset", "add", "my-dataset", str(directory_tree)], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
# list files with name
result = runner.invoke(cli, ["dataset", "ls-files", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "dir1/file2" in result.output
def test_datasets_ls_files_correct_size(runner, client, directory_tree, large_file):
"""Test ls-files shows the size stored in git and not the current file size."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree / "file1")]).exit_code
path = client.path / DATA_DIR / "my-dataset" / "file1"
shutil.copy(large_file, path)
# check include / exclude filters
result = runner.invoke(cli, ["dataset", "ls-files", "--columns=size, path"])
assert 0 == result.exit_code, format_result_exception(result)
line = next(line for line in result.output.split("\n") if "file1" in line)
size = int(line.split()[0])
assert 3 == size
@pytest.mark.skip(reason="FIXME: We don't have commit shas for files. What should be listed here?")
def test_datasets_ls_files_correct_commit(runner, client, directory_tree):
"""Test ls-files shows the size stored in git and not the current file size."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-dataset", "-c", str(directory_tree / "file1")]).exit_code
commit = client.find_previous_commit(paths=client.path / DATA_DIR / "my-dataset" / "file1")
# check include / exclude filters
result = runner.invoke(cli, ["dataset", "ls-files", "--columns=commit,path"])
assert 0 == result.exit_code, format_result_exception(result)
line = next(line for line in result.output.split("\n") if "file1" in line)
commit_sha = line.split()[0]
assert commit.hexsha == commit_sha
def test_dataset_unlink_file_not_found(runner, project):
"""Test unlinking of file from dataset with no files found."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
result = runner.invoke(cli, ["dataset", "unlink", "my-dataset", "--include", "notthere.csv"])
assert 2 == result.exit_code
def test_dataset_unlink_file_abort_unlinking(tmpdir, runner, project):
"""Test unlinking of file from dataset and aborting."""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
# create data file
new_file = tmpdir.join("datafile.csv")
new_file.write("1,2,3")
# add data to dataset
result = runner.invoke(cli, ["dataset", "add", "my-dataset", str(new_file)])
assert 0 == result.exit_code, format_result_exception(result)
# unlink file from dataset
result = runner.invoke(cli, ["dataset", "unlink", "my-dataset", "--include", new_file.basename], input="n")
assert 1 == result.exit_code
# check output
assert "Aborted!" in result.output
def test_dataset_unlink_file(tmpdir, runner, client, subdirectory, load_dataset_with_injection):
"""Test unlinking of file and check removal from dataset"""
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
# create data file
new_file = tmpdir.join("datafile.csv")
new_file.write("1,2,3")
# add data to dataset
result = runner.invoke(cli, ["dataset", "add", "my-dataset", str(new_file)])
assert 0 == result.exit_code, format_result_exception(result)
assert not client.repo.is_dirty()
dataset = load_dataset_with_injection("my-dataset", client)
assert new_file.basename in {Path(f.entity.path).name for f in dataset.files}
commit_sha_before = client.repo.head.object.hexsha
result = runner.invoke(cli, ["dataset", "unlink", "my-dataset", "--include", new_file.basename, "-y"])
assert 0 == result.exit_code, format_result_exception(result)
assert not client.repo.is_dirty()
commit_sha_after = client.repo.head.object.hexsha
assert commit_sha_before != commit_sha_after
dataset = load_dataset_with_injection("my-dataset", client)
assert new_file.basename not in [Path(f.entity.path).name for f in dataset.files if not f.is_removed()]
def test_dataset_rm(runner, client, directory_tree, subdirectory, load_dataset_with_injection):
"""Test removal of a dataset."""
assert 0 == runner.invoke(cli, ["dataset", "add", "--create", "my-dataset", str(directory_tree)]).exit_code
assert load_dataset_with_injection("my-dataset", client)
result = runner.invoke(cli, ["dataset", "rm", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
assert not load_dataset_with_injection("my-dataset", client)
result = runner.invoke(cli, ["doctor"], catch_exceptions=False)
assert 0 == result.exit_code, format_result_exception(result)
def test_dataset_rm_failure(runner, client):
"""Test errors in removal of a dataset."""
assert 2 == runner.invoke(cli, ["dataset", "rm"]).exit_code
assert 1 == runner.invoke(cli, ["dataset", "rm", "does-not-exist"]).exit_code
def test_dataset_overwrite_no_confirm(runner, project):
"""Check dataset overwrite behaviour without confirmation."""
result = runner.invoke(cli, ["dataset", "create", "rokstar"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
result = runner.invoke(cli, ["dataset", "create", "rokstar"])
assert 1 == result.exit_code