1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 require 'fix_collection_versions_timestamps'
8 class CollectionTest < ActiveSupport::TestCase
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)
17 test 'accept ASCII manifest_text' do
19 c = create_collection 'foo', Encoding::US_ASCII
24 test 'accept UTF-8 manifest_text' do
26 c = create_collection "f\xc3\x98\xc3\x98", Encoding::UTF_8
31 test 'refuse manifest_text with invalid UTF-8 byte sequence' do
33 c = create_collection "f\xc8o", Encoding::UTF_8
35 assert_equal [:manifest_text], c.errors.messages.keys
36 assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
40 test 'refuse manifest_text with non-UTF-8 encoding' do
42 c = create_collection "f\xc8o", Encoding::ASCII_8BIT
44 assert_equal [:manifest_text], c.errors.messages.keys
45 assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
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
57 c = Collection.create(manifest_text: manifest_text)
64 [". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", 1, 34],
65 [". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:30:foo.txt 0:30:foo1.txt 0:30:foo2.txt 0:30:foo3.txt 0:30:foo4.txt\n", 5, 184],
66 [". d41d8cd98f00b204e9800998ecf8427e 0:0:.\n", 0, 0]
67 ].each do |manifest, count, size|
68 test "file stats on create collection with #{manifest}" do
70 c = Collection.create(manifest_text: manifest)
71 assert_equal count, c.file_count
72 assert_equal size, c.file_size_total
77 test "file stats cannot be changed unless through manifest change" do
79 # Direct changes to file stats should be ignored
80 c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n")
82 c.file_size_total = 30
84 assert_equal 1, c.file_count
85 assert_equal 34, c.file_size_total
87 # File stats specified on create should be ignored and overwritten
88 c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count: 10, file_size_total: 10)
90 assert_equal 1, c.file_count
91 assert_equal 34, c.file_size_total
93 # Updating the manifest should change file stats
94 c.update(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:34:foo2.txt\n")
96 assert_equal 2, c.file_count
97 assert_equal 68, c.file_size_total
99 # Updating file stats and the manifest should use manifest values
100 c.update(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count:10, file_size_total: 10)
102 assert_equal 1, c.file_count
103 assert_equal 34, c.file_size_total
105 # Updating just the file stats should be ignored
106 c.update(file_count: 10, file_size_total: 10)
108 assert_equal 1, c.file_count
109 assert_equal 34, c.file_size_total
116 ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
117 ].each do |manifest_text|
118 test "create collection with valid manifest text #{manifest_text.inspect} and expect success" do
119 act_as_system_user do
120 c = Collection.create(manifest_text: manifest_text)
128 ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
129 "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
130 ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
131 ].each do |manifest_text|
132 test "update collection with invalid manifest text #{manifest_text} and expect error" do
133 act_as_system_user do
134 c = create_collection 'foo', Encoding::US_ASCII
137 c.update_attribute 'manifest_text', manifest_text
146 ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
147 ].each do |manifest_text|
148 test "update collection with valid manifest text #{manifest_text.inspect} and expect success" do
149 act_as_system_user do
150 c = create_collection 'foo', Encoding::US_ASCII
153 c.update_attribute 'manifest_text', manifest_text
159 test "auto-create version after idle setting" do
160 Rails.configuration.Collections.CollectionVersioning = true
161 Rails.configuration.Collections.PreserveVersionIfIdle = 600 # 10 minutes
162 act_as_user users(:active) do
163 # Set up initial collection
164 c = create_collection 'foo', Encoding::US_ASCII
166 assert_equal 1, c.version
167 assert_equal false, c.preserve_version
168 # Make a versionable update, it shouldn't create a new version yet
169 c.update!({'name' => 'bar'})
171 assert_equal 'bar', c.name
172 assert_equal 1, c.version
173 # Update modified_at to trigger a version auto-creation
174 fifteen_min_ago = Time.now - 15.minutes
175 c.update_column('modified_at', fifteen_min_ago) # Update without validations/callbacks
177 assert_equal fifteen_min_ago.to_i, c.modified_at.to_i
178 c.update!({'name' => 'baz'})
180 assert_equal 'baz', c.name
181 assert_equal 2, c.version
182 # Make another update, no new version should be created
183 c.update!({'name' => 'foobar'})
185 assert_equal 'foobar', c.name
186 assert_equal 2, c.version
187 # Simulate a keep-balance run and trigger a new versionable update
188 # This tests bug #18005
189 assert_nil c.replication_confirmed
190 assert_nil c.replication_confirmed_at
191 # Updates without validations/callbacks
192 c.update_column('modified_at', fifteen_min_ago)
193 c.update_column('replication_confirmed_at', Time.now)
194 c.update_column('replication_confirmed', 2)
196 assert_equal fifteen_min_ago.to_i, c.modified_at.to_i
197 assert_not_nil c.replication_confirmed_at
198 assert_not_nil c.replication_confirmed
199 # Make the versionable update
200 c.update!({'name' => 'foobarbaz'})
202 assert_equal 'foobarbaz', c.name
203 assert_equal 3, c.version
207 test "preserve_version updates" do
208 Rails.configuration.Collections.CollectionVersioning = true
209 Rails.configuration.Collections.PreserveVersionIfIdle = -1 # disabled
210 act_as_user users(:active) do
211 # Set up initial collection
212 c = create_collection 'foo', Encoding::US_ASCII
214 assert_equal 1, c.version
215 assert_equal false, c.preserve_version
216 # This update shouldn't produce a new version, as the idle time is not up
221 assert_equal 1, c.version
222 assert_equal 'bar', c.name
223 assert_equal false, c.preserve_version
224 # This update should produce a new version, even if the idle time is not up
225 # and also keep the preserve_version=true flag to persist it.
228 'preserve_version' => true
231 assert_equal 2, c.version
232 assert_equal 'baz', c.name
233 assert_equal true, c.preserve_version
234 # Make sure preserve_version is not disabled after being enabled, unless
235 # a new version is created.
236 # This is a non-versionable update
238 'preserve_version' => false,
239 'replication_desired' => 2
242 assert_equal 2, c.version
243 assert_equal 2, c.replication_desired
244 assert_equal true, c.preserve_version
245 # This is a versionable update
247 'preserve_version' => false,
251 assert_equal 3, c.version
252 assert_equal false, c.preserve_version
253 assert_equal 'foobar', c.name
254 # Flipping only 'preserve_version' to true doesn't create a new version
255 c.update!({'preserve_version' => true})
257 assert_equal 3, c.version
258 assert_equal true, c.preserve_version
262 test "preserve_version updates don't change modified_at timestamp" do
263 act_as_user users(:active) do
264 c = create_collection 'foo', Encoding::US_ASCII
266 assert_equal false, c.preserve_version
267 modified_at = c.modified_at.to_f
268 c.update!({'preserve_version' => true})
270 assert_equal true, c.preserve_version
271 assert_equal modified_at, c.modified_at.to_f,
272 'preserve_version updates should not trigger modified_at changes'
278 ['current_version_uuid', 'zzzzz-4zz18-bv31uwvy3neko21'],
279 ].each do |name, new_value|
280 test "'#{name}' updates on current version collections are not allowed" do
281 act_as_user users(:active) do
282 # Set up initial collection
283 c = create_collection 'foo', Encoding::US_ASCII
285 assert_equal 1, c.version
287 assert_raises(ActiveRecord::RecordInvalid) do
296 test "uuid updates on current version make older versions update their pointers" do
297 Rails.configuration.Collections.CollectionVersioning = true
298 Rails.configuration.Collections.PreserveVersionIfIdle = 0
299 act_as_system_user do
300 # Set up initial collection
301 c = create_collection 'foo', Encoding::US_ASCII
303 assert_equal 1, c.version
304 # Make changes so that a new version is created
305 c.update!({'name' => 'bar'})
307 assert_equal 2, c.version
308 assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
309 new_uuid = 'zzzzz-4zz18-somefakeuuidnow'
310 assert_empty Collection.where(uuid: new_uuid)
311 # Update UUID on current version, check that both collections point to it
312 c.update!({'uuid' => new_uuid})
314 assert_equal new_uuid, c.uuid
315 assert_equal 2, Collection.where(current_version_uuid: new_uuid).count
319 # This test exposes a bug related to JSONB attributes, see #15725.
320 test "recently loaded collection shouldn't list changed attributes" do
321 col = Collection.where("properties != '{}'::jsonb").limit(1).first
322 refute col.properties_changed?, 'Properties field should not be seen as changed'
328 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
329 {:foo=>:bar, :lst=>[1, 3, 5, 7], :hsh=>{'baz'=>'qux', :foobar=>true, 'hsh'=>{:nested=>true}}, :delete_at=>nil},
333 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
334 {'delete_at'=>nil, 'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}},
338 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
339 {'delete_at'=>nil, 'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'foobar'=>true, 'hsh'=>{'nested'=>true}, 'baz'=>'qux'}},
343 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
344 {'foo'=>'bar', 'lst'=>[1, 3, 5, 42], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
348 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
349 {'foo'=>'bar', 'lst'=>[1, 3, 7, 5], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
353 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
354 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>false}}, 'delete_at'=>nil},
358 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
359 {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>1234567890},
361 ].each do |should_be_equal, value_1, value_2|
362 test "JSONB properties #{value_1} is#{should_be_equal ? '' : ' not'} equal to #{value_2}" do
363 act_as_user users(:active) do
364 # Set up initial collection
365 c = create_collection 'foo', Encoding::US_ASCII
367 c.update!({'properties' => value_1})
369 assert c.changes.keys.empty?
370 c.properties = value_2
372 assert c.changes.keys.empty?, "Properties #{value_1.inspect} should be equal to #{value_2.inspect}"
374 refute c.changes.keys.empty?, "Properties #{value_1.inspect} should not be equal to #{value_2.inspect}"
380 test "older versions' modified_at indicate when they're created" do
381 Rails.configuration.Collections.CollectionVersioning = true
382 Rails.configuration.Collections.PreserveVersionIfIdle = 0
383 act_as_user users(:active) do
384 # Set up initial collection
385 c = create_collection 'foo', Encoding::US_ASCII
387 original_version_modified_at = c.modified_at.to_f
388 # Make changes so that a new version is created
389 c.update!({'name' => 'bar'})
391 assert_equal 2, c.version
392 # Get the old version
393 c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
396 version_creation_datetime = c_old.modified_at.to_f
397 assert_equal c.created_at.to_f, c_old.created_at.to_f
398 assert_equal original_version_modified_at, version_creation_datetime
400 # Make update on current version so old version get the attribute synced;
401 # its modified_at should not change.
403 c.update!({'replication_desired' => new_replication})
405 assert_equal new_replication, c.replication_desired
407 assert_equal new_replication, c_old.replication_desired
408 assert_equal version_creation_datetime, c_old.modified_at.to_f
409 assert_operator c.modified_at.to_f, :>, c_old.modified_at.to_f
413 # Bug #17152 - This test relies on fixtures simulating the problem.
414 test "migration fixing collection versions' modified_at timestamps" do
415 versioned_collection_fixtures = [
416 collections(:w_a_z_file).uuid,
417 collections(:collection_owned_by_active).uuid
419 versioned_collection_fixtures.each do |uuid|
420 cols = Collection.where(current_version_uuid: uuid).order(version: :desc)
421 assert_equal cols.size, 2
422 # cols[0] -> head version // cols[1] -> old version
423 assert_operator (cols[0].modified_at.to_f - cols[1].modified_at.to_f), :==, 0
424 assert cols[1].modified_at != cols[1].created_at
426 fix_collection_versions_timestamps
427 versioned_collection_fixtures.each do |uuid|
428 cols = Collection.where(current_version_uuid: uuid).order(version: :desc)
429 assert_equal cols.size, 2
430 # cols[0] -> head version // cols[1] -> old version
431 assert_operator (cols[0].modified_at.to_f - cols[1].modified_at.to_f), :>, 1
432 assert_operator cols[1].modified_at, :==, cols[1].created_at
436 test "past versions should not be directly updatable" do
437 Rails.configuration.Collections.CollectionVersioning = true
438 Rails.configuration.Collections.PreserveVersionIfIdle = 0
439 act_as_system_user do
440 # Set up initial collection
441 c = create_collection 'foo', Encoding::US_ASCII
443 # Make changes so that a new version is created
444 c.update!({'name' => 'bar'})
446 assert_equal 2, c.version
447 # Get the old version
448 c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
450 # With collection versioning still being enabled, try to update
451 c_old.name = 'this was foo'
452 assert c_old.invalid?
454 # Try to fool the validator attempting to make c_old to look like a
455 # current version, it should also fail.
456 c_old.current_version_uuid = c_old.uuid
457 assert c_old.invalid?
459 # Now disable collection versioning, it should behave the same way
460 Rails.configuration.Collections.CollectionVersioning = false
461 c_old.name = 'this was foo'
462 assert c_old.invalid?
467 ['owner_uuid', 'zzzzz-tpzed-d9tiejq69daie8f', 'zzzzz-tpzed-xurymjxw79nv3jz'],
468 ['replication_desired', 2, 3],
469 ['storage_classes_desired', ['hot'], ['archive']],
470 ].each do |attr, first_val, second_val|
471 test "sync #{attr} with older versions" do
472 Rails.configuration.Collections.CollectionVersioning = true
473 Rails.configuration.Collections.PreserveVersionIfIdle = 0
474 act_as_system_user do
475 # Set up initial collection
476 c = create_collection 'foo', Encoding::US_ASCII
478 assert_equal 1, c.version
479 assert_not_equal first_val, c.attributes[attr]
480 # Make changes so that a new version is created and a synced field is
482 c.update!({'name' => 'bar', attr => first_val})
484 assert_equal 2, c.version
485 assert_equal first_val, c.attributes[attr]
486 assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
487 assert_equal first_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
488 # Only make an update on the same synced field & check that the previously
489 # created version also gets it.
490 c.update!({attr => second_val})
492 assert_equal 2, c.version
493 assert_equal second_val, c.attributes[attr]
494 assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
495 assert_equal second_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
501 [false, 'name', 'bar', false],
502 [false, 'description', 'The quick brown fox jumps over the lazy dog', false],
503 [false, 'properties', {'new_version' => true}, false],
504 [false, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", false],
505 [true, 'name', 'bar', true],
506 [true, 'description', 'The quick brown fox jumps over the lazy dog', true],
507 [true, 'properties', {'new_version' => true}, true],
508 [true, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", true],
509 # Non-versionable attribute updates shouldn't create new versions
510 [true, 'replication_desired', 5, false],
511 [false, 'replication_desired', 5, false],
512 ].each do |versioning, attr, val, new_version_expected|
513 test "update #{attr} with versioning #{versioning ? '' : 'not '}enabled should #{new_version_expected ? '' : 'not '}create a new version" do
514 Rails.configuration.Collections.CollectionVersioning = versioning
515 Rails.configuration.Collections.PreserveVersionIfIdle = 0
516 act_as_user users(:active) do
517 # Create initial collection
518 c = create_collection 'foo', Encoding::US_ASCII
520 assert_equal 'foo', c.name
522 # Check current version attributes
523 assert_equal 1, c.version
524 assert_equal c.uuid, c.current_version_uuid
526 # Update attribute and check if version number should be incremented
527 old_value = c.attributes[attr]
528 c.update!({attr => val})
529 assert_equal new_version_expected, c.version == 2
530 assert_equal val, c.attributes[attr]
532 if versioning && new_version_expected
533 # Search for the snapshot & previous value
534 assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
535 s = Collection.where(current_version_uuid: c.uuid, version: 1).first
537 assert_equal old_value, s.attributes[attr]
539 # If versioning is disabled or no versionable attribute was updated,
540 # only the current version should exist
541 assert_equal 1, Collection.where(current_version_uuid: c.uuid).count
542 assert_equal c, Collection.where(current_version_uuid: c.uuid).first
548 test 'current_version_uuid is ignored during update' do
549 Rails.configuration.Collections.CollectionVersioning = true
550 Rails.configuration.Collections.PreserveVersionIfIdle = 0
551 act_as_user users(:active) do
552 # Create 1st collection
553 col1 = create_collection 'foo', Encoding::US_ASCII
555 assert_equal 1, col1.version
557 # Create 2nd collection, update it so it becomes version:2
558 # (to avoid unique index violation)
559 col2 = create_collection 'bar', Encoding::US_ASCII
561 assert_equal 1, col2.version
562 col2.update({name: 'baz'})
563 assert_equal 2, col2.version
565 # Try to make col2 a past version of col1. It shouldn't be possible
566 col2.update({current_version_uuid: col1.uuid})
569 assert_not_equal col1.uuid, col2.current_version_uuid
573 test 'with versioning enabled, simultaneous updates increment version correctly' do
574 Rails.configuration.Collections.CollectionVersioning = true
575 Rails.configuration.Collections.PreserveVersionIfIdle = 0
576 act_as_user users(:active) do
577 # Create initial collection
578 col = create_collection 'foo', Encoding::US_ASCII
580 assert_equal 1, col.version
582 # Simulate simultaneous updates
583 c1 = Collection.where(uuid: col.uuid).first
584 assert_equal 1, c1.version
586 c2 = Collection.where(uuid: col.uuid).first
587 c2.description = 'foo collection'
589 assert_equal 1, c2.version
590 # with_lock forces a reload, so this shouldn't produce an unique violation error
592 assert_equal 3, c2.version
593 assert_equal 'foo collection', c2.description
597 test 'create and update collection and verify file_names' do
598 act_as_system_user do
599 c = create_collection 'foo', Encoding::US_ASCII
601 created_file_names = c.file_names
602 assert created_file_names
603 assert_match(/foo.txt/, c.file_names)
605 c.update_attribute 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo2.txt\n"
606 assert_not_equal created_file_names, c.file_names
607 assert_match(/foo2.txt/, c.file_names)
614 ].each do |manifest_size, allow_truncate|
615 test "create collection with manifest size #{manifest_size} with allow_truncate=#{allow_truncate},
616 and not expect exceptions even on very large manifest texts" do
617 # file_names has a max size, hence there will be no errors even on large manifests
618 act_as_system_user do
621 while manifest_text.length < manifest_size
622 manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
625 manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
626 c = Collection.create(manifest_text: manifest_text)
630 assert_match(/veryverylongfilename0000000000001.txt/, c.file_names)
631 assert_match(/veryverylongfilename0000000000002.txt/, c.file_names)
632 if not allow_truncate
633 assert_match(/veryverylastfilename/, c.file_names)
634 assert_match(/laststreamname/, c.file_names)
640 test "full text search for collections" do
641 # file_names column does not get populated when fixtures are loaded, hence setup test data
642 act_as_system_user do
643 Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n")
644 Collection.create(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
645 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")
650 ['foo bar', false], # no collection matching both
651 ['foo&bar', false], # no collection matching both
652 ['foo|bar', true], # works only no spaces between the words
653 ['Gnu public', true], # both prefixes found, though not consecutively
654 ['Gnu&public', true], # both prefixes found, though not consecutively
655 ['file4', true], # prefix match
656 ['file4.txt', true], # whole string match
657 ['filex', false], # no such prefix
658 ['subdir', true], # prefix matches
661 ['subdir2/subdir3', true],
662 ['subdir2/subdir3/subdir4', true],
663 ['subdir2 file4', true], # look for both prefixes
664 ['subdir4', false], # not a prefix match
665 ].each do |search_filter, expect_results|
666 search_filters = search_filter.split.each {|s| s.concat(':*')}.join('&')
667 results = Collection.where("#{Collection.full_text_tsvector} @@ to_tsquery(?)",
677 test 'portable data hash with missing size hints' do
678 [[". d41d8cd98f00b204e9800998ecf8427e+0+Bar 0:0:x\n",
679 ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"],
680 [". d41d8cd98f00b204e9800998ecf8427e+Foo 0:0:x\n",
681 ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
682 [". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n",
683 ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
684 ].each do |unportable, portable|
685 c = Collection.new(manifest_text: unportable)
687 assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
688 c.portable_data_hash)
692 pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
693 pdhmd5 = Digest::MD5.hexdigest pdhmanifest
696 [true, pdhmd5+'+12345'],
697 [true, pdhmd5+'+'+pdhmanifest.length.to_s],
698 [true, pdhmd5+'+12345+Foo'],
699 [true, pdhmd5+'+Foo'],
700 [false, Digest::MD5.hexdigest(pdhmanifest.strip)],
701 [false, Digest::MD5.hexdigest(pdhmanifest.strip)+'+'+pdhmanifest.length.to_s],
702 [false, pdhmd5[0..30]],
703 [false, pdhmd5[0..30]+'z'],
704 [false, pdhmd5[0..24]+'000000000'],
705 [false, pdhmd5[0..24]+'000000000+0']].each do |isvalid, pdh|
706 test "portable_data_hash #{pdh.inspect} valid? == #{isvalid}" do
707 c = Collection.new manifest_text: pdhmanifest, portable_data_hash: pdh
708 assert_equal isvalid, c.valid?, c.errors.full_messages.to_s
712 test "storage_classes_desired default respects config" do
713 saved = Rails.configuration.DefaultStorageClasses
714 Rails.configuration.DefaultStorageClasses = ["foo"]
716 act_as_user users(:active) do
717 c = Collection.create!
718 assert_equal ["foo"], c.storage_classes_desired
721 Rails.configuration.DefaultStorageClasses = saved
725 test "storage_classes_desired cannot be empty" do
726 act_as_user users(:active) do
727 c = collections(:collection_owned_by_active)
728 c.update storage_classes_desired: ["hot"]
729 assert_equal ["hot"], c.storage_classes_desired
730 assert_raise ArvadosModel::InvalidStateTransitionError do
731 c.update storage_classes_desired: []
736 test "storage classes lists should only contain non-empty strings" do
737 c = collections(:storage_classes_desired_default_unconfirmed)
738 act_as_user users(:admin) do
739 assert c.update(storage_classes_desired: ["default", "a_string"],
740 storage_classes_confirmed: ["another_string"])
742 ["storage_classes_desired", ["default", 42]],
743 ["storage_classes_confirmed", [{the_answer: 42}]],
744 ["storage_classes_desired", ["default", ""]],
745 ["storage_classes_confirmed", [""]],
746 ].each do |attr, val|
747 assert_raise ArvadosModel::InvalidStateTransitionError do
748 assert c.update({attr => val})
754 test "storage_classes_confirmed* can be set by admin user" do
755 c = collections(:storage_classes_desired_default_unconfirmed)
756 act_as_user users(:admin) do
757 assert c.update(storage_classes_confirmed: ["default"],
758 storage_classes_confirmed_at: Time.now)
762 test "storage_classes_confirmed* cannot be set by non-admin user" do
763 act_as_user users(:active) do
764 c = collections(:storage_classes_desired_default_unconfirmed)
765 # Cannot set just one at a time.
766 assert_raise ArvadosModel::PermissionDeniedError do
767 c.update storage_classes_confirmed: ["default"]
770 assert_raise ArvadosModel::PermissionDeniedError do
771 c.update storage_classes_confirmed_at: Time.now
773 # Cannot set bot at once, either.
775 assert_raise ArvadosModel::PermissionDeniedError do
776 assert c.update(storage_classes_confirmed: ["default"],
777 storage_classes_confirmed_at: Time.now)
782 test "storage_classes_confirmed* can be cleared (but only together) by non-admin user" do
783 act_as_user users(:active) do
784 c = collections(:storage_classes_desired_default_confirmed_default)
785 # Cannot clear just one at a time.
786 assert_raise ArvadosModel::PermissionDeniedError do
787 c.update storage_classes_confirmed: []
790 assert_raise ArvadosModel::PermissionDeniedError do
791 c.update storage_classes_confirmed_at: nil
793 # Can clear both at once.
795 assert c.update(storage_classes_confirmed: [],
796 storage_classes_confirmed_at: nil)
800 [0, 2, 4, nil].each do |ask|
801 test "set replication_desired to #{ask.inspect}" do
802 Rails.configuration.Collections.DefaultReplication = 2
803 act_as_user users(:active) do
804 c = collections(:replication_undesired_unconfirmed)
805 c.update replication_desired: ask
806 assert_equal ask, c.replication_desired
811 test "replication_confirmed* can be set by admin user" do
812 c = collections(:replication_desired_2_unconfirmed)
813 act_as_user users(:admin) do
814 assert c.update(replication_confirmed: 2,
815 replication_confirmed_at: Time.now)
819 test "replication_confirmed* cannot be set by non-admin user" do
820 act_as_user users(:active) do
821 c = collections(:replication_desired_2_unconfirmed)
822 # Cannot set just one at a time.
823 assert_raise ArvadosModel::PermissionDeniedError do
824 c.update replication_confirmed: 1
826 assert_raise ArvadosModel::PermissionDeniedError do
827 c.update replication_confirmed_at: Time.now
829 # Cannot set both at once, either.
830 assert_raise ArvadosModel::PermissionDeniedError do
831 c.update(replication_confirmed: 1,
832 replication_confirmed_at: Time.now)
837 test "replication_confirmed* can be cleared (but only together) by non-admin user" do
838 act_as_user users(:active) do
839 c = collections(:replication_desired_2_confirmed_2)
840 # Cannot clear just one at a time.
841 assert_raise ArvadosModel::PermissionDeniedError do
842 c.update replication_confirmed: nil
845 assert_raise ArvadosModel::PermissionDeniedError do
846 c.update replication_confirmed_at: nil
848 # Can clear both at once.
850 assert c.update(replication_confirmed: nil,
851 replication_confirmed_at: nil)
855 test "clear replication_confirmed* when introducing a new block in manifest" do
856 c = collections(:replication_desired_2_confirmed_2)
857 act_as_user users(:active) do
858 assert c.update(manifest_text: collections(:user_agreement).signed_manifest_text_only_for_tests)
859 assert_nil c.replication_confirmed
860 assert_nil c.replication_confirmed_at
864 test "don't clear replication_confirmed* when just renaming a file" do
865 c = collections(:replication_desired_2_confirmed_2)
866 act_as_user users(:active) do
867 new_manifest = c.signed_manifest_text_only_for_tests.sub(':bar', ':foo')
868 assert c.update(manifest_text: new_manifest)
869 assert_equal 2, c.replication_confirmed
870 assert_not_nil c.replication_confirmed_at
874 test "don't clear replication_confirmed* when just deleting a data block" do
875 c = collections(:replication_desired_2_confirmed_2)
876 act_as_user users(:active) do
877 new_manifest = c.signed_manifest_text_only_for_tests
878 new_manifest.sub!(/ \S+:bar/, '')
879 new_manifest.sub!(/ acbd\S+/, '')
881 # Confirm that we did just remove a block from the manifest (if
882 # not, this test would pass without testing the relevant case):
883 assert_operator new_manifest.length+40, :<, c.signed_manifest_text_only_for_tests.length
885 assert c.update(manifest_text: new_manifest)
886 assert_equal 2, c.replication_confirmed
887 assert_not_nil c.replication_confirmed_at
891 test 'signature expiry does not exceed trash_at' do
892 act_as_user users(:active) do
894 c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
895 c.update! trash_at: (t0 + 1.hours)
897 sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text_only_for_tests)[1].to_i
898 assert_operator sig_exp.to_i, :<=, (t0 + 1.hours).to_i
902 test 'far-future expiry date cannot be used to circumvent configured permission ttl' do
903 act_as_user users(:active) do
904 c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n",
906 trash_at: db_current_time + 1.years)
907 sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text_only_for_tests)[1].to_i
908 expect_max_sig_exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
909 assert_operator c.trash_at.to_i, :>, expect_max_sig_exp
910 assert_operator sig_exp.to_i, :<=, expect_max_sig_exp
914 test "create collection with properties" do
915 act_as_system_user do
916 c = Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n",
917 properties: {'property_1' => 'value_1'})
919 assert_equal 'value_1', c.properties['property_1']
923 test 'create, delete, recreate collection with same name and owner' do
924 act_as_user users(:active) do
925 # create collection with name
926 c = Collection.create(manifest_text: '',
927 name: "test collection name")
931 c = Collection.readable_by(current_user).where(uuid: uuid)
932 assert_not_empty c, 'Should be able to find live collection'
934 # mark collection as expired
935 c.first.update!(trash_at: Time.new.strftime("%Y-%m-%d"))
936 c = Collection.readable_by(current_user).where(uuid: uuid)
937 assert_empty c, 'Should not be able to find expired collection'
939 # recreate collection with the same name
940 c = Collection.create(manifest_text: '',
941 name: "test collection name")
946 test 'trash_at cannot be set too far in the past' do
947 act_as_user users(:active) do
949 c = Collection.create!(manifest_text: '', name: 'foo')
950 c.update! trash_at: (t0 - 2.weeks)
952 assert_operator c.trash_at, :>, t0
957 [['trash-to-delete interval negative',
958 :collection_owned_by_active,
959 {trash_at: now+2.weeks, delete_at: now},
961 ['now-to-delete interval short',
962 :collection_owned_by_active,
963 {trash_at: now+3.days, delete_at: now+7.days},
964 {state: :trash_future}],
965 ['now-to-delete interval short, trash=delete',
966 :collection_owned_by_active,
967 {trash_at: now+3.days, delete_at: now+3.days},
968 {state: :trash_future}],
969 ['trash-to-delete interval ok',
970 :collection_owned_by_active,
971 {trash_at: now, delete_at: now+15.days},
972 {state: :trash_now}],
973 ['trash-to-delete interval short, but far enough in future',
974 :collection_owned_by_active,
975 {trash_at: now+13.days, delete_at: now+15.days},
976 {state: :trash_future}],
977 ['trash by setting is_trashed bool',
978 :collection_owned_by_active,
980 {state: :trash_now}],
981 ['trash in future by setting just trash_at',
982 :collection_owned_by_active,
983 {trash_at: now+1.week},
984 {state: :trash_future}],
985 ['trash in future by setting trash_at and delete_at',
986 :collection_owned_by_active,
987 {trash_at: now+1.week, delete_at: now+4.weeks},
988 {state: :trash_future}],
989 ['untrash by clearing is_trashed bool',
992 {state: :not_trash}],
993 ].each do |test_name, fixture_name, updates, expect|
995 act_as_user users(:active) do
996 min_exp = (db_current_time +
997 Rails.configuration.Collections.BlobSigningTTL)
998 if fixture_name == :expired_collection
999 # Fixture-finder shorthand doesn't find trashed collections
1000 # because they're not in the default scope.
1001 c = Collection.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
1003 c = collections(fixture_name)
1005 updates_ok = c.update(updates)
1006 expect_valid = expect[:state] != :invalid
1007 assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
1013 assert_not_nil c.trash_at
1014 assert_operator c.trash_at, :<=, db_current_time
1015 assert_not_nil c.delete_at
1016 assert_operator c.delete_at, :>=, min_exp
1019 assert_not_nil c.trash_at
1020 assert_operator c.trash_at, :>, db_current_time
1021 assert_not_nil c.delete_at
1022 assert_operator c.delete_at, :>=, c.trash_at
1023 # Currently this minimum interval is needed to prevent early
1024 # garbage collection:
1025 assert_operator c.delete_at, :>=, min_exp
1028 assert_nil c.trash_at
1029 assert_nil c.delete_at
1031 raise "bad expect[:state]==#{expect[:state].inspect} in test case"
1037 test 'default trash interval > blob signature ttl' do
1038 Rails.configuration.Collections.DefaultTrashLifetime = 86400 * 21 # 3 weeks
1039 start = db_current_time
1040 act_as_user users(:active) do
1041 c = Collection.create!(manifest_text: '', name: 'foo')
1042 c.update!(trash_at: start + 86400.seconds)
1043 assert_operator c.delete_at, :>=, start + (86400*22).seconds
1044 assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
1047 c = Collection.create!(manifest_text: '', name: 'foo')
1048 c.update!(is_trashed: true)
1049 assert_operator c.delete_at, :>=, start + (86400*21).seconds
1053 test "find_all_for_docker_image resolves names that look like hashes" do
1054 coll_list = Collection.
1055 find_all_for_docker_image('a' * 64, nil, [users(:active)])
1056 coll_uuids = coll_list.map(&:uuid)
1057 assert_includes(coll_uuids, collections(:docker_image).uuid)
1060 test "empty names are exempt from name uniqueness" do
1061 act_as_user users(:active) do
1062 c1 = Collection.new(name: nil, manifest_text: '', owner_uuid: groups(:aproject).uuid)
1064 c2 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1066 c3 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1068 c4 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1070 c5 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1071 assert_raises(ActiveRecord::RecordNotUnique) do
1077 test "create collections with managed properties" do
1078 Rails.configuration.Collections.ManagedProperties = ConfigLoader.to_OrderedOptions({
1079 'default_prop1' => {'Value' => 'prop1_value'},
1080 'responsible_person_uuid' => {'Function' => 'original_owner'}
1082 # Test collection without initial properties
1083 act_as_user users(:active) do
1084 c = create_collection 'foo', Encoding::US_ASCII
1086 assert_not_empty c.properties
1087 assert_equal 'prop1_value', c.properties['default_prop1']
1088 assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1090 # Test collection with default_prop1 property already set
1091 act_as_user users(:active) do
1092 c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n",
1093 properties: {'default_prop1' => 'custom_value'})
1095 assert_not_empty c.properties
1096 assert_equal 'custom_value', c.properties['default_prop1']
1097 assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1099 # Test collection inside a sub project
1100 act_as_user users(:active) do
1101 c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n",
1102 owner_uuid: groups(:asubproject).uuid)
1104 assert_not_empty c.properties
1105 assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1109 test "update collection with protected managed properties" do
1110 Rails.configuration.Collections.ManagedProperties = ConfigLoader.to_OrderedOptions({
1111 'default_prop1' => {'Value' => 'prop1_value', 'Protected' => true},
1113 act_as_user users(:active) do
1114 c = create_collection 'foo', Encoding::US_ASCII
1116 assert_not_empty c.properties
1117 assert_equal 'prop1_value', c.properties['default_prop1']
1119 c.properties['prop2'] = 'value2'
1122 assert_equal 'value2', c.properties['prop2']
1123 # Try to change protected property's value
1124 c.properties['default_prop1'] = 'new_value'
1125 assert_raises(ArvadosModel::PermissionDeniedError) do
1128 # Admins are allowed to change protected properties
1129 act_as_system_user do
1130 c.properties['default_prop1'] = 'new_value'
1133 assert_equal 'new_value', c.properties['default_prop1']
1138 test "collection names must be displayable in a filesystem" do
1139 set_user_from_auth :active
1140 ["", "{SOLIDUS}"].each do |subst|
1141 Rails.configuration.Collections.ForwardSlashNameSubstitution = subst
1142 c = Collection.create
1149 ["foo/bar", subst != ""],
1150 ["../..", subst != ""],
1152 ].each do |name, valid|
1154 assert_equal valid, c.valid?, "#{name.inspect} should be #{valid ? "valid" : "invalid"}"