Merge branch 'patch-1' of https://github.com/mr-c/arvados into mr-c-patch-1
[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 = Specimen.create({material: 'caloric'}.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 = Specimen.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 = Specimen.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 = Human.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     all_tables =  ActiveRecord::Base.connection.tables
130     all_tables.delete 'schema_migrations'
131     all_tables.delete 'permission_refresh_lock'
132     all_tables.delete 'ar_internal_metadata'
133
134     all_tables.each do |table|
135       table_class = table.classify.constantize
136       if table_class.respond_to?('searchable_columns')
137         search_index_columns = table_class.searchable_columns('ilike')
138         # Disappointing, but text columns aren't indexed yet.
139         search_index_columns -= table_class.columns.select { |c|
140           c.type == :text or c.name == 'description' or c.name == 'file_names'
141         }.collect(&:name)
142
143         indexes = ActiveRecord::Base.connection.indexes(table)
144         search_index_by_columns = indexes.select do |index|
145           # After rails 5.0 upgrade, AR::Base.connection.indexes() started to include
146           # GIN indexes, with its 'columns' attribute being a String like
147           # 'to_tsvector(...)'
148           index.columns.is_a?(Array) ? index.columns.sort == search_index_columns.sort : false
149         end
150         search_index_by_name = indexes.select do |index|
151           index.name == "#{table}_search_index"
152         end
153         assert !search_index_by_columns.empty?, "#{table} has no search index with columns #{search_index_columns}. Instead found search index with columns #{search_index_by_name.first.andand.columns}"
154       end
155     end
156   end
157
158   test "full text search index exists on models" do
159     indexes = {}
160     conn = ActiveRecord::Base.connection
161     conn.exec_query("SELECT i.relname as indname,
162       i.relowner as indowner,
163       idx.indrelid::regclass::text as table,
164       am.amname as indam,
165       idx.indkey,
166       ARRAY(
167             SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
168                    FROM generate_subscripts(idx.indkey, 1) as k
169                    ORDER BY k
170                    ) as keys,
171       idx.indexprs IS NOT NULL as indexprs,
172       idx.indpred IS NOT NULL as indpred
173       FROM   pg_index as idx
174       JOIN   pg_class as i
175       ON     i.oid = idx.indexrelid
176       JOIN   pg_am as am
177       ON     i.relam = am.oid
178       JOIN   pg_namespace as ns
179       ON     ns.oid = i.relnamespace
180       AND    ns.nspname = ANY(current_schemas(false))").each do |idx|
181       if idx['keys'].match(/to_tsvector/)
182         indexes[idx['table']] ||= []
183         indexes[idx['table']] << idx
184       end
185     end
186     fts_tables =  ["collections", "container_requests", "groups", "jobs",
187                    "pipeline_instances", "pipeline_templates", "workflows"]
188     fts_tables.each do |table|
189       table_class = table.classify.constantize
190       if table_class.respond_to?('full_text_searchable_columns')
191         expect = table_class.full_text_searchable_columns
192         ok = false
193         indexes[table].andand.each do |idx|
194           if expect == idx['keys'].scan(/COALESCE\(([A-Za-z_]+)/).flatten
195             ok = true
196           end
197         end
198         assert ok, "#{table} has no full-text index\nexpect: #{expect.inspect}\nfound: #{indexes[table].inspect}"
199       end
200     end
201   end
202
203   [
204     %w[collections collections_trgm_text_search_idx],
205     %w[container_requests container_requests_trgm_text_search_idx],
206     %w[groups groups_trgm_text_search_idx],
207     %w[jobs jobs_trgm_text_search_idx],
208     %w[pipeline_instances pipeline_instances_trgm_text_search_idx],
209     %w[pipeline_templates pipeline_templates_trgm_text_search_idx],
210     %w[workflows workflows_trgm_text_search_idx]
211   ].each do |model|
212     table = model[0]
213     indexname = model[1]
214     test "trigram index exists on #{table} model" do
215       table_class = table.classify.constantize
216       expect = table_class.full_text_searchable_columns
217       ok = false
218       conn = ActiveRecord::Base.connection
219       conn.exec_query("SELECT indexdef FROM pg_indexes WHERE tablename = '#{table}' AND indexname = '#{indexname}'").each do |res|
220         searchable = res['indexdef'].scan(/COALESCE\(+([A-Za-z_]+)/).flatten
221         ok = (expect == searchable)
222         assert ok, "Invalid or no trigram index on #{table} named #{indexname}\nexpect: #{expect.inspect}\nfound: #{searchable}"
223       end
224     end
225   end
226
227   test "selectable_attributes includes database attributes" do
228     assert_includes(Job.selectable_attributes, "success")
229   end
230
231   test "selectable_attributes includes non-database attributes" do
232     assert_includes(Job.selectable_attributes, "node_uuids")
233   end
234
235   test "selectable_attributes includes common attributes in extensions" do
236     assert_includes(Job.selectable_attributes, "uuid")
237   end
238
239   test "selectable_attributes does not include unexposed attributes" do
240     refute_includes(Job.selectable_attributes, "nodes")
241   end
242
243   test "selectable_attributes on a non-default template" do
244     attr_a = Job.selectable_attributes(:common)
245     assert_includes(attr_a, "uuid")
246     refute_includes(attr_a, "success")
247   end
248
249   test 'create and retrieve using created_at time' do
250     set_user_from_auth :active
251     group = Group.create! name: 'test create and retrieve group', group_class: "project"
252     assert group.valid?, "group is not valid"
253
254     results = Group.where(created_at: group.created_at)
255     assert_includes results.map(&:uuid), group.uuid,
256       "Expected new group uuid in results when searched with its created_at timestamp"
257   end
258
259   test 'create and update twice and expect different update times' do
260     set_user_from_auth :active
261     group = Group.create! name: 'test create and retrieve group', group_class: "project"
262     assert group.valid?, "group is not valid"
263
264     # update 1
265     group.update_attributes!(name: "test create and update name 1")
266     results = Group.where(uuid: group.uuid)
267     assert_equal "test create and update name 1", results.first.name, "Expected name to be updated to 1"
268     updated_at_1 = results.first.updated_at.to_f
269
270     # update 2
271     group.update_attributes!(name: "test create and update name 2")
272     results = Group.where(uuid: group.uuid)
273     assert_equal "test create and update name 2", results.first.name, "Expected name to be updated to 2"
274     updated_at_2 = results.first.updated_at.to_f
275
276     assert_equal true, (updated_at_2 > updated_at_1), "Expected updated time 2 to be newer than 1"
277   end
278
279   test 'jsonb column' do
280     set_user_from_auth :active
281
282     c = Collection.create!(properties: {})
283     assert_equal({}, c.properties)
284
285     c.update_attributes(properties: {'foo' => 'foo'})
286     c.reload
287     assert_equal({'foo' => 'foo'}, c.properties)
288
289     c.update_attributes(properties: nil)
290     c.reload
291     assert_equal({}, c.properties)
292
293     c.update_attributes(properties: {foo: 'bar'})
294     assert_equal({'foo' => 'bar'}, c.properties)
295     c.reload
296     assert_equal({'foo' => 'bar'}, c.properties)
297   end
298 end