13561: Sync selected fields changes with older versions, with tests.
[arvados.git] / services / api / test / unit / collection_test.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'test_helper'
6 require 'sweep_trashed_objects'
7
8 class CollectionTest < ActiveSupport::TestCase
9   include DbCurrentTime
10
11   def create_collection name, enc=nil
12     txt = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:#{name}.txt\n"
13     txt.force_encoding(enc) if enc
14     return Collection.create(manifest_text: txt, name: name)
15   end
16
17   test 'accept ASCII manifest_text' do
18     act_as_system_user do
19       c = create_collection 'foo', Encoding::US_ASCII
20       assert c.valid?
21     end
22   end
23
24   test 'accept UTF-8 manifest_text' do
25     act_as_system_user do
26       c = create_collection "f\xc3\x98\xc3\x98", Encoding::UTF_8
27       assert c.valid?
28     end
29   end
30
31   test 'refuse manifest_text with invalid UTF-8 byte sequence' do
32     act_as_system_user do
33       c = create_collection "f\xc8o", Encoding::UTF_8
34       assert !c.valid?
35       assert_equal [:manifest_text], c.errors.messages.keys
36       assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
37     end
38   end
39
40   test 'refuse manifest_text with non-UTF-8 encoding' do
41     act_as_system_user do
42       c = create_collection "f\xc8o", Encoding::ASCII_8BIT
43       assert !c.valid?
44       assert_equal [:manifest_text], c.errors.messages.keys
45       assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
46     end
47   end
48
49   [
50     ". 0:0:foo.txt",
51     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
52     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
53     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
54   ].each do |manifest_text|
55     test "create collection with invalid manifest text #{manifest_text} and expect error" do
56       act_as_system_user do
57         c = Collection.create(manifest_text: manifest_text)
58         assert !c.valid?
59       end
60     end
61   end
62
63   [
64     nil,
65     "",
66     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
67   ].each do |manifest_text|
68     test "create collection with valid manifest text #{manifest_text.inspect} and expect success" do
69       act_as_system_user do
70         c = Collection.create(manifest_text: manifest_text)
71         assert c.valid?
72       end
73     end
74   end
75
76   [
77     ". 0:0:foo.txt",
78     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
79     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
80     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
81   ].each do |manifest_text|
82     test "update collection with invalid manifest text #{manifest_text} and expect error" do
83       act_as_system_user do
84         c = create_collection 'foo', Encoding::US_ASCII
85         assert c.valid?
86
87         c.update_attribute 'manifest_text', manifest_text
88         assert !c.valid?
89       end
90     end
91   end
92
93   [
94     nil,
95     "",
96     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
97   ].each do |manifest_text|
98     test "update collection with valid manifest text #{manifest_text.inspect} and expect success" do
99       act_as_system_user do
100         c = create_collection 'foo', Encoding::US_ASCII
101         assert c.valid?
102
103         c.update_attribute 'manifest_text', manifest_text
104         assert c.valid?
105       end
106     end
107   end
108
109   test "uuid updates on current version make older versions update their pointers" do
110     Rails.configuration.collection_versioning = true
111     act_as_system_user do
112       # Set up initial collection
113       c = create_collection 'foo', Encoding::US_ASCII
114       assert c.valid?
115       assert_equal 1, c.version
116       # Make changes so that a new version is created
117       c.update_attributes!({'name' => 'bar'})
118       c.reload
119       assert_equal 2, c.version
120       assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
121       new_uuid = 'zzzzz-4zz18-somefakeuuidnow'
122       assert_empty Collection.where(uuid: new_uuid)
123       # Update UUID on current version, check that both collections point to it
124       c.update_attributes!({'uuid' => new_uuid})
125       c.reload
126       assert_equal new_uuid, c.uuid
127       assert_equal 2, Collection.where(current_version_uuid: new_uuid).count
128     end
129   end
130
131   [
132     ['owner_uuid', 'zzzzz-tpzed-d9tiejq69daie8f', 'zzzzz-tpzed-xurymjxw79nv3jz'],
133     ['replication_desired', 2, 3],
134     ['storage_classes_desired', ['hot'], ['archive']],
135     ['is_trashed', true, false],
136   ].each do |attr, first_val, second_val|
137     test "sync #{attr} with older versions" do
138       Rails.configuration.collection_versioning = true
139       act_as_system_user do
140         # Set up initial collection
141         c = create_collection 'foo', Encoding::US_ASCII
142         assert c.valid?
143         assert_equal 1, c.version
144         assert_not_equal first_val, c.attributes[attr]
145         # Make changes so that a new version is created and a synced field is
146         # updated on both
147         c.update_attributes!({'name' => 'bar', attr => first_val})
148         c.reload
149         assert_equal 2, c.version
150         assert_equal first_val, c.attributes[attr]
151         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
152         assert_equal first_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
153         # Only make an update on the same synced field & check that the previously
154         # created version also gets it.
155         c.update_attributes!({attr => second_val})
156         c.reload
157         assert_equal 2, c.version
158         assert_equal second_val, c.attributes[attr]
159         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
160         assert_equal second_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
161       end
162     end
163   end
164
165   [
166     [false, 'name', 'bar', false],
167     [false, 'description', 'The quick brown fox jumps over the lazy dog', false],
168     [false, 'properties', {'new_version' => true}, false],
169     [false, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", false],
170     [true, 'name', 'bar', true],
171     [true, 'description', 'The quick brown fox jumps over the lazy dog', true],
172     [true, 'properties', {'new_version' => true}, true],
173     [true, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", true],
174     # Non-versionable attribute updates shouldn't create new versions
175     [true, 'replication_desired', 5, false],
176     [false, 'replication_desired', 5, false],
177   ].each do |versioning, attr, val, new_version_expected|
178     test "update #{attr} with versioning #{versioning ? '' : 'not '}enabled should #{new_version_expected ? '' : 'not '}create a new version" do
179       Rails.configuration.collection_versioning = versioning
180       act_as_system_user do
181         # Create initial collection
182         c = create_collection 'foo', Encoding::US_ASCII
183         assert c.valid?
184         assert_equal 'foo', c.name
185
186         # Check current version attributes
187         assert_equal 1, c.version
188         assert_equal c.uuid, c.current_version_uuid
189
190         # Update attribute and check if version number should be incremented
191         old_value = c.attributes[attr]
192         c.update_attributes!({attr => val})
193         assert_equal new_version_expected, c.version == 2
194         assert_equal val, c.attributes[attr]
195
196         if versioning && new_version_expected
197           # Search for the snapshot & previous value
198           assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
199           s = Collection.where(current_version_uuid: c.uuid, version: 1).first
200           assert_not_nil s
201           assert_equal old_value, s.attributes[attr]
202         else
203           # If versioning is disabled or no versionable attribute was updated,
204           # only the current version should exist
205           assert_equal 1, Collection.where(current_version_uuid: c.uuid).count
206           assert_equal c, Collection.where(current_version_uuid: c.uuid).first
207         end
208       end
209     end
210   end
211
212   test 'with versioning enabled, simultaneous updates increment version correctly' do
213     Rails.configuration.collection_versioning = true
214     act_as_system_user do
215       # Create initial collection
216       col = create_collection 'foo', Encoding::US_ASCII
217       assert col.valid?
218       assert_equal 1, col.version
219
220       # Simulate simultaneous updates
221       c1 = Collection.where(uuid: col.uuid).first
222       assert_equal 1, c1.version
223       c1.name = 'bar'
224       c2 = Collection.where(uuid: col.uuid).first
225       c2.description = 'foo collection'
226       c1.save!
227       assert_equal 1, c2.version
228       # with_lock forces a reload, so this shouldn't produce an unique violation error
229       c2.save!
230       assert_equal 3, c2.version
231       assert_equal 'foo collection', c2.description
232     end
233   end
234
235   test 'create and update collection and verify file_names' do
236     act_as_system_user do
237       c = create_collection 'foo', Encoding::US_ASCII
238       assert c.valid?
239       created_file_names = c.file_names
240       assert created_file_names
241       assert_match(/foo.txt/, c.file_names)
242
243       c.update_attribute 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo2.txt\n"
244       assert_not_equal created_file_names, c.file_names
245       assert_match(/foo2.txt/, c.file_names)
246     end
247   end
248
249   [
250     [2**8, false],
251     [2**18, true],
252   ].each do |manifest_size, allow_truncate|
253     test "create collection with manifest size #{manifest_size} with allow_truncate=#{allow_truncate},
254           and not expect exceptions even on very large manifest texts" do
255       # file_names has a max size, hence there will be no errors even on large manifests
256       act_as_system_user do
257         manifest_text = ''
258         index = 0
259         while manifest_text.length < manifest_size
260           manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
261           index += 1
262         end
263         manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
264         c = Collection.create(manifest_text: manifest_text)
265
266         assert c.valid?
267         assert c.file_names
268         assert_match(/veryverylongfilename0000000000001.txt/, c.file_names)
269         assert_match(/veryverylongfilename0000000000002.txt/, c.file_names)
270         if not allow_truncate
271           assert_match(/veryverylastfilename/, c.file_names)
272           assert_match(/laststreamname/, c.file_names)
273         end
274       end
275     end
276   end
277
278   test "full text search for collections" do
279     # file_names column does not get populated when fixtures are loaded, hence setup test data
280     act_as_system_user do
281       Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n")
282       Collection.create(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
283       Collection.create(manifest_text: ". 85877ca2d7e05498dd3d109baf2df106+95+A3a4e26a366ee7e4ed3e476ccf05354761be2e4ae@545a9920 0:95:file_in_subdir1\n./subdir2/subdir3 2bbc341c702df4d8f42ec31f16c10120+64+A315d7e7bad2ce937e711fc454fae2d1194d14d64@545a9920 0:32:file1.txt 32:32:file2.txt\n./subdir2/subdir3/subdir4 2bbc341c702df4d8f42ec31f16c10120+64+A315d7e7bad2ce937e711fc454fae2d1194d14d64@545a9920 0:32:file3.txt 32:32:file4.txt\n")
284     end
285
286     [
287       ['foo', true],
288       ['foo bar', false],                     # no collection matching both
289       ['foo&bar', false],                     # no collection matching both
290       ['foo|bar', true],                      # works only no spaces between the words
291       ['Gnu public', true],                   # both prefixes found, though not consecutively
292       ['Gnu&public', true],                   # both prefixes found, though not consecutively
293       ['file4', true],                        # prefix match
294       ['file4.txt', true],                    # whole string match
295       ['filex', false],                       # no such prefix
296       ['subdir', true],                       # prefix matches
297       ['subdir2', true],
298       ['subdir2/', true],
299       ['subdir2/subdir3', true],
300       ['subdir2/subdir3/subdir4', true],
301       ['subdir2 file4', true],                # look for both prefixes
302       ['subdir4', false],                     # not a prefix match
303     ].each do |search_filter, expect_results|
304       search_filters = search_filter.split.each {|s| s.concat(':*')}.join('&')
305       results = Collection.where("#{Collection.full_text_tsvector} @@ to_tsquery(?)",
306                                  "#{search_filters}")
307       if expect_results
308         refute_empty results
309       else
310         assert_empty results
311       end
312     end
313   end
314
315   test 'portable data hash with missing size hints' do
316     [[". d41d8cd98f00b204e9800998ecf8427e+0+Bar 0:0:x\n",
317       ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"],
318      [". d41d8cd98f00b204e9800998ecf8427e+Foo 0:0:x\n",
319       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
320      [". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n",
321       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
322     ].each do |unportable, portable|
323       c = Collection.new(manifest_text: unportable)
324       assert c.valid?
325       assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
326                    c.portable_data_hash)
327     end
328   end
329
330   pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
331   pdhmd5 = Digest::MD5.hexdigest pdhmanifest
332   [[true, nil],
333    [true, pdhmd5],
334    [true, pdhmd5+'+12345'],
335    [true, pdhmd5+'+'+pdhmanifest.length.to_s],
336    [true, pdhmd5+'+12345+Foo'],
337    [true, pdhmd5+'+Foo'],
338    [false, Digest::MD5.hexdigest(pdhmanifest.strip)],
339    [false, Digest::MD5.hexdigest(pdhmanifest.strip)+'+'+pdhmanifest.length.to_s],
340    [false, pdhmd5[0..30]],
341    [false, pdhmd5[0..30]+'z'],
342    [false, pdhmd5[0..24]+'000000000'],
343    [false, pdhmd5[0..24]+'000000000+0']].each do |isvalid, pdh|
344     test "portable_data_hash #{pdh.inspect} valid? == #{isvalid}" do
345       c = Collection.new manifest_text: pdhmanifest, portable_data_hash: pdh
346       assert_equal isvalid, c.valid?, c.errors.full_messages.to_s
347     end
348   end
349
350   test "storage_classes_desired cannot be empty" do
351     act_as_user users(:active) do
352       c = collections(:collection_owned_by_active)
353       c.update_attributes storage_classes_desired: ["hot"]
354       assert_equal ["hot"], c.storage_classes_desired
355       assert_raise ArvadosModel::InvalidStateTransitionError do
356         c.update_attributes storage_classes_desired: []
357       end
358     end
359   end
360
361   test "storage classes lists should only contain non-empty strings" do
362     c = collections(:storage_classes_desired_default_unconfirmed)
363     act_as_user users(:admin) do
364       assert c.update_attributes(storage_classes_desired: ["default", "a_string"],
365                                  storage_classes_confirmed: ["another_string"])
366       [
367         ["storage_classes_desired", ["default", 42]],
368         ["storage_classes_confirmed", [{the_answer: 42}]],
369         ["storage_classes_desired", ["default", ""]],
370         ["storage_classes_confirmed", [""]],
371       ].each do |attr, val|
372         assert_raise ArvadosModel::InvalidStateTransitionError do
373           assert c.update_attributes({attr => val})
374         end
375       end
376     end
377   end
378
379   test "storage_classes_confirmed* can be set by admin user" do
380     c = collections(:storage_classes_desired_default_unconfirmed)
381     act_as_user users(:admin) do
382       assert c.update_attributes(storage_classes_confirmed: ["default"],
383                                  storage_classes_confirmed_at: Time.now)
384     end
385   end
386
387   test "storage_classes_confirmed* cannot be set by non-admin user" do
388     act_as_user users(:active) do
389       c = collections(:storage_classes_desired_default_unconfirmed)
390       # Cannot set just one at a time.
391       assert_raise ArvadosModel::PermissionDeniedError do
392         c.update_attributes storage_classes_confirmed: ["default"]
393       end
394       c.reload
395       assert_raise ArvadosModel::PermissionDeniedError do
396         c.update_attributes storage_classes_confirmed_at: Time.now
397       end
398       # Cannot set bot at once, either.
399       c.reload
400       assert_raise ArvadosModel::PermissionDeniedError do
401         assert c.update_attributes(storage_classes_confirmed: ["default"],
402                                    storage_classes_confirmed_at: Time.now)
403       end
404     end
405   end
406
407   test "storage_classes_confirmed* can be cleared (but only together) by non-admin user" do
408     act_as_user users(:active) do
409       c = collections(:storage_classes_desired_default_confirmed_default)
410       # Cannot clear just one at a time.
411       assert_raise ArvadosModel::PermissionDeniedError do
412         c.update_attributes storage_classes_confirmed: []
413       end
414       c.reload
415       assert_raise ArvadosModel::PermissionDeniedError do
416         c.update_attributes storage_classes_confirmed_at: nil
417       end
418       # Can clear both at once.
419       c.reload
420       assert c.update_attributes(storage_classes_confirmed: [],
421                                  storage_classes_confirmed_at: nil)
422     end
423   end
424
425   [0, 2, 4, nil].each do |ask|
426     test "set replication_desired to #{ask.inspect}" do
427       Rails.configuration.default_collection_replication = 2
428       act_as_user users(:active) do
429         c = collections(:replication_undesired_unconfirmed)
430         c.update_attributes replication_desired: ask
431         assert_equal ask, c.replication_desired
432       end
433     end
434   end
435
436   test "replication_confirmed* can be set by admin user" do
437     c = collections(:replication_desired_2_unconfirmed)
438     act_as_user users(:admin) do
439       assert c.update_attributes(replication_confirmed: 2,
440                                  replication_confirmed_at: Time.now)
441     end
442   end
443
444   test "replication_confirmed* cannot be set by non-admin user" do
445     act_as_user users(:active) do
446       c = collections(:replication_desired_2_unconfirmed)
447       # Cannot set just one at a time.
448       assert_raise ArvadosModel::PermissionDeniedError do
449         c.update_attributes replication_confirmed: 1
450       end
451       assert_raise ArvadosModel::PermissionDeniedError do
452         c.update_attributes replication_confirmed_at: Time.now
453       end
454       # Cannot set both at once, either.
455       assert_raise ArvadosModel::PermissionDeniedError do
456         c.update_attributes(replication_confirmed: 1,
457                             replication_confirmed_at: Time.now)
458       end
459     end
460   end
461
462   test "replication_confirmed* can be cleared (but only together) by non-admin user" do
463     act_as_user users(:active) do
464       c = collections(:replication_desired_2_confirmed_2)
465       # Cannot clear just one at a time.
466       assert_raise ArvadosModel::PermissionDeniedError do
467         c.update_attributes replication_confirmed: nil
468       end
469       c.reload
470       assert_raise ArvadosModel::PermissionDeniedError do
471         c.update_attributes replication_confirmed_at: nil
472       end
473       # Can clear both at once.
474       c.reload
475       assert c.update_attributes(replication_confirmed: nil,
476                                  replication_confirmed_at: nil)
477     end
478   end
479
480   test "clear replication_confirmed* when introducing a new block in manifest" do
481     c = collections(:replication_desired_2_confirmed_2)
482     act_as_user users(:active) do
483       assert c.update_attributes(manifest_text: collections(:user_agreement).signed_manifest_text)
484       assert_nil c.replication_confirmed
485       assert_nil c.replication_confirmed_at
486     end
487   end
488
489   test "don't clear replication_confirmed* when just renaming a file" do
490     c = collections(:replication_desired_2_confirmed_2)
491     act_as_user users(:active) do
492       new_manifest = c.signed_manifest_text.sub(':bar', ':foo')
493       assert c.update_attributes(manifest_text: new_manifest)
494       assert_equal 2, c.replication_confirmed
495       assert_not_nil c.replication_confirmed_at
496     end
497   end
498
499   test "don't clear replication_confirmed* when just deleting a data block" do
500     c = collections(:replication_desired_2_confirmed_2)
501     act_as_user users(:active) do
502       new_manifest = c.signed_manifest_text
503       new_manifest.sub!(/ \S+:bar/, '')
504       new_manifest.sub!(/ acbd\S+/, '')
505
506       # Confirm that we did just remove a block from the manifest (if
507       # not, this test would pass without testing the relevant case):
508       assert_operator new_manifest.length+40, :<, c.signed_manifest_text.length
509
510       assert c.update_attributes(manifest_text: new_manifest)
511       assert_equal 2, c.replication_confirmed
512       assert_not_nil c.replication_confirmed_at
513     end
514   end
515
516   test 'signature expiry does not exceed trash_at' do
517     act_as_user users(:active) do
518       t0 = db_current_time
519       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
520       c.update_attributes! trash_at: (t0 + 1.hours)
521       c.reload
522       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
523       assert_operator sig_exp.to_i, :<=, (t0 + 1.hours).to_i
524     end
525   end
526
527   test 'far-future expiry date cannot be used to circumvent configured permission ttl' do
528     act_as_user users(:active) do
529       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n",
530                              name: 'foo',
531                              trash_at: db_current_time + 1.years)
532       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
533       expect_max_sig_exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
534       assert_operator c.trash_at.to_i, :>, expect_max_sig_exp
535       assert_operator sig_exp.to_i, :<=, expect_max_sig_exp
536     end
537   end
538
539   test "create collection with properties" do
540     act_as_system_user do
541       c = Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n",
542                             properties: {'property_1' => 'value_1'})
543       assert c.valid?
544       assert_equal 'value_1', c.properties['property_1']
545     end
546   end
547
548   test 'create, delete, recreate collection with same name and owner' do
549     act_as_user users(:active) do
550       # create collection with name
551       c = Collection.create(manifest_text: '',
552                             name: "test collection name")
553       assert c.valid?
554       uuid = c.uuid
555
556       c = Collection.readable_by(current_user).where(uuid: uuid)
557       assert_not_empty c, 'Should be able to find live collection'
558
559       # mark collection as expired
560       c.first.update_attributes!(trash_at: Time.new.strftime("%Y-%m-%d"))
561       c = Collection.readable_by(current_user).where(uuid: uuid)
562       assert_empty c, 'Should not be able to find expired collection'
563
564       # recreate collection with the same name
565       c = Collection.create(manifest_text: '',
566                             name: "test collection name")
567       assert c.valid?
568     end
569   end
570
571   test 'trash_at cannot be set too far in the past' do
572     act_as_user users(:active) do
573       t0 = db_current_time
574       c = Collection.create!(manifest_text: '', name: 'foo')
575       c.update_attributes! trash_at: (t0 - 2.weeks)
576       c.reload
577       assert_operator c.trash_at, :>, t0
578     end
579   end
580
581   now = Time.now
582   [['trash-to-delete interval negative',
583     :collection_owned_by_active,
584     {trash_at: now+2.weeks, delete_at: now},
585     {state: :invalid}],
586    ['now-to-delete interval short',
587     :collection_owned_by_active,
588     {trash_at: now+3.days, delete_at: now+7.days},
589     {state: :trash_future}],
590    ['now-to-delete interval short, trash=delete',
591     :collection_owned_by_active,
592     {trash_at: now+3.days, delete_at: now+3.days},
593     {state: :trash_future}],
594    ['trash-to-delete interval ok',
595     :collection_owned_by_active,
596     {trash_at: now, delete_at: now+15.days},
597     {state: :trash_now}],
598    ['trash-to-delete interval short, but far enough in future',
599     :collection_owned_by_active,
600     {trash_at: now+13.days, delete_at: now+15.days},
601     {state: :trash_future}],
602    ['trash by setting is_trashed bool',
603     :collection_owned_by_active,
604     {is_trashed: true},
605     {state: :trash_now}],
606    ['trash in future by setting just trash_at',
607     :collection_owned_by_active,
608     {trash_at: now+1.week},
609     {state: :trash_future}],
610    ['trash in future by setting trash_at and delete_at',
611     :collection_owned_by_active,
612     {trash_at: now+1.week, delete_at: now+4.weeks},
613     {state: :trash_future}],
614    ['untrash by clearing is_trashed bool',
615     :expired_collection,
616     {is_trashed: false},
617     {state: :not_trash}],
618   ].each do |test_name, fixture_name, updates, expect|
619     test test_name do
620       act_as_user users(:active) do
621         min_exp = (db_current_time +
622                    Rails.configuration.blob_signature_ttl.seconds)
623         if fixture_name == :expired_collection
624           # Fixture-finder shorthand doesn't find trashed collections
625           # because they're not in the default scope.
626           c = Collection.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
627         else
628           c = collections(fixture_name)
629         end
630         updates_ok = c.update_attributes(updates)
631         expect_valid = expect[:state] != :invalid
632         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
633         case expect[:state]
634         when :invalid
635           refute c.valid?
636         when :trash_now
637           assert c.is_trashed
638           assert_not_nil c.trash_at
639           assert_operator c.trash_at, :<=, db_current_time
640           assert_not_nil c.delete_at
641           assert_operator c.delete_at, :>=, min_exp
642         when :trash_future
643           refute c.is_trashed
644           assert_not_nil c.trash_at
645           assert_operator c.trash_at, :>, db_current_time
646           assert_not_nil c.delete_at
647           assert_operator c.delete_at, :>=, c.trash_at
648           # Currently this minimum interval is needed to prevent early
649           # garbage collection:
650           assert_operator c.delete_at, :>=, min_exp
651         when :not_trash
652           refute c.is_trashed
653           assert_nil c.trash_at
654           assert_nil c.delete_at
655         else
656           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
657         end
658       end
659     end
660   end
661
662   test 'default trash interval > blob signature ttl' do
663     Rails.configuration.default_trash_lifetime = 86400 * 21 # 3 weeks
664     start = db_current_time
665     act_as_user users(:active) do
666       c = Collection.create!(manifest_text: '', name: 'foo')
667       c.update_attributes!(trash_at: start + 86400.seconds)
668       assert_operator c.delete_at, :>=, start + (86400*22).seconds
669       assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
670       c.destroy
671
672       c = Collection.create!(manifest_text: '', name: 'foo')
673       c.update_attributes!(is_trashed: true)
674       assert_operator c.delete_at, :>=, start + (86400*21).seconds
675     end
676   end
677
678   test "find_all_for_docker_image resolves names that look like hashes" do
679     coll_list = Collection.
680       find_all_for_docker_image('a' * 64, nil, [users(:active)])
681     coll_uuids = coll_list.map(&:uuid)
682     assert_includes(coll_uuids, collections(:docker_image).uuid)
683   end
684
685   test "move collections to trash in SweepTrashedObjects" do
686     c = collections(:trashed_on_next_sweep)
687     refute_empty Collection.where('uuid=? and is_trashed=false', c.uuid)
688     assert_raises(ActiveRecord::RecordNotUnique) do
689       act_as_user users(:active) do
690         Collection.create!(owner_uuid: c.owner_uuid,
691                            name: c.name)
692       end
693     end
694     SweepTrashedObjects.sweep_now
695     c = Collection.where('uuid=? and is_trashed=true', c.uuid).first
696     assert c
697     act_as_user users(:active) do
698       assert Collection.create!(owner_uuid: c.owner_uuid,
699                                 name: c.name)
700     end
701   end
702
703   test "delete collections in SweepTrashedObjects" do
704     uuid = 'zzzzz-4zz18-3u1p5umicfpqszp' # deleted_on_next_sweep
705     assert_not_empty Collection.where(uuid: uuid)
706     SweepTrashedObjects.sweep_now
707     assert_empty Collection.where(uuid: uuid)
708   end
709
710   test "delete referring links in SweepTrashedObjects" do
711     uuid = collections(:trashed_on_next_sweep).uuid
712     act_as_system_user do
713       Link.create!(head_uuid: uuid,
714                    tail_uuid: system_user_uuid,
715                    link_class: 'whatever',
716                    name: 'something')
717     end
718     past = db_current_time
719     Collection.where(uuid: uuid).
720       update_all(is_trashed: true, trash_at: past, delete_at: past)
721     assert_not_empty Collection.where(uuid: uuid)
722     SweepTrashedObjects.sweep_now
723     assert_empty Collection.where(uuid: uuid)
724   end
725 end