-
Notifications
You must be signed in to change notification settings - Fork 13
/
test_asset.py
1780 lines (1459 loc) · 56.5 KB
/
test_asset.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
from __future__ import annotations
import json
from uuid import uuid4
from dandischema.models import AccessType
from django.conf import settings
from django.db.utils import IntegrityError
from django.urls import reverse
from guardian.shortcuts import assign_perm
import pytest
import requests
from dandiapi.api.asset_paths import add_asset_paths, extract_paths
from dandiapi.api.models import Asset, AssetBlob, Version
from dandiapi.api.models.asset_paths import AssetPath
from dandiapi.api.models.dandiset import Dandiset
from dandiapi.api.services.asset import add_asset_to_version
from dandiapi.api.services.asset.exceptions import AssetPathConflictError
from dandiapi.api.services.publish import publish_asset
from dandiapi.api.tasks.scheduled import validate_pending_asset_metadata
from dandiapi.zarr.models import ZarrArchive, ZarrArchiveStatus
from dandiapi.zarr.tasks import ingest_zarr_archive
from .fuzzy import HTTP_URL_RE, TIMESTAMP_RE, URN_RE, UTC_ISO_TIMESTAMP_RE, UUID_RE
# Model tests
@pytest.mark.django_db
def test_asset_no_blob_zarr(draft_asset_factory):
asset = draft_asset_factory()
# An integrity error is thrown when the blob/zarr check constraint fails
asset.blob = None
with pytest.raises(IntegrityError) as excinfo:
asset.save()
assert 'blob-xor-zarr' in str(excinfo.value)
@pytest.mark.django_db
def test_asset_blob_and_zarr(draft_asset, zarr_archive):
# An integrity error is thrown by the constraint that both blob and zarr cannot both be defined
draft_asset.zarr = zarr_archive
with pytest.raises(IntegrityError) as excinfo:
draft_asset.save()
assert 'blob-xor-zarr' in str(excinfo.value)
@pytest.mark.django_db
def test_asset_rest_path(api_client, draft_version_factory, asset_factory):
# Initialize version and contained assets
version: Version = draft_version_factory()
asset = asset_factory(path='foo/bar/baz/a.txt')
version.assets.add(asset)
# Add asset path
add_asset_paths(asset, version)
# Retrieve root paths
resp = api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/'
f'versions/{version.version}/assets/paths/',
{'path_prefix': ''},
).data
assert resp['count'] == 1
val = resp['results'][0]
assert val['aggregate_files'] == 1
@pytest.mark.django_db
def test_asset_rest_path_not_found(api_client, draft_version_factory, asset_factory):
# Initialize version and contained assets
version: Version = draft_version_factory()
asset = asset_factory(path='foo/a.txt')
version.assets.add(asset)
# Add asset path
add_asset_paths(asset, version)
# Retrieve root paths
resp = api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/'
f'versions/{version.version}/assets/paths/',
{'path_prefix': 'bar'},
)
assert resp.status_code == 404
assert resp.json() == {'detail': 'Specified path not found.'}
@pytest.mark.django_db
def test_asset_s3_url(asset_blob):
signed_url = asset_blob.blob.url
s3_url = asset_blob.s3_url
assert signed_url.startswith(s3_url)
assert signed_url.split('?')[0] == s3_url
@pytest.mark.django_db
def test_publish_asset(draft_asset: Asset):
draft_asset_id = draft_asset.asset_id
draft_blob = draft_asset.blob
draft_metadata = draft_asset.full_metadata
draft_asset.status = Asset.Status.VALID
draft_asset.save()
publish_asset(asset=draft_asset)
# draft_asset has been published, so it is now published_asset
published_asset = draft_asset
published_asset.refresh_from_db()
assert published_asset.blob == draft_blob
assert published_asset.full_metadata == {
**draft_metadata,
'id': f'dandiasset:{draft_asset_id}',
'publishedBy': {
'id': URN_RE,
'name': 'DANDI publish',
'startDate': UTC_ISO_TIMESTAMP_RE,
'endDate': UTC_ISO_TIMESTAMP_RE,
'wasAssociatedWith': [
{
'id': URN_RE,
'identifier': 'RRID:SCR_017571',
'name': 'DANDI API',
# TODO: version the API
'version': '0.1.0',
'schemaKey': 'Software',
}
],
'schemaKey': 'PublishActivity',
},
'datePublished': UTC_ISO_TIMESTAMP_RE,
'identifier': str(draft_asset_id),
'contentUrl': [HTTP_URL_RE, HTTP_URL_RE],
}
@pytest.mark.django_db
def test_asset_total_size(
draft_version_factory, asset_factory, asset_blob_factory, zarr_archive_factory
):
# This asset blob should only be counted once,
# despite belonging to multiple assets and multiple versions.
asset_blob = asset_blob_factory()
asset1 = asset_factory(blob=asset_blob)
version1 = draft_version_factory()
version1.assets.add(asset1)
asset2 = asset_factory(blob=asset_blob)
version2 = draft_version_factory()
version2.assets.add(asset2)
# These asset blobs should not be counted since they aren't in any versions.
asset_blob_factory()
asset_factory()
assert Asset.total_size() == asset_blob.size
zarr_archive = zarr_archive_factory()
# give it some size
zarr_archive.size = 100
zarr_archive.save() # save adjusted .size into DB
# adding of an asset with zarr should be reflected
asset3 = asset_factory(zarr=zarr_archive, blob=None)
version2.assets.add(asset3)
assert Asset.total_size() == asset_blob.size + zarr_archive.size
@pytest.mark.django_db
def test_asset_full_metadata(draft_asset_factory):
raw_metadata = {
'foo': 'bar',
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
}
asset: Asset = draft_asset_factory(metadata=raw_metadata)
# Test that full_metadata includes the correct values
download_url = settings.DANDI_API_URL + reverse(
'asset-download',
kwargs={'asset_id': str(asset.asset_id)},
)
blob_url = asset.blob.s3_url
assert asset.full_metadata == {
**raw_metadata,
'id': f'dandiasset:{asset.asset_id}',
'access': [{'schemaKey': 'AccessRequirements', 'status': AccessType.OpenAccess.value}],
'path': asset.path,
'identifier': str(asset.asset_id),
'contentUrl': [download_url, blob_url],
'contentSize': asset.blob.size,
'digest': asset.blob.digest,
'@context': f'https://raw.githubusercontent.com/dandi/schema/master/releases/{settings.DANDI_SCHEMA_VERSION}/context.json',
}
@pytest.mark.django_db
def test_asset_full_metadata_zarr(draft_asset_factory, zarr_archive):
raw_metadata = {
'foo': 'bar',
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
}
asset: Asset = draft_asset_factory(metadata=raw_metadata, blob=None, zarr=zarr_archive)
# Test that full_metadata includes the correct values
download_url = settings.DANDI_API_URL + reverse(
'asset-download',
kwargs={'asset_id': str(asset.asset_id)},
)
s3_url = asset.zarr.s3_url
assert asset.full_metadata == {
**raw_metadata,
'id': f'dandiasset:{asset.asset_id}',
'access': [{'schemaKey': 'AccessRequirements', 'status': AccessType.OpenAccess.value}],
'path': asset.path,
'identifier': str(asset.asset_id),
'contentUrl': [download_url, s3_url],
'contentSize': asset.size,
'digest': asset.digest,
# This should be injected on all zarr assets
'encodingFormat': 'application/x-zarr',
'@context': f'https://raw.githubusercontent.com/dandi/schema/master/releases/{settings.DANDI_SCHEMA_VERSION}/context.json',
}
@pytest.mark.django_db
def test_asset_full_metadata_access(draft_asset_factory, asset_blob_factory, zarr_archive_factory):
raw_metadata = {
'foo': 'bar',
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
}
embargoed_zarr_asset: Asset = draft_asset_factory(
metadata=raw_metadata, blob=None, zarr=zarr_archive_factory(embargoed=True)
)
open_zarr_asset: Asset = draft_asset_factory(
metadata=raw_metadata, blob=None, zarr=zarr_archive_factory(embargoed=False)
)
embargoed_blob_asset: Asset = draft_asset_factory(
metadata=raw_metadata, blob=asset_blob_factory(embargoed=True), zarr=None
)
open_blob_asset: Asset = draft_asset_factory(
metadata=raw_metadata, blob=asset_blob_factory(embargoed=False), zarr=None
)
# Test that access is correctly inferred from embargo status
assert embargoed_zarr_asset.full_metadata['access'] == [
{'schemaKey': 'AccessRequirements', 'status': AccessType.EmbargoedAccess.value}
]
assert embargoed_blob_asset.full_metadata['access'] == [
{'schemaKey': 'AccessRequirements', 'status': AccessType.EmbargoedAccess.value}
]
assert open_zarr_asset.full_metadata['access'] == [
{'schemaKey': 'AccessRequirements', 'status': AccessType.OpenAccess.value}
]
assert open_blob_asset.full_metadata['access'] == [
{'schemaKey': 'AccessRequirements', 'status': AccessType.OpenAccess.value}
]
# API Tests
@pytest.mark.django_db
def test_asset_rest_list(api_client, version, asset, asset_factory):
version.assets.add(asset)
# Create an extra asset so that there are multiple assets to filter down
asset_factory()
assert api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/versions/{version.version}/assets/'
).json() == {
'count': 1,
'next': None,
'previous': None,
'results': [
{
'asset_id': str(asset.asset_id),
'path': asset.path,
'size': asset.size,
'blob': str(asset.blob.blob_id),
'zarr': None,
'created': TIMESTAMP_RE,
'modified': TIMESTAMP_RE,
}
],
}
@pytest.mark.django_db
def test_asset_rest_list_include_metadata(api_client, version, asset, asset_factory):
version.assets.add(asset)
# Create an extra asset so that there are multiple assets to filter down
asset_factory()
# Assert false has no effect
r = api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/versions/{version.version}/assets/',
{'metadata': False},
)
assert 'metadata' not in r.json()['results'][0]
# Test positive case
r = api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/versions/{version.version}/assets/',
{'metadata': True},
)
assert r.json()['results'][0]['metadata'] == asset.full_metadata
@pytest.mark.parametrize(
('path', 'result_indices'),
[
('foo.txt', [0]),
('bar.txt', [1]),
('foo', [0, 2]),
('bar', [1]),
('foo/', [2]),
('txt', []),
],
ids=[
'exact-match-foo',
'exact-match-bar',
'prefix-foo',
'prefix-bar',
'prefix-foo/',
'no-match',
],
)
@pytest.mark.django_db
def test_asset_rest_list_path_filter(api_client, version, asset_factory, path, result_indices):
assets = [
asset_factory(path='foo.txt'),
asset_factory(path='bar.txt'),
asset_factory(path='foo/bar.txt'),
]
for asset in assets:
version.assets.add(asset)
expected_assets = [assets[i] for i in result_indices]
assert api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/versions/{version.version}/assets/',
data={'path': path},
).json() == {
'count': len(expected_assets),
'next': None,
'previous': None,
'results': [
{
'asset_id': str(asset.asset_id),
'path': asset.path,
'size': asset.size,
'blob': str(asset.blob.blob_id),
'zarr': None,
'created': TIMESTAMP_RE,
'modified': TIMESTAMP_RE,
}
for asset in expected_assets
],
}
@pytest.mark.parametrize(
('order_param', 'ordering'),
[
('created', ['b', 'a', 'c']),
('-created', ['c', 'a', 'b']),
# Modified is same as created
('modified', ['b', 'a', 'c']),
('-modified', ['c', 'a', 'b']),
('path', ['a', 'b', 'c']),
('-path', ['c', 'b', 'a']),
],
ids=['created', '-created', 'modified', '-modified', 'path', '-path'],
)
@pytest.mark.django_db
def test_asset_rest_list_ordering(api_client, version, asset_factory, order_param, ordering):
# Create asset B first so that the path ordering is different from the created ordering.
b = asset_factory(path='b')
a = asset_factory(path='a')
c = asset_factory(path='c')
version.assets.add(a)
version.assets.add(b)
version.assets.add(c)
results = api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/versions/{version.version}/assets/',
data={'order': order_param},
).data['results']
# Summarize the returned asset objects with their path, so that we can parametrize the
# expected results easier.
result_paths = [asset['path'] for asset in results]
assert result_paths == ordering
@pytest.mark.django_db
def test_asset_path_ordering(api_client, version, asset_factory):
# The default collation will ignore special characters, including slashes, on the first pass. If
# there are ties, it uses these characters to break ties. This means that in the below example,
# removing the slashes leads to a comparison of 'az' and 'aaz', which would obviously sort the
# latter before the former. However, with the slashes, it's clear that 'a/z' should come before
# 'aa/z'. This is fixed by changing the collation of the path field, and as such this test
# serves as a regression test.
a = asset_factory(path='a/z')
b = asset_factory(path='aa/z')
version.assets.add(a)
version.assets.add(b)
asset_listing = Asset.objects.filter(versions__in=[version]).order_by('path')
assert asset_listing.count() == 2
assert asset_listing[0].pk == a.pk
assert asset_listing[1].pk == b.pk
@pytest.mark.django_db
def test_asset_rest_retrieve(api_client, version, asset, asset_factory):
version.assets.add(asset)
# Create an extra asset so that there are multiple assets to filter down
asset_factory()
assert (
api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/'
f'versions/{version.version}/assets/{asset.asset_id}/'
).json()
== asset.full_metadata
)
@pytest.mark.django_db
def test_asset_rest_retrieve_no_sha256(api_client, version, asset):
version.assets.add(asset)
# Remove the sha256 from the factory asset
asset.blob.sha256 = None
asset.blob.save()
assert (
api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/'
f'versions/{version.version}/assets/{asset.asset_id}/'
).json()
== asset.full_metadata
)
@pytest.mark.django_db
def test_asset_rest_retrieve_embargoed_admin(
api_client,
draft_version_factory,
draft_asset_factory,
admin_user,
storage,
monkeypatch,
):
monkeypatch.setattr(AssetBlob.blob.field, 'storage', storage)
api_client.force_authenticate(user=admin_user)
version = draft_version_factory(dandiset__embargo_status=Dandiset.EmbargoStatus.EMBARGOED)
ds = version.dandiset
# Create an extra asset so that there are multiple assets to filter down
asset = draft_asset_factory(blob__embargoed=True)
version.assets.add(asset)
# Asset View
r = api_client.get(f'/api/assets/{asset.asset_id}/')
assert r.status_code == 200
# Nested Asset View
r = api_client.get(
f'/api/dandisets/{ds.identifier}/versions/{version.version}/assets/{asset.asset_id}/'
)
assert r.status_code == 200
@pytest.mark.django_db
def test_asset_rest_download_embargoed_admin(
api_client,
draft_version_factory,
draft_asset_factory,
admin_user,
storage,
monkeypatch,
):
monkeypatch.setattr(AssetBlob.blob.field, 'storage', storage)
api_client.force_authenticate(user=admin_user)
version = draft_version_factory(dandiset__embargo_status=Dandiset.EmbargoStatus.EMBARGOED)
ds = version.dandiset
# Create an extra asset so that there are multiple assets to filter down
asset = draft_asset_factory(blob__embargoed=True)
version.assets.add(asset)
# Asset View
r = api_client.get(f'/api/assets/{asset.asset_id}/download/')
assert r.status_code == 302
# Nested Asset View
r = api_client.get(
f'/api/dandisets/{ds.identifier}/versions/{version.version}/assets/{asset.asset_id}/download/'
)
assert r.status_code == 302
@pytest.mark.django_db
def test_asset_rest_info(api_client, version, asset):
version.assets.add(asset)
assert api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/'
f'versions/{version.version}/assets/{asset.asset_id}/info/'
).json() == {
'asset_id': str(asset.asset_id),
'blob': str(asset.blob.blob_id),
'zarr': None,
'path': asset.path,
'size': asset.size,
'metadata': asset.full_metadata,
'created': TIMESTAMP_RE,
'modified': TIMESTAMP_RE,
}
@pytest.mark.django_db
@pytest.mark.parametrize(
('status', 'validation_error'),
[
(Asset.Status.PENDING, ''),
(Asset.Status.VALIDATING, ''),
(Asset.Status.VALID, ''),
(Asset.Status.INVALID, 'error'),
],
)
def test_asset_rest_validation(api_client, version, asset, status, validation_error):
version.assets.add(asset)
asset.status = status
asset.validation_errors = validation_error
asset.save()
assert api_client.get(
f'/api/dandisets/{version.dandiset.identifier}/'
f'versions/{version.version}/assets/{asset.asset_id}/validation/'
).data == {
'status': status,
'validation_errors': validation_error,
}
@pytest.mark.django_db
def test_asset_create(api_client, user, draft_version, asset_blob):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-nwb',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': asset_blob.blob_id},
format='json',
).json()
new_asset = Asset.objects.get(asset_id=resp['asset_id'])
assert resp == {
'asset_id': UUID_RE,
'path': path,
'size': asset_blob.size,
'blob': asset_blob.blob_id,
'zarr': None,
'created': TIMESTAMP_RE,
'modified': TIMESTAMP_RE,
'metadata': new_asset.full_metadata,
}
# Assert all provided metadata exists
for key in metadata:
assert resp['metadata'][key] == metadata[key]
# Assert paths are properly ingested
for subpath in extract_paths(path):
obj = AssetPath.objects.get(version=draft_version, path=subpath)
if subpath == path:
assert obj.asset == new_asset
else:
assert obj.asset is None
# The version modified date should be updated
start_time = draft_version.modified
draft_version.refresh_from_db()
end_time = draft_version.modified
assert start_time < end_time
# Adding an Asset should trigger a revalidation
assert draft_version.status == Version.Status.PENDING
@pytest.mark.parametrize(
('path', 'expected_status_code'),
[
('foo.txt', 200),
('/foo', 400),
('', 400),
('/', 400),
('./foo', 400),
('../foo', 400),
('foo/.', 400),
('foo/..', 400),
('foo/./bar', 400),
('foo/../bar', 400),
('foo//bar', 400),
('foo\0bar', 400),
('foo/.bar', 200),
],
)
@pytest.mark.django_db
def test_asset_create_path_validation(
api_client, user, draft_version, asset_blob, path, expected_status_code
):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
metadata = {
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
'encodingFormat': 'application/x-nwb',
'path': path,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': asset_blob.blob_id},
format='json',
)
assert resp.status_code == expected_status_code, resp.data
@pytest.mark.django_db
def test_asset_create_conflicting_path(api_client, user, draft_version, asset_blob):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
# Add first asset
add_asset_to_version(
user=user,
version=draft_version,
asset_blob=asset_blob,
metadata={
'path': 'foo/bar.txt',
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
},
)
# Add an asset that has a path which fully contains that of the first asset
with pytest.raises(AssetPathConflictError):
add_asset_to_version(
user=user,
version=draft_version,
asset_blob=asset_blob,
metadata={
'path': 'foo/bar.txt/baz.txt',
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
},
)
# Add an asset that's path is fully contained by the first asset
with pytest.raises(AssetPathConflictError):
add_asset_to_version(
user=user,
version=draft_version,
asset_blob=asset_blob,
metadata={
'path': 'foo',
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
},
)
@pytest.mark.django_db
def test_asset_create_embargo(
api_client, user, draft_version_factory, dandiset_factory, embargoed_asset_blob
):
dandiset = dandiset_factory(embargo_status=Dandiset.EmbargoStatus.EMBARGOED)
draft_version = draft_version_factory(dandiset=dandiset)
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
assert draft_version.dandiset.embargo_status == Dandiset.EmbargoStatus.EMBARGOED
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-nwb',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
'access': [
{
'schemaKey': 'AccessRequirements',
'status': AccessType.OpenAccess.value,
}
],
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': embargoed_asset_blob.blob_id},
format='json',
).json()
new_asset = Asset.objects.get(asset_id=resp['asset_id'])
assert new_asset.full_metadata['access'][0]['status'] == AccessType.EmbargoedAccess.value
assert new_asset.blob.embargoed
assert new_asset.zarr is None
# Adding an Asset should trigger a revalidation
assert draft_version.status == Version.Status.PENDING
@pytest.mark.django_db
def test_asset_create_unembargo_in_progress(
api_client, user, draft_version_factory, dandiset_factory, embargoed_asset_blob
):
dandiset = dandiset_factory(embargo_status=Dandiset.EmbargoStatus.UNEMBARGOING)
draft_version = draft_version_factory(dandiset=dandiset)
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-nwb',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': embargoed_asset_blob.blob_id},
format='json',
)
assert resp.status_code == 400
@pytest.mark.django_db(transaction=True)
def test_asset_create_embargoed_asset_blob_open_dandiset(
api_client, user, draft_version, embargoed_asset_blob, mocker
):
# Ensure that creating an asset in an open dandiset that points to an embargoed asset blob
# results in that asset blob being unembargoed
assert draft_version.dandiset.embargo_status == Dandiset.EmbargoStatus.OPEN
assert embargoed_asset_blob.embargoed
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-nwb',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
# Mock this so we can check that it's been called later
mocked_func = mocker.patch('dandiapi.api.services.embargo.remove_asset_blob_embargoed_tag')
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': embargoed_asset_blob.blob_id},
format='json',
).json()
new_asset = Asset.objects.get(asset_id=resp['asset_id'])
assert new_asset.blob == embargoed_asset_blob
assert not new_asset.blob.embargoed
# We can't test that the tags were correctly removed in a testing env, but we can test that the
# function which removes the tags was correctly invoked
mocked_func.assert_called_once()
# Adding an Asset should trigger a revalidation
assert draft_version.status == Version.Status.PENDING
@pytest.mark.django_db
def test_asset_create_zarr(api_client, user, draft_version, zarr_archive):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-zarr',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'zarr_id': zarr_archive.zarr_id},
format='json',
).json()
new_asset = Asset.objects.get(asset_id=resp['asset_id'])
assert resp == {
'asset_id': UUID_RE,
'path': path,
'size': zarr_archive.size,
'blob': None,
'zarr': zarr_archive.zarr_id,
'created': TIMESTAMP_RE,
'modified': TIMESTAMP_RE,
'metadata': new_asset.full_metadata,
}
for key in metadata:
assert resp['metadata'][key] == metadata[key]
# The version modified date should be updated
start_time = draft_version.modified
draft_version.refresh_from_db()
end_time = draft_version.modified
assert start_time < end_time
# Asset should be pending, since checksum isn't calculated
assert new_asset.status == Asset.Status.PENDING
# Adding an Asset should trigger a revalidation
assert draft_version.status == Version.Status.PENDING
# Must use transaction=True to ensure `on_commit` funcs are called
@pytest.mark.django_db(transaction=True)
def test_asset_create_zarr_validated(
api_client, user, draft_version, zarr_archive, zarr_file_factory
):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-zarr',
'schemaKey': 'Asset',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
# Create asset
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'zarr_id': zarr_archive.zarr_id},
format='json',
).json()
asset1 = Asset.objects.get(asset_id=resp['asset_id'])
# Create second asset that points to the same zarr
metadata['1'] = 3
metadata['path'] = 'test/create/asset2.txt'
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'zarr_id': zarr_archive.zarr_id},
format='json',
).json()
asset2 = Asset.objects.get(asset_id=resp['asset_id'])
# Add zarr file and finalize
zarr_file_factory(zarr_archive=zarr_archive)
api_client.post(f'/api/zarr/{zarr_archive.zarr_id}/finalize/')
validate_pending_asset_metadata()
asset1.refresh_from_db()
asset2.refresh_from_db()
assert asset1.status == Asset.Status.VALID
assert asset2.status == Asset.Status.VALID
@pytest.mark.django_db
def test_asset_create_zarr_wrong_dandiset(
api_client, user, draft_version, zarr_archive_factory, dandiset_factory
):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
zarr_dandiset = dandiset_factory()
zarr_archive = zarr_archive_factory(dandiset=zarr_dandiset)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-zarr',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'zarr_id': zarr_archive.zarr_id},
format='json',
)
assert resp.status_code == 400
assert resp.json() == 'The zarr archive belongs to a different dandiset'
@pytest.mark.django_db
def test_asset_create_no_blob_or_zarr(api_client, user, draft_version):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-zarr',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata},
format='json',
)
assert resp.status_code == 400
assert resp.json() == {'blob_id': ['Exactly one of blob_id or zarr_id must be specified.']}
@pytest.mark.django_db
def test_asset_create_blob_and_zarr(api_client, user, draft_version, asset_blob, zarr_archive):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {
'encodingFormat': 'application/x-zarr',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
}
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': asset_blob.blob_id, 'zarr_id': zarr_archive.zarr_id},
format='json',
)
assert resp.status_code == 400
assert resp.json() == {'blob_id': ['Exactly one of blob_id or zarr_id must be specified.']}
@pytest.mark.django_db
def test_asset_create_no_valid_blob(api_client, user, draft_version):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)
path = 'test/create/asset.txt'
metadata = {'path': path, 'foo': ['bar', 'baz'], '1': 2}
uuid = uuid4()
resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': uuid},