]> git.arvados.org - arvados.git/blob - services/api/test/unit/arvados_model_test.rb
Merge branch '22394-project-tab-preference' into main. Closes #22394
[arvados.git] / services / api / test / unit / arvados_model_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
7 class ArvadosModelTest < ActiveSupport::TestCase
8   fixtures :all
9
10   def create_with_attrs attrs
11     a = Collection.create({properties: {'foo' => 'bar'}}.merge(attrs))
12     a if a.valid?
13   end
14
15   test 'non-admin cannot assign uuid' do
16     set_user_from_auth :active_trustedclient
17     want_uuid = Collection.generate_uuid
18     a = create_with_attrs(uuid: want_uuid)
19     assert_nil a, "Non-admin should not assign uuid."
20   end
21
22   test 'admin can assign valid uuid' do
23     set_user_from_auth :admin_trustedclient
24     want_uuid = Collection.generate_uuid
25     a = create_with_attrs(uuid: want_uuid)
26     assert_equal want_uuid, a.uuid, "Admin should assign valid uuid."
27     assert a.uuid.length==27, "Auto assigned uuid length is wrong."
28   end
29
30   test 'admin cannot assign uuid with wrong object type' do
31     set_user_from_auth :admin_trustedclient
32     want_uuid = Group.generate_uuid
33     a = create_with_attrs(uuid: want_uuid)
34     assert_nil a, "Admin should not be able to assign invalid uuid."
35   end
36
37   test 'admin cannot assign badly formed uuid' do
38     set_user_from_auth :admin_trustedclient
39     a = create_with_attrs(uuid: "ntoheunthaoesunhasoeuhtnsaoeunhtsth")
40     assert_nil a, "Admin should not be able to assign invalid uuid."
41   end
42
43   test 'admin cannot assign empty uuid' do
44     set_user_from_auth :admin_trustedclient
45     a = create_with_attrs(uuid: "")
46     assert_nil a, "Admin cannot assign empty uuid."
47   end
48
49   [ {:a => 'foo'},
50     {'a' => :foo},
51     {:a => ['foo', 'bar']},
52     {'a' => [:foo, 'bar']},
53     {'a' => ['foo', :bar]},
54     {:a => [:foo, :bar]},
55     {:a => {'foo' => {'bar' => 'baz'}}},
56     {'a' => {:foo => {'bar' => 'baz'}}},
57     {'a' => {'foo' => {:bar => 'baz'}}},
58     {'a' => {'foo' => {'bar' => :baz}}},
59     {'a' => {'foo' => ['bar', :baz]}},
60   ].each do |x|
61     test "prevent symbol keys in serialized db columns: #{x.inspect}" do
62       set_user_from_auth :active
63       link = Link.create!(link_class: 'test',
64                           properties: x)
65       raw = ActiveRecord::Base.connection.
66           select_value("select properties from links where uuid='#{link.uuid}'")
67       refute_match(/:[fb]/, raw)
68     end
69   end
70
71   [ {['foo'] => 'bar'},
72     {'a' => {['foo', :foo] => 'bar'}},
73     {'a' => {{'foo' => 'bar'} => 'bar'}},
74     {'a' => {['foo', :foo] => ['bar', 'baz']}},
75   ].each do |x|
76     test "refuse non-string keys in serialized db columns: #{x.inspect}" do
77       set_user_from_auth :active
78       assert_raises(ArgumentError) do
79         Link.create!(link_class: 'test',
80                      properties: x)
81       end
82     end
83   end
84
85   test "No HashWithIndifferentAccess in database" do
86     set_user_from_auth :admin_trustedclient
87     link = Link.create!(link_class: 'test',
88                         properties: {'foo' => 'bar'}.with_indifferent_access)
89     raw = ActiveRecord::Base.connection.
90       select_value("select properties from links where uuid='#{link.uuid}'")
91     assert_equal '{"foo": "bar"}', raw
92   end
93
94   test "store long string" do
95     set_user_from_auth :active
96     longstring = "a"
97     while longstring.length < 2**16
98       longstring = longstring + longstring
99     end
100     g = Group.create! name: 'Has a long description', description: longstring, group_class: "project"
101     g = Group.find_by_uuid g.uuid
102     assert_equal g.description, longstring
103   end
104
105   [['uuid', {unique: true}],
106    ['owner_uuid', {}]].each do |the_column, requires|
107     test "unique index on all models with #{the_column}" do
108       checked = 0
109       ActiveRecord::Base.connection.tables.each do |table|
110         columns = ActiveRecord::Base.connection.columns(table)
111
112         next unless columns.collect(&:name).include? the_column
113
114         indexes = ActiveRecord::Base.connection.indexes(table).reject do |index|
115           requires.map do |key, val|
116             index.send(key) == val
117           end.include? false
118         end
119         assert_includes indexes.collect(&:columns), [the_column], 'no index'
120         checked += 1
121       end
122       # Sanity check: make sure we didn't just systematically miss everything.
123       assert_operator(10, :<, checked,
124                       "Only #{checked} tables have a #{the_column}?!")
125     end
126   end
127
128   test "search index exists on models that go into projects" do
129     ActiveRecord::Base.descendants.each do |model_class|
130       next if model_class.abstract_class?
131       next if !model_class.respond_to?('searchable_columns')
132
133       search_index_columns = model_class.searchable_columns('ilike')
134       # Disappointing, but text columns aren't indexed yet.
135       search_index_columns -= model_class.columns.select { |c|
136         c.type == :text or c.name == 'description' or c.name == 'file_names'
137       }.collect(&:name)
138       next if search_index_columns.empty?
139
140       indexes = ActiveRecord::Base.connection.indexes(model_class.table_name)
141       search_index_by_columns = indexes.select do |index|
142         # After rails 5.0 upgrade, AR::Base.connection.indexes() started to include
143         # GIN indexes, with its 'columns' attribute being a String like
144         # 'to_tsvector(...)'
145         index.columns.is_a?(Array) ? index.columns.sort == search_index_columns.sort : false
146       end
147       search_index_by_name = indexes.select do |index|
148         index.name == "#{model_class.table_name}_search_index"
149       end
150       assert !search_index_by_columns.empty?, "#{model_class.table_name} (#{model_class.to_s}) has no search index with columns #{search_index_columns}. Instead found search index with columns #{search_index_by_name.first.andand.columns}"
151     end
152   end
153
154   [Collection, ContainerRequest, Group, Workflow].each do |model|
155     test "trigram index exists on #{model} model" do
156       expect = model.full_text_searchable_columns
157       conn = ActiveRecord::Base.connection
158       index_name = "#{model.table_name}_trgm_text_search_idx"
159       indexes = conn.exec_query("SELECT indexdef FROM pg_indexes WHERE tablename = '#{model.table_name}' AND indexname = '#{index_name}'")
160       assert_not_equal(indexes.length, 0)
161       indexes.each do |res|
162         searchable = res['indexdef'].scan(/COALESCE\(+([A-Za-z_]+)/).flatten
163         assert_equal(
164           searchable, expect,
165           "Invalid or no trigram index for #{model} named #{index_name}\nexpect: #{expect.inspect}\nfound: #{searchable}",
166         )
167       end
168     end
169
170     test "UUID and hash columns are excluded from #{model} full text index" do
171       assert_equal(
172         model.full_text_searchable_columns & full_text_excluded_columns, [],
173         "UUID/hash columns returned by #{model}.full_text_searchable_columns",
174       )
175     end
176   end
177
178   test "selectable_attributes includes database attributes" do
179     assert_includes(Collection.selectable_attributes, "name")
180   end
181
182   test "selectable_attributes includes non-database attributes" do
183     assert_includes(Collection.selectable_attributes, "unsigned_manifest_text")
184   end
185
186   test "selectable_attributes includes common attributes in extensions" do
187     assert_includes(Collection.selectable_attributes, "uuid")
188   end
189
190   test "selectable_attributes does not include unexposed attributes" do
191     refute_includes(Collection.selectable_attributes, "id")
192   end
193
194   test "selectable_attributes on a non-default template" do
195     attr_a = Collection.selectable_attributes(:common)
196     assert_includes(attr_a, "uuid")
197     refute_includes(attr_a, "name")
198   end
199
200   test 'create and retrieve using created_at time' do
201     set_user_from_auth :active
202     group = Group.create! name: 'test create and retrieve group', group_class: "project"
203     assert group.valid?, "group is not valid"
204
205     results = Group.where(created_at: group.created_at)
206     assert_includes results.map(&:uuid), group.uuid,
207       "Expected new group uuid in results when searched with its created_at timestamp"
208   end
209
210   test 'create and update twice and expect different update times' do
211     set_user_from_auth :active
212     group = Group.create! name: 'test create and retrieve group', group_class: "project"
213     assert group.valid?, "group is not valid"
214
215     # update 1
216     group.update!(name: "test create and update name 1")
217     results = Group.where(uuid: group.uuid)
218     assert_equal "test create and update name 1", results.first.name, "Expected name to be updated to 1"
219     modified_at_1 = results.first.modified_at.to_f
220
221     # update 2
222     group.update!(name: "test create and update name 2")
223     results = Group.where(uuid: group.uuid)
224     assert_equal "test create and update name 2", results.first.name, "Expected name to be updated to 2"
225     modified_at_2 = results.first.modified_at.to_f
226
227     assert_equal true, (modified_at_2 > modified_at_1), "Expected modified time 2 to be newer than 1"
228   end
229
230   test 'jsonb column' do
231     set_user_from_auth :active
232
233     c = Collection.create!(properties: {})
234     assert_equal({}, c.properties)
235
236     c.update(properties: {'foo' => 'foo'})
237     c.reload
238     assert_equal({'foo' => 'foo'}, c.properties)
239
240     c.update(properties: nil)
241     c.reload
242     assert_equal({}, c.properties)
243
244     c.update(properties: {foo: 'bar'})
245     assert_equal({'foo' => 'bar'}, c.properties)
246     c.reload
247     assert_equal({'foo' => 'bar'}, c.properties)
248   end
249
250   {
251     Collection => ["description", "manifest_text"],
252     Container => [
253       "command",
254       "environment",
255       "output_properties",
256       "runtime_constraints",
257       "secret_mounts",
258     ],
259     ContainerRequest => [
260       "command",
261       "environment",
262       "mounts",
263       "output_glob",
264       "output_properties",
265       "properties",
266       "runtime_constraints",
267       "secret_mounts",
268     ],
269     Group => ["description", "properties"],
270     Log => ["properties", "summary"],
271   }.each_pair do |model, expect|
272     test "#{model.name} limits expected columns on index" do
273       assert_equal(
274         (model.limit_index_columns_read & expect).sort,
275         expect.sort,
276       )
277     end
278   end
279
280   {
281     Collection => ["delete_at", "preserve_version", "trash_at", "version"],
282     Container => ["cost", "progress", "state", "subrequests_cost"],
283     ContainerRequest => ["container_uuid", "cwd", "requesting_container_uuid"],
284     Group => ["group_class", "is_trashed", "trashed_at"],
285     Log => ["event_at", "event_type"],
286   }.each_pair do |model, colnames|
287     test "#{model.name} does not limit expected columns on index" do
288       assert_equal(model.limit_index_columns_read & colnames, [])
289     end
290   end
291
292   test 'serialized attributes dirty tracking with audit log settings' do
293     Rails.configuration.AuditLogs.MaxDeleteBatch = 1000
294     set_user_from_auth :admin
295     [false, true].each do |auditlogs_enabled|
296       if auditlogs_enabled
297         Rails.configuration.AuditLogs.MaxAge = 3600
298       else
299         Rails.configuration.AuditLogs.MaxAge = 0
300       end
301       tested_serialized = false
302       [
303         User.find_by_uuid(users(:active).uuid),
304         ContainerRequest.find_by_uuid(container_requests(:queued).uuid),
305         Container.find_by_uuid(containers(:queued).uuid),
306         Group.find_by_uuid(groups(:afiltergroup).uuid),
307         Collection.find_by_uuid(collections(:collection_with_one_property).uuid),
308       ].each do |obj|
309         if !obj.class.serialized_attributes.empty?
310           tested_serialized = true
311         end
312         # obj shouldn't have changed since it's just retrieved from the database
313         assert_not(obj.changed?, "#{obj.class} model's attribute(s) appear as changed: '#{obj.changes.keys.join(',')}' with audit logs #{auditlogs_enabled ? '': 'not '}enabled.")
314       end
315       assert(tested_serialized, "did not test any models with serialized attributes")
316     end
317   end
318 end