Fix 2.4.2 upgrade notes formatting refs #19330
[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 'fix_collection_versions_timestamps'
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     [". 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
69       act_as_system_user do
70         c = Collection.create(manifest_text: manifest)
71         assert_equal count, c.file_count
72         assert_equal size, c.file_size_total
73       end
74     end
75   end
76
77   test "file stats cannot be changed unless through manifest change" do
78     act_as_system_user do
79       # Direct changes to file stats should be ignored
80       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n")
81       c.file_count = 6
82       c.file_size_total = 30
83       assert c.valid?
84       assert_equal 1, c.file_count
85       assert_equal 34, c.file_size_total
86
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)
89       assert c.valid?
90       assert_equal 1, c.file_count
91       assert_equal 34, c.file_size_total
92
93       # Updating the manifest should change file stats
94       c.update_attributes(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:34:foo2.txt\n")
95       assert c.valid?
96       assert_equal 2, c.file_count
97       assert_equal 68, c.file_size_total
98
99       # Updating file stats and the manifest should use manifest values
100       c.update_attributes(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count:10, file_size_total: 10)
101       assert c.valid?
102       assert_equal 1, c.file_count
103       assert_equal 34, c.file_size_total
104
105       # Updating just the file stats should be ignored
106       c.update_attributes(file_count: 10, file_size_total: 10)
107       assert c.valid?
108       assert_equal 1, c.file_count
109       assert_equal 34, c.file_size_total
110     end
111   end
112
113   [
114     nil,
115     "",
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)
121         assert c.valid?
122       end
123     end
124   end
125
126   [
127     ". 0:0:foo.txt",
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
135         assert c.valid?
136
137         c.update_attribute 'manifest_text', manifest_text
138         assert !c.valid?
139       end
140     end
141   end
142
143   [
144     nil,
145     "",
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
151         assert c.valid?
152
153         c.update_attribute 'manifest_text', manifest_text
154         assert c.valid?
155       end
156     end
157   end
158
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
165       assert c.valid?
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_attributes!({'name' => 'bar'})
170       c.reload
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
176       c.reload
177       assert_equal fifteen_min_ago.to_i, c.modified_at.to_i
178       c.update_attributes!({'name' => 'baz'})
179       c.reload
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_attributes!({'name' => 'foobar'})
184       c.reload
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)
195       c.reload
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_attributes!({'name' => 'foobarbaz'})
201       c.reload
202       assert_equal 'foobarbaz', c.name
203       assert_equal 3, c.version
204     end
205   end
206
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
213       assert c.valid?
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
217       c.update_attributes!({
218         'name' => 'bar'
219       })
220       c.reload
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.
226       c.update_attributes!({
227         'name' => 'baz',
228         'preserve_version' => true
229       })
230       c.reload
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
237       c.update_attributes!({
238         'preserve_version' => false,
239         'replication_desired' => 2
240       })
241       c.reload
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
246       c.update_attributes!({
247         'preserve_version' => false,
248         'name' => 'foobar'
249       })
250       c.reload
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_attributes!({'preserve_version' => true})
256       c.reload
257       assert_equal 3, c.version
258       assert_equal true, c.preserve_version
259     end
260   end
261
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
265       assert c.valid?
266       assert_equal false, c.preserve_version
267       modified_at = c.modified_at.to_f
268       c.update_attributes!({'preserve_version' => true})
269       c.reload
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'
273     end
274   end
275
276   [
277     ['version', 10],
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
284         assert c.valid?
285         assert_equal 1, c.version
286
287         assert_raises(ActiveRecord::RecordInvalid) do
288           c.update_attributes!({
289             name => new_value
290           })
291         end
292       end
293     end
294   end
295
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
302       assert c.valid?
303       assert_equal 1, c.version
304       # Make changes so that a new version is created
305       c.update_attributes!({'name' => 'bar'})
306       c.reload
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_attributes!({'uuid' => new_uuid})
313       c.reload
314       assert_equal new_uuid, c.uuid
315       assert_equal 2, Collection.where(current_version_uuid: new_uuid).count
316     end
317   end
318
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'
323   end
324
325   [
326     [
327       true,
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},
330     ],
331     [
332       true,
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}}},
335     ],
336     [
337       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'}},
340     ],
341     [
342       false,
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},
345     ],
346     [
347       false,
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},
350     ],
351     [
352       false,
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},
355     ],
356     [
357       false,
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},
360     ],
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
366         assert c.valid?
367         c.update_attributes!({'properties' => value_1})
368         c.reload
369         assert c.changes.keys.empty?
370         c.properties = value_2
371         if should_be_equal
372           assert c.changes.keys.empty?, "Properties #{value_1.inspect} should be equal to #{value_2.inspect}"
373         else
374           refute c.changes.keys.empty?, "Properties #{value_1.inspect} should not be equal to #{value_2.inspect}"
375         end
376       end
377     end
378   end
379
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
386       assert c.valid?
387       original_version_modified_at = c.modified_at.to_f
388       # Make changes so that a new version is created
389       c.update_attributes!({'name' => 'bar'})
390       c.reload
391       assert_equal 2, c.version
392       # Get the old version
393       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
394       assert_not_nil c_old
395
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
399
400       # Make update on current version so old version get the attribute synced;
401       # its modified_at should not change.
402       new_replication = 3
403       c.update_attributes!({'replication_desired' => new_replication})
404       c.reload
405       assert_equal new_replication, c.replication_desired
406       c_old.reload
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
410     end
411   end
412
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
418     ]
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
425     end
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
433     end
434   end
435
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
442       assert c.valid?
443       # Make changes so that a new version is created
444       c.update_attributes!({'name' => 'bar'})
445       c.reload
446       assert_equal 2, c.version
447       # Get the old version
448       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
449       assert_not_nil c_old
450       # With collection versioning still being enabled, try to update
451       c_old.name = 'this was foo'
452       assert c_old.invalid?
453       c_old.reload
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?
458       c_old.reload
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?
463     end
464   end
465
466   [
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
477         assert c.valid?
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
481         # updated on both
482         c.update_attributes!({'name' => 'bar', attr => first_val})
483         c.reload
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_attributes!({attr => second_val})
491         c.reload
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]
496       end
497     end
498   end
499
500   [
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
519         assert c.valid?
520         assert_equal 'foo', c.name
521
522         # Check current version attributes
523         assert_equal 1, c.version
524         assert_equal c.uuid, c.current_version_uuid
525
526         # Update attribute and check if version number should be incremented
527         old_value = c.attributes[attr]
528         c.update_attributes!({attr => val})
529         assert_equal new_version_expected, c.version == 2
530         assert_equal val, c.attributes[attr]
531
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
536           assert_not_nil s
537           assert_equal old_value, s.attributes[attr]
538         else
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
543         end
544       end
545     end
546   end
547
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
554       assert col1.valid?
555       assert_equal 1, col1.version
556
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
560       assert col2.valid?
561       assert_equal 1, col2.version
562       col2.update_attributes({name: 'baz'})
563       assert_equal 2, col2.version
564
565       # Try to make col2 a past version of col1. It shouldn't be possible
566       col2.update_attributes({current_version_uuid: col1.uuid})
567       assert col2.invalid?
568       col2.reload
569       assert_not_equal col1.uuid, col2.current_version_uuid
570     end
571   end
572
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
579       assert col.valid?
580       assert_equal 1, col.version
581
582       # Simulate simultaneous updates
583       c1 = Collection.where(uuid: col.uuid).first
584       assert_equal 1, c1.version
585       c1.name = 'bar'
586       c2 = Collection.where(uuid: col.uuid).first
587       c2.description = 'foo collection'
588       c1.save!
589       assert_equal 1, c2.version
590       # with_lock forces a reload, so this shouldn't produce an unique violation error
591       c2.save!
592       assert_equal 3, c2.version
593       assert_equal 'foo collection', c2.description
594     end
595   end
596
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
600       assert c.valid?
601       created_file_names = c.file_names
602       assert created_file_names
603       assert_match(/foo.txt/, c.file_names)
604
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)
608     end
609   end
610
611   [
612     [2**8, false],
613     [2**18, true],
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
619         manifest_text = ''
620         index = 0
621         while manifest_text.length < manifest_size
622           manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
623           index += 1
624         end
625         manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
626         c = Collection.create(manifest_text: manifest_text)
627
628         assert c.valid?
629         assert c.file_names
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)
635         end
636       end
637     end
638   end
639
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")
646     end
647
648     [
649       ['foo', true],
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
659       ['subdir2', true],
660       ['subdir2/', true],
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(?)",
668                                  "#{search_filters}")
669       if expect_results
670         refute_empty results
671       else
672         assert_empty results
673       end
674     end
675   end
676
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)
686       assert c.valid?
687       assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
688                    c.portable_data_hash)
689     end
690   end
691
692   pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
693   pdhmd5 = Digest::MD5.hexdigest pdhmanifest
694   [[true, nil],
695    [true, pdhmd5],
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
709     end
710   end
711
712   test "storage_classes_desired default respects config" do
713     saved = Rails.configuration.DefaultStorageClasses
714     Rails.configuration.DefaultStorageClasses = ["foo"]
715     begin
716       act_as_user users(:active) do
717         c = Collection.create!
718         assert_equal ["foo"], c.storage_classes_desired
719       end
720     ensure
721       Rails.configuration.DefaultStorageClasses = saved
722     end
723   end
724
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_attributes storage_classes_desired: ["hot"]
729       assert_equal ["hot"], c.storage_classes_desired
730       assert_raise ArvadosModel::InvalidStateTransitionError do
731         c.update_attributes storage_classes_desired: []
732       end
733     end
734   end
735
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_attributes(storage_classes_desired: ["default", "a_string"],
740                                  storage_classes_confirmed: ["another_string"])
741       [
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_attributes({attr => val})
749         end
750       end
751     end
752   end
753
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_attributes(storage_classes_confirmed: ["default"],
758                                  storage_classes_confirmed_at: Time.now)
759     end
760   end
761
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_attributes storage_classes_confirmed: ["default"]
768       end
769       c.reload
770       assert_raise ArvadosModel::PermissionDeniedError do
771         c.update_attributes storage_classes_confirmed_at: Time.now
772       end
773       # Cannot set bot at once, either.
774       c.reload
775       assert_raise ArvadosModel::PermissionDeniedError do
776         assert c.update_attributes(storage_classes_confirmed: ["default"],
777                                    storage_classes_confirmed_at: Time.now)
778       end
779     end
780   end
781
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_attributes storage_classes_confirmed: []
788       end
789       c.reload
790       assert_raise ArvadosModel::PermissionDeniedError do
791         c.update_attributes storage_classes_confirmed_at: nil
792       end
793       # Can clear both at once.
794       c.reload
795       assert c.update_attributes(storage_classes_confirmed: [],
796                                  storage_classes_confirmed_at: nil)
797     end
798   end
799
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_attributes replication_desired: ask
806         assert_equal ask, c.replication_desired
807       end
808     end
809   end
810
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_attributes(replication_confirmed: 2,
815                                  replication_confirmed_at: Time.now)
816     end
817   end
818
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_attributes replication_confirmed: 1
825       end
826       assert_raise ArvadosModel::PermissionDeniedError do
827         c.update_attributes replication_confirmed_at: Time.now
828       end
829       # Cannot set both at once, either.
830       assert_raise ArvadosModel::PermissionDeniedError do
831         c.update_attributes(replication_confirmed: 1,
832                             replication_confirmed_at: Time.now)
833       end
834     end
835   end
836
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_attributes replication_confirmed: nil
843       end
844       c.reload
845       assert_raise ArvadosModel::PermissionDeniedError do
846         c.update_attributes replication_confirmed_at: nil
847       end
848       # Can clear both at once.
849       c.reload
850       assert c.update_attributes(replication_confirmed: nil,
851                                  replication_confirmed_at: nil)
852     end
853   end
854
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_attributes(manifest_text: collections(:user_agreement).signed_manifest_text_only_for_tests)
859       assert_nil c.replication_confirmed
860       assert_nil c.replication_confirmed_at
861     end
862   end
863
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_attributes(manifest_text: new_manifest)
869       assert_equal 2, c.replication_confirmed
870       assert_not_nil c.replication_confirmed_at
871     end
872   end
873
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+/, '')
880
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
884
885       assert c.update_attributes(manifest_text: new_manifest)
886       assert_equal 2, c.replication_confirmed
887       assert_not_nil c.replication_confirmed_at
888     end
889   end
890
891   test 'signature expiry does not exceed trash_at' do
892     act_as_user users(:active) do
893       t0 = db_current_time
894       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
895       c.update_attributes! trash_at: (t0 + 1.hours)
896       c.reload
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
899     end
900   end
901
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",
905                              name: 'foo',
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
911     end
912   end
913
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'})
918       assert c.valid?
919       assert_equal 'value_1', c.properties['property_1']
920     end
921   end
922
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")
928       assert c.valid?
929       uuid = c.uuid
930
931       c = Collection.readable_by(current_user).where(uuid: uuid)
932       assert_not_empty c, 'Should be able to find live collection'
933
934       # mark collection as expired
935       c.first.update_attributes!(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'
938
939       # recreate collection with the same name
940       c = Collection.create(manifest_text: '',
941                             name: "test collection name")
942       assert c.valid?
943     end
944   end
945
946   test 'trash_at cannot be set too far in the past' do
947     act_as_user users(:active) do
948       t0 = db_current_time
949       c = Collection.create!(manifest_text: '', name: 'foo')
950       c.update_attributes! trash_at: (t0 - 2.weeks)
951       c.reload
952       assert_operator c.trash_at, :>, t0
953     end
954   end
955
956   now = Time.now
957   [['trash-to-delete interval negative',
958     :collection_owned_by_active,
959     {trash_at: now+2.weeks, delete_at: now},
960     {state: :invalid}],
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,
979     {is_trashed: true},
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',
990     :expired_collection,
991     {is_trashed: false},
992     {state: :not_trash}],
993   ].each do |test_name, fixture_name, updates, expect|
994     test test_name do
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')
1002         else
1003           c = collections(fixture_name)
1004         end
1005         updates_ok = c.update_attributes(updates)
1006         expect_valid = expect[:state] != :invalid
1007         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
1008         case expect[:state]
1009         when :invalid
1010           refute c.valid?
1011         when :trash_now
1012           assert c.is_trashed
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
1017         when :trash_future
1018           refute c.is_trashed
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
1026         when :not_trash
1027           refute c.is_trashed
1028           assert_nil c.trash_at
1029           assert_nil c.delete_at
1030         else
1031           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
1032         end
1033       end
1034     end
1035   end
1036
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_attributes!(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
1045       c.destroy
1046
1047       c = Collection.create!(manifest_text: '', name: 'foo')
1048       c.update_attributes!(is_trashed: true)
1049       assert_operator c.delete_at, :>=, start + (86400*21).seconds
1050     end
1051   end
1052
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)
1058   end
1059
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)
1063       assert c1.save
1064       c2 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1065       assert c2.save
1066       c3 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1067       assert c3.save
1068       c4 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1069       assert c4.save
1070       c5 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1071       assert_raises(ActiveRecord::RecordNotUnique) do
1072         c5.save
1073       end
1074     end
1075   end
1076
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'}
1081     })
1082     # Test collection without initial properties
1083     act_as_user users(:active) do
1084       c = create_collection 'foo', Encoding::US_ASCII
1085       assert c.valid?
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']
1089     end
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'})
1094       assert c.valid?
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']
1098     end
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)
1103       assert c.valid?
1104       assert_not_empty c.properties
1105       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1106     end
1107   end
1108
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},
1112     })
1113     act_as_user users(:active) do
1114       c = create_collection 'foo', Encoding::US_ASCII
1115       assert c.valid?
1116       assert_not_empty c.properties
1117       assert_equal 'prop1_value', c.properties['default_prop1']
1118       # Add new property
1119       c.properties['prop2'] = 'value2'
1120       c.save!
1121       c.reload
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
1126         c.save!
1127       end
1128       # Admins are allowed to change protected properties
1129       act_as_system_user do
1130         c.properties['default_prop1'] = 'new_value'
1131         c.save!
1132         c.reload
1133         assert_equal 'new_value', c.properties['default_prop1']
1134       end
1135     end
1136   end
1137
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
1143       [[nil, true],
1144        ["", true],
1145        [".", false],
1146        ["..", false],
1147        ["...", true],
1148        ["..z..", true],
1149        ["foo/bar", subst != ""],
1150        ["../..", subst != ""],
1151        ["/", subst != ""],
1152       ].each do |name, valid|
1153         c.name = name
1154         assert_equal valid, c.valid?, "#{name.inspect} should be #{valid ? "valid" : "invalid"}"
1155       end
1156     end
1157   end
1158 end