17417: Add arm64 packages for our Golang components.
[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 require 'fix_collection_versions_timestamps'
8
9 class CollectionTest < ActiveSupport::TestCase
10   include DbCurrentTime
11
12   def create_collection name, enc=nil
13     txt = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:#{name}.txt\n"
14     txt.force_encoding(enc) if enc
15     return Collection.create(manifest_text: txt, name: name)
16   end
17
18   test 'accept ASCII manifest_text' do
19     act_as_system_user do
20       c = create_collection 'foo', Encoding::US_ASCII
21       assert c.valid?
22     end
23   end
24
25   test 'accept UTF-8 manifest_text' do
26     act_as_system_user do
27       c = create_collection "f\xc3\x98\xc3\x98", Encoding::UTF_8
28       assert c.valid?
29     end
30   end
31
32   test 'refuse manifest_text with invalid UTF-8 byte sequence' do
33     act_as_system_user do
34       c = create_collection "f\xc8o", Encoding::UTF_8
35       assert !c.valid?
36       assert_equal [:manifest_text], c.errors.messages.keys
37       assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
38     end
39   end
40
41   test 'refuse manifest_text with non-UTF-8 encoding' do
42     act_as_system_user do
43       c = create_collection "f\xc8o", Encoding::ASCII_8BIT
44       assert !c.valid?
45       assert_equal [:manifest_text], c.errors.messages.keys
46       assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
47     end
48   end
49
50   [
51     ". 0:0:foo.txt",
52     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
53     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
54     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
55   ].each do |manifest_text|
56     test "create collection with invalid manifest text #{manifest_text} and expect error" do
57       act_as_system_user do
58         c = Collection.create(manifest_text: manifest_text)
59         assert !c.valid?
60       end
61     end
62   end
63
64   [
65     [". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", 1, 34],
66     [". 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],
67     [". d41d8cd98f00b204e9800998ecf8427e 0:0:.\n", 0, 0]
68   ].each do |manifest, count, size|
69     test "file stats on create collection with #{manifest}" do
70       act_as_system_user do
71         c = Collection.create(manifest_text: manifest)
72         assert_equal count, c.file_count
73         assert_equal size, c.file_size_total
74       end
75     end
76   end
77
78   test "file stats cannot be changed unless through manifest change" do
79     act_as_system_user do
80       # Direct changes to file stats should be ignored
81       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n")
82       c.file_count = 6
83       c.file_size_total = 30
84       assert c.valid?
85       assert_equal 1, c.file_count
86       assert_equal 34, c.file_size_total
87
88       # File stats specified on create should be ignored and overwritten
89       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count: 10, file_size_total: 10)
90       assert c.valid?
91       assert_equal 1, c.file_count
92       assert_equal 34, c.file_size_total
93
94       # Updating the manifest should change file stats
95       c.update_attributes(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:34:foo2.txt\n")
96       assert c.valid?
97       assert_equal 2, c.file_count
98       assert_equal 68, c.file_size_total
99
100       # Updating file stats and the manifest should use manifest values
101       c.update_attributes(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count:10, file_size_total: 10)
102       assert c.valid?
103       assert_equal 1, c.file_count
104       assert_equal 34, c.file_size_total
105
106       # Updating just the file stats should be ignored
107       c.update_attributes(file_count: 10, file_size_total: 10)
108       assert c.valid?
109       assert_equal 1, c.file_count
110       assert_equal 34, c.file_size_total
111     end
112   end
113
114   [
115     nil,
116     "",
117     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
118   ].each do |manifest_text|
119     test "create collection with valid manifest text #{manifest_text.inspect} and expect success" do
120       act_as_system_user do
121         c = Collection.create(manifest_text: manifest_text)
122         assert c.valid?
123       end
124     end
125   end
126
127   [
128     ". 0:0:foo.txt",
129     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
130     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
131     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
132   ].each do |manifest_text|
133     test "update collection with invalid manifest text #{manifest_text} and expect error" do
134       act_as_system_user do
135         c = create_collection 'foo', Encoding::US_ASCII
136         assert c.valid?
137
138         c.update_attribute 'manifest_text', manifest_text
139         assert !c.valid?
140       end
141     end
142   end
143
144   [
145     nil,
146     "",
147     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
148   ].each do |manifest_text|
149     test "update collection with valid manifest text #{manifest_text.inspect} and expect success" do
150       act_as_system_user do
151         c = create_collection 'foo', Encoding::US_ASCII
152         assert c.valid?
153
154         c.update_attribute 'manifest_text', manifest_text
155         assert c.valid?
156       end
157     end
158   end
159
160   test "auto-create version after idle setting" do
161     Rails.configuration.Collections.CollectionVersioning = true
162     Rails.configuration.Collections.PreserveVersionIfIdle = 600 # 10 minutes
163     act_as_user users(:active) do
164       # Set up initial collection
165       c = create_collection 'foo', Encoding::US_ASCII
166       assert c.valid?
167       assert_equal 1, c.version
168       assert_equal false, c.preserve_version
169       # Make a versionable update, it shouldn't create a new version yet
170       c.update_attributes!({'name' => 'bar'})
171       c.reload
172       assert_equal 'bar', c.name
173       assert_equal 1, c.version
174       # Update modified_at to trigger a version auto-creation
175       fifteen_min_ago = Time.now - 15.minutes
176       c.update_column('modified_at', fifteen_min_ago) # Update without validations/callbacks
177       c.reload
178       assert_equal fifteen_min_ago.to_i, c.modified_at.to_i
179       c.update_attributes!({'name' => 'baz'})
180       c.reload
181       assert_equal 'baz', c.name
182       assert_equal 2, c.version
183       # Make another update, no new version should be created
184       c.update_attributes!({'name' => 'foobar'})
185       c.reload
186       assert_equal 'foobar', c.name
187       assert_equal 2, c.version
188     end
189   end
190
191   test "preserve_version updates" do
192     Rails.configuration.Collections.CollectionVersioning = true
193     Rails.configuration.Collections.PreserveVersionIfIdle = -1 # disabled
194     act_as_user users(:active) do
195       # Set up initial collection
196       c = create_collection 'foo', Encoding::US_ASCII
197       assert c.valid?
198       assert_equal 1, c.version
199       assert_equal false, c.preserve_version
200       # This update shouldn't produce a new version, as the idle time is not up
201       c.update_attributes!({
202         'name' => 'bar'
203       })
204       c.reload
205       assert_equal 1, c.version
206       assert_equal 'bar', c.name
207       assert_equal false, c.preserve_version
208       # This update should produce a new version, even if the idle time is not up
209       # and also keep the preserve_version=true flag to persist it.
210       c.update_attributes!({
211         'name' => 'baz',
212         'preserve_version' => true
213       })
214       c.reload
215       assert_equal 2, c.version
216       assert_equal 'baz', c.name
217       assert_equal true, c.preserve_version
218       # Make sure preserve_version is not disabled after being enabled, unless
219       # a new version is created.
220       # This is a non-versionable update
221       c.update_attributes!({
222         'preserve_version' => false,
223         'replication_desired' => 2
224       })
225       c.reload
226       assert_equal 2, c.version
227       assert_equal 2, c.replication_desired
228       assert_equal true, c.preserve_version
229       # This is a versionable update
230       c.update_attributes!({
231         'preserve_version' => false,
232         'name' => 'foobar'
233       })
234       c.reload
235       assert_equal 3, c.version
236       assert_equal false, c.preserve_version
237       assert_equal 'foobar', c.name
238       # Flipping only 'preserve_version' to true doesn't create a new version
239       c.update_attributes!({'preserve_version' => true})
240       c.reload
241       assert_equal 3, c.version
242       assert_equal true, c.preserve_version
243     end
244   end
245
246   test "preserve_version updates don't change modified_at timestamp" do
247     act_as_user users(:active) do
248       c = create_collection 'foo', Encoding::US_ASCII
249       assert c.valid?
250       assert_equal false, c.preserve_version
251       modified_at = c.modified_at.to_f
252       c.update_attributes!({'preserve_version' => true})
253       c.reload
254       assert_equal true, c.preserve_version
255       assert_equal modified_at, c.modified_at.to_f,
256         'preserve_version updates should not trigger modified_at changes'
257     end
258   end
259
260   [
261     ['version', 10],
262     ['current_version_uuid', 'zzzzz-4zz18-bv31uwvy3neko21'],
263   ].each do |name, new_value|
264     test "'#{name}' updates on current version collections are not allowed" do
265       act_as_user users(:active) do
266         # Set up initial collection
267         c = create_collection 'foo', Encoding::US_ASCII
268         assert c.valid?
269         assert_equal 1, c.version
270
271         assert_raises(ActiveRecord::RecordInvalid) do
272           c.update_attributes!({
273             name => new_value
274           })
275         end
276       end
277     end
278   end
279
280   test "uuid updates on current version make older versions update their pointers" do
281     Rails.configuration.Collections.CollectionVersioning = true
282     Rails.configuration.Collections.PreserveVersionIfIdle = 0
283     act_as_system_user do
284       # Set up initial collection
285       c = create_collection 'foo', Encoding::US_ASCII
286       assert c.valid?
287       assert_equal 1, c.version
288       # Make changes so that a new version is created
289       c.update_attributes!({'name' => 'bar'})
290       c.reload
291       assert_equal 2, c.version
292       assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
293       new_uuid = 'zzzzz-4zz18-somefakeuuidnow'
294       assert_empty Collection.where(uuid: new_uuid)
295       # Update UUID on current version, check that both collections point to it
296       c.update_attributes!({'uuid' => new_uuid})
297       c.reload
298       assert_equal new_uuid, c.uuid
299       assert_equal 2, Collection.where(current_version_uuid: new_uuid).count
300     end
301   end
302
303   # This test exposes a bug related to JSONB attributes, see #15725.
304   test "recently loaded collection shouldn't list changed attributes" do
305     col = Collection.where("properties != '{}'::jsonb").limit(1).first
306     refute col.properties_changed?, 'Properties field should not be seen as changed'
307   end
308
309   [
310     [
311       true,
312       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
313       {:foo=>:bar, :lst=>[1, 3, 5, 7], :hsh=>{'baz'=>'qux', :foobar=>true, 'hsh'=>{:nested=>true}}, :delete_at=>nil},
314     ],
315     [
316       true,
317       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
318       {'delete_at'=>nil, 'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}},
319     ],
320     [
321       true,
322       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
323       {'delete_at'=>nil, 'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'foobar'=>true, 'hsh'=>{'nested'=>true}, 'baz'=>'qux'}},
324     ],
325     [
326       false,
327       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
328       {'foo'=>'bar', 'lst'=>[1, 3, 5, 42], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
329     ],
330     [
331       false,
332       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
333       {'foo'=>'bar', 'lst'=>[1, 3, 7, 5], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
334     ],
335     [
336       false,
337       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
338       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>false}}, 'delete_at'=>nil},
339     ],
340     [
341       false,
342       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
343       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>1234567890},
344     ],
345   ].each do |should_be_equal, value_1, value_2|
346     test "JSONB properties #{value_1} is#{should_be_equal ? '' : ' not'} equal to #{value_2}" do
347       act_as_user users(:active) do
348         # Set up initial collection
349         c = create_collection 'foo', Encoding::US_ASCII
350         assert c.valid?
351         c.update_attributes!({'properties' => value_1})
352         c.reload
353         assert c.changes.keys.empty?
354         c.properties = value_2
355         if should_be_equal
356           assert c.changes.keys.empty?, "Properties #{value_1.inspect} should be equal to #{value_2.inspect}"
357         else
358           refute c.changes.keys.empty?, "Properties #{value_1.inspect} should not be equal to #{value_2.inspect}"
359         end
360       end
361     end
362   end
363
364   test "older versions' modified_at indicate when they're created" do
365     Rails.configuration.Collections.CollectionVersioning = true
366     Rails.configuration.Collections.PreserveVersionIfIdle = 0
367     act_as_user users(:active) do
368       # Set up initial collection
369       c = create_collection 'foo', Encoding::US_ASCII
370       assert c.valid?
371       original_version_modified_at = c.modified_at.to_f
372       # Make changes so that a new version is created
373       c.update_attributes!({'name' => 'bar'})
374       c.reload
375       assert_equal 2, c.version
376       # Get the old version
377       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
378       assert_not_nil c_old
379
380       version_creation_datetime = c_old.modified_at.to_f
381       assert_equal c.created_at.to_f, c_old.created_at.to_f
382       assert_equal original_version_modified_at, version_creation_datetime
383
384       # Make update on current version so old version get the attribute synced;
385       # its modified_at should not change.
386       new_replication = 3
387       c.update_attributes!({'replication_desired' => new_replication})
388       c.reload
389       assert_equal new_replication, c.replication_desired
390       c_old.reload
391       assert_equal new_replication, c_old.replication_desired
392       assert_equal version_creation_datetime, c_old.modified_at.to_f
393       assert_operator c.modified_at.to_f, :>, c_old.modified_at.to_f
394     end
395   end
396
397   # Bug #17152 - This test relies on fixtures simulating the problem.
398   test "migration fixing collection versions' modified_at timestamps" do
399     versioned_collection_fixtures = [
400       collections(:w_a_z_file).uuid,
401       collections(:collection_owned_by_active).uuid
402     ]
403     versioned_collection_fixtures.each do |uuid|
404       cols = Collection.where(current_version_uuid: uuid).order(version: :desc)
405       assert_equal cols.size, 2
406       # cols[0] -> head version // cols[1] -> old version
407       assert_operator (cols[0].modified_at.to_f - cols[1].modified_at.to_f), :==, 0
408       assert cols[1].modified_at != cols[1].created_at
409     end
410     fix_collection_versions_timestamps
411     versioned_collection_fixtures.each do |uuid|
412       cols = Collection.where(current_version_uuid: uuid).order(version: :desc)
413       assert_equal cols.size, 2
414       # cols[0] -> head version // cols[1] -> old version
415       assert_operator (cols[0].modified_at.to_f - cols[1].modified_at.to_f), :>, 1
416       assert_operator cols[1].modified_at, :==, cols[1].created_at
417     end
418   end
419
420   test "past versions should not be directly updatable" do
421     Rails.configuration.Collections.CollectionVersioning = true
422     Rails.configuration.Collections.PreserveVersionIfIdle = 0
423     act_as_system_user do
424       # Set up initial collection
425       c = create_collection 'foo', Encoding::US_ASCII
426       assert c.valid?
427       # Make changes so that a new version is created
428       c.update_attributes!({'name' => 'bar'})
429       c.reload
430       assert_equal 2, c.version
431       # Get the old version
432       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
433       assert_not_nil c_old
434       # With collection versioning still being enabled, try to update
435       c_old.name = 'this was foo'
436       assert c_old.invalid?
437       c_old.reload
438       # Try to fool the validator attempting to make c_old to look like a
439       # current version, it should also fail.
440       c_old.current_version_uuid = c_old.uuid
441       assert c_old.invalid?
442       c_old.reload
443       # Now disable collection versioning, it should behave the same way
444       Rails.configuration.Collections.CollectionVersioning = false
445       c_old.name = 'this was foo'
446       assert c_old.invalid?
447     end
448   end
449
450   [
451     ['owner_uuid', 'zzzzz-tpzed-d9tiejq69daie8f', 'zzzzz-tpzed-xurymjxw79nv3jz'],
452     ['replication_desired', 2, 3],
453     ['storage_classes_desired', ['hot'], ['archive']],
454   ].each do |attr, first_val, second_val|
455     test "sync #{attr} with older versions" do
456       Rails.configuration.Collections.CollectionVersioning = true
457       Rails.configuration.Collections.PreserveVersionIfIdle = 0
458       act_as_system_user do
459         # Set up initial collection
460         c = create_collection 'foo', Encoding::US_ASCII
461         assert c.valid?
462         assert_equal 1, c.version
463         assert_not_equal first_val, c.attributes[attr]
464         # Make changes so that a new version is created and a synced field is
465         # updated on both
466         c.update_attributes!({'name' => 'bar', attr => first_val})
467         c.reload
468         assert_equal 2, c.version
469         assert_equal first_val, c.attributes[attr]
470         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
471         assert_equal first_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
472         # Only make an update on the same synced field & check that the previously
473         # created version also gets it.
474         c.update_attributes!({attr => second_val})
475         c.reload
476         assert_equal 2, c.version
477         assert_equal second_val, c.attributes[attr]
478         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
479         assert_equal second_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
480       end
481     end
482   end
483
484   [
485     [false, 'name', 'bar', false],
486     [false, 'description', 'The quick brown fox jumps over the lazy dog', false],
487     [false, 'properties', {'new_version' => true}, false],
488     [false, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", false],
489     [true, 'name', 'bar', true],
490     [true, 'description', 'The quick brown fox jumps over the lazy dog', true],
491     [true, 'properties', {'new_version' => true}, true],
492     [true, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", true],
493     # Non-versionable attribute updates shouldn't create new versions
494     [true, 'replication_desired', 5, false],
495     [false, 'replication_desired', 5, false],
496   ].each do |versioning, attr, val, new_version_expected|
497     test "update #{attr} with versioning #{versioning ? '' : 'not '}enabled should #{new_version_expected ? '' : 'not '}create a new version" do
498       Rails.configuration.Collections.CollectionVersioning = versioning
499       Rails.configuration.Collections.PreserveVersionIfIdle = 0
500       act_as_user users(:active) do
501         # Create initial collection
502         c = create_collection 'foo', Encoding::US_ASCII
503         assert c.valid?
504         assert_equal 'foo', c.name
505
506         # Check current version attributes
507         assert_equal 1, c.version
508         assert_equal c.uuid, c.current_version_uuid
509
510         # Update attribute and check if version number should be incremented
511         old_value = c.attributes[attr]
512         c.update_attributes!({attr => val})
513         assert_equal new_version_expected, c.version == 2
514         assert_equal val, c.attributes[attr]
515
516         if versioning && new_version_expected
517           # Search for the snapshot & previous value
518           assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
519           s = Collection.where(current_version_uuid: c.uuid, version: 1).first
520           assert_not_nil s
521           assert_equal old_value, s.attributes[attr]
522         else
523           # If versioning is disabled or no versionable attribute was updated,
524           # only the current version should exist
525           assert_equal 1, Collection.where(current_version_uuid: c.uuid).count
526           assert_equal c, Collection.where(current_version_uuid: c.uuid).first
527         end
528       end
529     end
530   end
531
532   test 'current_version_uuid is ignored during update' do
533     Rails.configuration.Collections.CollectionVersioning = true
534     Rails.configuration.Collections.PreserveVersionIfIdle = 0
535     act_as_user users(:active) do
536       # Create 1st collection
537       col1 = create_collection 'foo', Encoding::US_ASCII
538       assert col1.valid?
539       assert_equal 1, col1.version
540
541       # Create 2nd collection, update it so it becomes version:2
542       # (to avoid unique index violation)
543       col2 = create_collection 'bar', Encoding::US_ASCII
544       assert col2.valid?
545       assert_equal 1, col2.version
546       col2.update_attributes({name: 'baz'})
547       assert_equal 2, col2.version
548
549       # Try to make col2 a past version of col1. It shouldn't be possible
550       col2.update_attributes({current_version_uuid: col1.uuid})
551       assert col2.invalid?
552       col2.reload
553       assert_not_equal col1.uuid, col2.current_version_uuid
554     end
555   end
556
557   test 'with versioning enabled, simultaneous updates increment version correctly' do
558     Rails.configuration.Collections.CollectionVersioning = true
559     Rails.configuration.Collections.PreserveVersionIfIdle = 0
560     act_as_user users(:active) do
561       # Create initial collection
562       col = create_collection 'foo', Encoding::US_ASCII
563       assert col.valid?
564       assert_equal 1, col.version
565
566       # Simulate simultaneous updates
567       c1 = Collection.where(uuid: col.uuid).first
568       assert_equal 1, c1.version
569       c1.name = 'bar'
570       c2 = Collection.where(uuid: col.uuid).first
571       c2.description = 'foo collection'
572       c1.save!
573       assert_equal 1, c2.version
574       # with_lock forces a reload, so this shouldn't produce an unique violation error
575       c2.save!
576       assert_equal 3, c2.version
577       assert_equal 'foo collection', c2.description
578     end
579   end
580
581   test 'create and update collection and verify file_names' do
582     act_as_system_user do
583       c = create_collection 'foo', Encoding::US_ASCII
584       assert c.valid?
585       created_file_names = c.file_names
586       assert created_file_names
587       assert_match(/foo.txt/, c.file_names)
588
589       c.update_attribute 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo2.txt\n"
590       assert_not_equal created_file_names, c.file_names
591       assert_match(/foo2.txt/, c.file_names)
592     end
593   end
594
595   [
596     [2**8, false],
597     [2**18, true],
598   ].each do |manifest_size, allow_truncate|
599     test "create collection with manifest size #{manifest_size} with allow_truncate=#{allow_truncate},
600           and not expect exceptions even on very large manifest texts" do
601       # file_names has a max size, hence there will be no errors even on large manifests
602       act_as_system_user do
603         manifest_text = ''
604         index = 0
605         while manifest_text.length < manifest_size
606           manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
607           index += 1
608         end
609         manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
610         c = Collection.create(manifest_text: manifest_text)
611
612         assert c.valid?
613         assert c.file_names
614         assert_match(/veryverylongfilename0000000000001.txt/, c.file_names)
615         assert_match(/veryverylongfilename0000000000002.txt/, c.file_names)
616         if not allow_truncate
617           assert_match(/veryverylastfilename/, c.file_names)
618           assert_match(/laststreamname/, c.file_names)
619         end
620       end
621     end
622   end
623
624   test "full text search for collections" do
625     # file_names column does not get populated when fixtures are loaded, hence setup test data
626     act_as_system_user do
627       Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n")
628       Collection.create(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
629       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")
630     end
631
632     [
633       ['foo', true],
634       ['foo bar', false],                     # no collection matching both
635       ['foo&bar', false],                     # no collection matching both
636       ['foo|bar', true],                      # works only no spaces between the words
637       ['Gnu public', true],                   # both prefixes found, though not consecutively
638       ['Gnu&public', true],                   # both prefixes found, though not consecutively
639       ['file4', true],                        # prefix match
640       ['file4.txt', true],                    # whole string match
641       ['filex', false],                       # no such prefix
642       ['subdir', true],                       # prefix matches
643       ['subdir2', true],
644       ['subdir2/', true],
645       ['subdir2/subdir3', true],
646       ['subdir2/subdir3/subdir4', true],
647       ['subdir2 file4', true],                # look for both prefixes
648       ['subdir4', false],                     # not a prefix match
649     ].each do |search_filter, expect_results|
650       search_filters = search_filter.split.each {|s| s.concat(':*')}.join('&')
651       results = Collection.where("#{Collection.full_text_tsvector} @@ to_tsquery(?)",
652                                  "#{search_filters}")
653       if expect_results
654         refute_empty results
655       else
656         assert_empty results
657       end
658     end
659   end
660
661   test 'portable data hash with missing size hints' do
662     [[". d41d8cd98f00b204e9800998ecf8427e+0+Bar 0:0:x\n",
663       ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"],
664      [". d41d8cd98f00b204e9800998ecf8427e+Foo 0:0:x\n",
665       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
666      [". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n",
667       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
668     ].each do |unportable, portable|
669       c = Collection.new(manifest_text: unportable)
670       assert c.valid?
671       assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
672                    c.portable_data_hash)
673     end
674   end
675
676   pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
677   pdhmd5 = Digest::MD5.hexdigest pdhmanifest
678   [[true, nil],
679    [true, pdhmd5],
680    [true, pdhmd5+'+12345'],
681    [true, pdhmd5+'+'+pdhmanifest.length.to_s],
682    [true, pdhmd5+'+12345+Foo'],
683    [true, pdhmd5+'+Foo'],
684    [false, Digest::MD5.hexdigest(pdhmanifest.strip)],
685    [false, Digest::MD5.hexdigest(pdhmanifest.strip)+'+'+pdhmanifest.length.to_s],
686    [false, pdhmd5[0..30]],
687    [false, pdhmd5[0..30]+'z'],
688    [false, pdhmd5[0..24]+'000000000'],
689    [false, pdhmd5[0..24]+'000000000+0']].each do |isvalid, pdh|
690     test "portable_data_hash #{pdh.inspect} valid? == #{isvalid}" do
691       c = Collection.new manifest_text: pdhmanifest, portable_data_hash: pdh
692       assert_equal isvalid, c.valid?, c.errors.full_messages.to_s
693     end
694   end
695
696   test "storage_classes_desired cannot be empty" do
697     act_as_user users(:active) do
698       c = collections(:collection_owned_by_active)
699       c.update_attributes storage_classes_desired: ["hot"]
700       assert_equal ["hot"], c.storage_classes_desired
701       assert_raise ArvadosModel::InvalidStateTransitionError do
702         c.update_attributes storage_classes_desired: []
703       end
704     end
705   end
706
707   test "storage classes lists should only contain non-empty strings" do
708     c = collections(:storage_classes_desired_default_unconfirmed)
709     act_as_user users(:admin) do
710       assert c.update_attributes(storage_classes_desired: ["default", "a_string"],
711                                  storage_classes_confirmed: ["another_string"])
712       [
713         ["storage_classes_desired", ["default", 42]],
714         ["storage_classes_confirmed", [{the_answer: 42}]],
715         ["storage_classes_desired", ["default", ""]],
716         ["storage_classes_confirmed", [""]],
717       ].each do |attr, val|
718         assert_raise ArvadosModel::InvalidStateTransitionError do
719           assert c.update_attributes({attr => val})
720         end
721       end
722     end
723   end
724
725   test "storage_classes_confirmed* can be set by admin user" do
726     c = collections(:storage_classes_desired_default_unconfirmed)
727     act_as_user users(:admin) do
728       assert c.update_attributes(storage_classes_confirmed: ["default"],
729                                  storage_classes_confirmed_at: Time.now)
730     end
731   end
732
733   test "storage_classes_confirmed* cannot be set by non-admin user" do
734     act_as_user users(:active) do
735       c = collections(:storage_classes_desired_default_unconfirmed)
736       # Cannot set just one at a time.
737       assert_raise ArvadosModel::PermissionDeniedError do
738         c.update_attributes storage_classes_confirmed: ["default"]
739       end
740       c.reload
741       assert_raise ArvadosModel::PermissionDeniedError do
742         c.update_attributes storage_classes_confirmed_at: Time.now
743       end
744       # Cannot set bot at once, either.
745       c.reload
746       assert_raise ArvadosModel::PermissionDeniedError do
747         assert c.update_attributes(storage_classes_confirmed: ["default"],
748                                    storage_classes_confirmed_at: Time.now)
749       end
750     end
751   end
752
753   test "storage_classes_confirmed* can be cleared (but only together) by non-admin user" do
754     act_as_user users(:active) do
755       c = collections(:storage_classes_desired_default_confirmed_default)
756       # Cannot clear just one at a time.
757       assert_raise ArvadosModel::PermissionDeniedError do
758         c.update_attributes storage_classes_confirmed: []
759       end
760       c.reload
761       assert_raise ArvadosModel::PermissionDeniedError do
762         c.update_attributes storage_classes_confirmed_at: nil
763       end
764       # Can clear both at once.
765       c.reload
766       assert c.update_attributes(storage_classes_confirmed: [],
767                                  storage_classes_confirmed_at: nil)
768     end
769   end
770
771   [0, 2, 4, nil].each do |ask|
772     test "set replication_desired to #{ask.inspect}" do
773       Rails.configuration.Collections.DefaultReplication = 2
774       act_as_user users(:active) do
775         c = collections(:replication_undesired_unconfirmed)
776         c.update_attributes replication_desired: ask
777         assert_equal ask, c.replication_desired
778       end
779     end
780   end
781
782   test "replication_confirmed* can be set by admin user" do
783     c = collections(:replication_desired_2_unconfirmed)
784     act_as_user users(:admin) do
785       assert c.update_attributes(replication_confirmed: 2,
786                                  replication_confirmed_at: Time.now)
787     end
788   end
789
790   test "replication_confirmed* cannot be set by non-admin user" do
791     act_as_user users(:active) do
792       c = collections(:replication_desired_2_unconfirmed)
793       # Cannot set just one at a time.
794       assert_raise ArvadosModel::PermissionDeniedError do
795         c.update_attributes replication_confirmed: 1
796       end
797       assert_raise ArvadosModel::PermissionDeniedError do
798         c.update_attributes replication_confirmed_at: Time.now
799       end
800       # Cannot set both at once, either.
801       assert_raise ArvadosModel::PermissionDeniedError do
802         c.update_attributes(replication_confirmed: 1,
803                             replication_confirmed_at: Time.now)
804       end
805     end
806   end
807
808   test "replication_confirmed* can be cleared (but only together) by non-admin user" do
809     act_as_user users(:active) do
810       c = collections(:replication_desired_2_confirmed_2)
811       # Cannot clear just one at a time.
812       assert_raise ArvadosModel::PermissionDeniedError do
813         c.update_attributes replication_confirmed: nil
814       end
815       c.reload
816       assert_raise ArvadosModel::PermissionDeniedError do
817         c.update_attributes replication_confirmed_at: nil
818       end
819       # Can clear both at once.
820       c.reload
821       assert c.update_attributes(replication_confirmed: nil,
822                                  replication_confirmed_at: nil)
823     end
824   end
825
826   test "clear replication_confirmed* when introducing a new block in manifest" do
827     c = collections(:replication_desired_2_confirmed_2)
828     act_as_user users(:active) do
829       assert c.update_attributes(manifest_text: collections(:user_agreement).signed_manifest_text)
830       assert_nil c.replication_confirmed
831       assert_nil c.replication_confirmed_at
832     end
833   end
834
835   test "don't clear replication_confirmed* when just renaming a file" do
836     c = collections(:replication_desired_2_confirmed_2)
837     act_as_user users(:active) do
838       new_manifest = c.signed_manifest_text.sub(':bar', ':foo')
839       assert c.update_attributes(manifest_text: new_manifest)
840       assert_equal 2, c.replication_confirmed
841       assert_not_nil c.replication_confirmed_at
842     end
843   end
844
845   test "don't clear replication_confirmed* when just deleting a data block" do
846     c = collections(:replication_desired_2_confirmed_2)
847     act_as_user users(:active) do
848       new_manifest = c.signed_manifest_text
849       new_manifest.sub!(/ \S+:bar/, '')
850       new_manifest.sub!(/ acbd\S+/, '')
851
852       # Confirm that we did just remove a block from the manifest (if
853       # not, this test would pass without testing the relevant case):
854       assert_operator new_manifest.length+40, :<, c.signed_manifest_text.length
855
856       assert c.update_attributes(manifest_text: new_manifest)
857       assert_equal 2, c.replication_confirmed
858       assert_not_nil c.replication_confirmed_at
859     end
860   end
861
862   test 'signature expiry does not exceed trash_at' do
863     act_as_user users(:active) do
864       t0 = db_current_time
865       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
866       c.update_attributes! trash_at: (t0 + 1.hours)
867       c.reload
868       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
869       assert_operator sig_exp.to_i, :<=, (t0 + 1.hours).to_i
870     end
871   end
872
873   test 'far-future expiry date cannot be used to circumvent configured permission ttl' do
874     act_as_user users(:active) do
875       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n",
876                              name: 'foo',
877                              trash_at: db_current_time + 1.years)
878       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
879       expect_max_sig_exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
880       assert_operator c.trash_at.to_i, :>, expect_max_sig_exp
881       assert_operator sig_exp.to_i, :<=, expect_max_sig_exp
882     end
883   end
884
885   test "create collection with properties" do
886     act_as_system_user do
887       c = Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n",
888                             properties: {'property_1' => 'value_1'})
889       assert c.valid?
890       assert_equal 'value_1', c.properties['property_1']
891     end
892   end
893
894   test 'create, delete, recreate collection with same name and owner' do
895     act_as_user users(:active) do
896       # create collection with name
897       c = Collection.create(manifest_text: '',
898                             name: "test collection name")
899       assert c.valid?
900       uuid = c.uuid
901
902       c = Collection.readable_by(current_user).where(uuid: uuid)
903       assert_not_empty c, 'Should be able to find live collection'
904
905       # mark collection as expired
906       c.first.update_attributes!(trash_at: Time.new.strftime("%Y-%m-%d"))
907       c = Collection.readable_by(current_user).where(uuid: uuid)
908       assert_empty c, 'Should not be able to find expired collection'
909
910       # recreate collection with the same name
911       c = Collection.create(manifest_text: '',
912                             name: "test collection name")
913       assert c.valid?
914     end
915   end
916
917   test 'trash_at cannot be set too far in the past' do
918     act_as_user users(:active) do
919       t0 = db_current_time
920       c = Collection.create!(manifest_text: '', name: 'foo')
921       c.update_attributes! trash_at: (t0 - 2.weeks)
922       c.reload
923       assert_operator c.trash_at, :>, t0
924     end
925   end
926
927   now = Time.now
928   [['trash-to-delete interval negative',
929     :collection_owned_by_active,
930     {trash_at: now+2.weeks, delete_at: now},
931     {state: :invalid}],
932    ['now-to-delete interval short',
933     :collection_owned_by_active,
934     {trash_at: now+3.days, delete_at: now+7.days},
935     {state: :trash_future}],
936    ['now-to-delete interval short, trash=delete',
937     :collection_owned_by_active,
938     {trash_at: now+3.days, delete_at: now+3.days},
939     {state: :trash_future}],
940    ['trash-to-delete interval ok',
941     :collection_owned_by_active,
942     {trash_at: now, delete_at: now+15.days},
943     {state: :trash_now}],
944    ['trash-to-delete interval short, but far enough in future',
945     :collection_owned_by_active,
946     {trash_at: now+13.days, delete_at: now+15.days},
947     {state: :trash_future}],
948    ['trash by setting is_trashed bool',
949     :collection_owned_by_active,
950     {is_trashed: true},
951     {state: :trash_now}],
952    ['trash in future by setting just trash_at',
953     :collection_owned_by_active,
954     {trash_at: now+1.week},
955     {state: :trash_future}],
956    ['trash in future by setting trash_at and delete_at',
957     :collection_owned_by_active,
958     {trash_at: now+1.week, delete_at: now+4.weeks},
959     {state: :trash_future}],
960    ['untrash by clearing is_trashed bool',
961     :expired_collection,
962     {is_trashed: false},
963     {state: :not_trash}],
964   ].each do |test_name, fixture_name, updates, expect|
965     test test_name do
966       act_as_user users(:active) do
967         min_exp = (db_current_time +
968                    Rails.configuration.Collections.BlobSigningTTL)
969         if fixture_name == :expired_collection
970           # Fixture-finder shorthand doesn't find trashed collections
971           # because they're not in the default scope.
972           c = Collection.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
973         else
974           c = collections(fixture_name)
975         end
976         updates_ok = c.update_attributes(updates)
977         expect_valid = expect[:state] != :invalid
978         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
979         case expect[:state]
980         when :invalid
981           refute c.valid?
982         when :trash_now
983           assert c.is_trashed
984           assert_not_nil c.trash_at
985           assert_operator c.trash_at, :<=, db_current_time
986           assert_not_nil c.delete_at
987           assert_operator c.delete_at, :>=, min_exp
988         when :trash_future
989           refute c.is_trashed
990           assert_not_nil c.trash_at
991           assert_operator c.trash_at, :>, db_current_time
992           assert_not_nil c.delete_at
993           assert_operator c.delete_at, :>=, c.trash_at
994           # Currently this minimum interval is needed to prevent early
995           # garbage collection:
996           assert_operator c.delete_at, :>=, min_exp
997         when :not_trash
998           refute c.is_trashed
999           assert_nil c.trash_at
1000           assert_nil c.delete_at
1001         else
1002           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
1003         end
1004       end
1005     end
1006   end
1007
1008   test 'default trash interval > blob signature ttl' do
1009     Rails.configuration.Collections.DefaultTrashLifetime = 86400 * 21 # 3 weeks
1010     start = db_current_time
1011     act_as_user users(:active) do
1012       c = Collection.create!(manifest_text: '', name: 'foo')
1013       c.update_attributes!(trash_at: start + 86400.seconds)
1014       assert_operator c.delete_at, :>=, start + (86400*22).seconds
1015       assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
1016       c.destroy
1017
1018       c = Collection.create!(manifest_text: '', name: 'foo')
1019       c.update_attributes!(is_trashed: true)
1020       assert_operator c.delete_at, :>=, start + (86400*21).seconds
1021     end
1022   end
1023
1024   test "find_all_for_docker_image resolves names that look like hashes" do
1025     coll_list = Collection.
1026       find_all_for_docker_image('a' * 64, nil, [users(:active)])
1027     coll_uuids = coll_list.map(&:uuid)
1028     assert_includes(coll_uuids, collections(:docker_image).uuid)
1029   end
1030
1031   test "move collections to trash in SweepTrashedObjects" do
1032     c = collections(:trashed_on_next_sweep)
1033     refute_empty Collection.where('uuid=? and is_trashed=false', c.uuid)
1034     assert_raises(ActiveRecord::RecordNotUnique) do
1035       act_as_user users(:active) do
1036         Collection.create!(owner_uuid: c.owner_uuid,
1037                            name: c.name)
1038       end
1039     end
1040     SweepTrashedObjects.sweep_now
1041     c = Collection.where('uuid=? and is_trashed=true', c.uuid).first
1042     assert c
1043     act_as_user users(:active) do
1044       assert Collection.create!(owner_uuid: c.owner_uuid,
1045                                 name: c.name)
1046     end
1047   end
1048
1049   test "delete collections in SweepTrashedObjects" do
1050     uuid = 'zzzzz-4zz18-3u1p5umicfpqszp' # deleted_on_next_sweep
1051     assert_not_empty Collection.where(uuid: uuid)
1052     SweepTrashedObjects.sweep_now
1053     assert_empty Collection.where(uuid: uuid)
1054   end
1055
1056   test "delete referring links in SweepTrashedObjects" do
1057     uuid = collections(:trashed_on_next_sweep).uuid
1058     act_as_system_user do
1059       assert_raises ActiveRecord::RecordInvalid do
1060         # Cannot create because :trashed_on_next_sweep is already trashed
1061         Link.create!(head_uuid: uuid,
1062                      tail_uuid: system_user_uuid,
1063                      link_class: 'whatever',
1064                      name: 'something')
1065       end
1066
1067       # Bump trash_at to now + 1 minute
1068       Collection.where(uuid: uuid).
1069         update(trash_at: db_current_time + (1).minute)
1070
1071       # Not considered trashed now
1072       Link.create!(head_uuid: uuid,
1073                    tail_uuid: system_user_uuid,
1074                    link_class: 'whatever',
1075                    name: 'something')
1076     end
1077     past = db_current_time
1078     Collection.where(uuid: uuid).
1079       update_all(is_trashed: true, trash_at: past, delete_at: past)
1080     assert_not_empty Collection.where(uuid: uuid)
1081     SweepTrashedObjects.sweep_now
1082     assert_empty Collection.where(uuid: uuid)
1083   end
1084
1085   test "empty names are exempt from name uniqueness" do
1086     act_as_user users(:active) do
1087       c1 = Collection.new(name: nil, manifest_text: '', owner_uuid: groups(:aproject).uuid)
1088       assert c1.save
1089       c2 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1090       assert c2.save
1091       c3 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1092       assert c3.save
1093       c4 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1094       assert c4.save
1095       c5 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1096       assert_raises(ActiveRecord::RecordNotUnique) do
1097         c5.save
1098       end
1099     end
1100   end
1101
1102   test "create collections with managed properties" do
1103     Rails.configuration.Collections.ManagedProperties = ConfigLoader.to_OrderedOptions({
1104       'default_prop1' => {'Value' => 'prop1_value'},
1105       'responsible_person_uuid' => {'Function' => 'original_owner'}
1106     })
1107     # Test collection without initial properties
1108     act_as_user users(:active) do
1109       c = create_collection 'foo', Encoding::US_ASCII
1110       assert c.valid?
1111       assert_not_empty c.properties
1112       assert_equal 'prop1_value', c.properties['default_prop1']
1113       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1114     end
1115     # Test collection with default_prop1 property already set
1116     act_as_user users(:active) do
1117       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n",
1118                             properties: {'default_prop1' => 'custom_value'})
1119       assert c.valid?
1120       assert_not_empty c.properties
1121       assert_equal 'custom_value', c.properties['default_prop1']
1122       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1123     end
1124     # Test collection inside a sub project
1125     act_as_user users(:active) do
1126       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n",
1127                             owner_uuid: groups(:asubproject).uuid)
1128       assert c.valid?
1129       assert_not_empty c.properties
1130       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1131     end
1132   end
1133
1134   test "update collection with protected managed properties" do
1135     Rails.configuration.Collections.ManagedProperties = ConfigLoader.to_OrderedOptions({
1136       'default_prop1' => {'Value' => 'prop1_value', 'Protected' => true},
1137     })
1138     act_as_user users(:active) do
1139       c = create_collection 'foo', Encoding::US_ASCII
1140       assert c.valid?
1141       assert_not_empty c.properties
1142       assert_equal 'prop1_value', c.properties['default_prop1']
1143       # Add new property
1144       c.properties['prop2'] = 'value2'
1145       c.save!
1146       c.reload
1147       assert_equal 'value2', c.properties['prop2']
1148       # Try to change protected property's value
1149       c.properties['default_prop1'] = 'new_value'
1150       assert_raises(ArvadosModel::PermissionDeniedError) do
1151         c.save!
1152       end
1153       # Admins are allowed to change protected properties
1154       act_as_system_user do
1155         c.properties['default_prop1'] = 'new_value'
1156         c.save!
1157         c.reload
1158         assert_equal 'new_value', c.properties['default_prop1']
1159       end
1160     end
1161   end
1162
1163   test "collection names must be displayable in a filesystem" do
1164     set_user_from_auth :active
1165     ["", "{SOLIDUS}"].each do |subst|
1166       Rails.configuration.Collections.ForwardSlashNameSubstitution = subst
1167       c = Collection.create
1168       [[nil, true],
1169        ["", true],
1170        [".", false],
1171        ["..", false],
1172        ["...", true],
1173        ["..z..", true],
1174        ["foo/bar", subst != ""],
1175        ["../..", subst != ""],
1176        ["/", subst != ""],
1177       ].each do |name, valid|
1178         c.name = name
1179         assert_equal valid, c.valid?, "#{name.inspect} should be #{valid ? "valid" : "invalid"}"
1180       end
1181     end
1182   end
1183 end