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