3645d0507b2db53f8316e7212d2b1434bbed30e6
[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 "Stringify symbols coming from serialized attribute in database" do
86     set_user_from_auth :admin_trustedclient
87     fixed = Link.find_by_uuid(links(:has_symbol_keys_in_database_somehow).uuid)
88     assert_equal(["baz", "foo"], fixed.properties.keys.sort,
89                  "Hash symbol keys from DB did not get stringified.")
90     assert_equal(['waz', 'waz', 'waz', 1, nil, false, true],
91                  fixed.properties['baz'],
92                  "Array symbol values from DB did not get stringified.")
93     assert_equal true, fixed.save, "Failed to save fixed model back to db."
94   end
95
96   test "No HashWithIndifferentAccess in database" do
97     set_user_from_auth :admin_trustedclient
98     link = Link.create!(link_class: 'test',
99                         properties: {'foo' => 'bar'}.with_indifferent_access)
100     raw = ActiveRecord::Base.connection.
101       select_value("select properties from links where uuid='#{link.uuid}'")
102     assert_equal '{"foo": "bar"}', raw
103   end
104
105   test "store long string" do
106     set_user_from_auth :active
107     longstring = "a"
108     while longstring.length < 2**16
109       longstring = longstring + longstring
110     end
111     g = Group.create! name: 'Has a long description', description: longstring
112     g = Group.find_by_uuid g.uuid
113     assert_equal g.description, longstring
114   end
115
116   [['uuid', {unique: true}],
117    ['owner_uuid', {}]].each do |the_column, requires|
118     test "unique index on all models with #{the_column}" do
119       checked = 0
120       ActiveRecord::Base.connection.tables.each do |table|
121         columns = ActiveRecord::Base.connection.columns(table)
122
123         next unless columns.collect(&:name).include? the_column
124
125         indexes = ActiveRecord::Base.connection.indexes(table).reject do |index|
126           requires.map do |key, val|
127             index.send(key) == val
128           end.include? false
129         end
130         assert_includes indexes.collect(&:columns), [the_column], 'no index'
131         checked += 1
132       end
133       # Sanity check: make sure we didn't just systematically miss everything.
134       assert_operator(10, :<, checked,
135                       "Only #{checked} tables have a #{the_column}?!")
136     end
137   end
138
139   test "search index exists on models that go into projects" do
140     all_tables =  ActiveRecord::Base.connection.tables
141     all_tables.delete 'schema_migrations'
142     all_tables.delete 'permission_refresh_lock'
143
144     all_tables.each do |table|
145       table_class = table.classify.constantize
146       if table_class.respond_to?('searchable_columns')
147         search_index_columns = table_class.searchable_columns('ilike')
148         # Disappointing, but text columns aren't indexed yet.
149         search_index_columns -= table_class.columns.select { |c|
150           c.type == :text or c.name == 'description' or c.name == 'file_names'
151         }.collect(&:name)
152
153         indexes = ActiveRecord::Base.connection.indexes(table)
154         search_index_by_columns = indexes.select do |index|
155           # After rails 5.0 upgrade, AR::Base.connection.indexes() started to include
156           # GIN indexes, with its 'columns' attribute being a String like
157           # 'to_tsvector(...)'
158           index.columns.is_a?(Array) ? index.columns.sort == search_index_columns.sort : false
159         end
160         search_index_by_name = indexes.select do |index|
161           index.name == "#{table}_search_index"
162         end
163         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}"
164       end
165     end
166   end
167
168   test "full text search index exists on models" do
169     indexes = {}
170     conn = ActiveRecord::Base.connection
171     conn.exec_query("SELECT i.relname as indname,
172       i.relowner as indowner,
173       idx.indrelid::regclass::text as table,
174       am.amname as indam,
175       idx.indkey,
176       ARRAY(
177             SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
178                    FROM generate_subscripts(idx.indkey, 1) as k
179                    ORDER BY k
180                    ) as keys,
181       idx.indexprs IS NOT NULL as indexprs,
182       idx.indpred IS NOT NULL as indpred
183       FROM   pg_index as idx
184       JOIN   pg_class as i
185       ON     i.oid = idx.indexrelid
186       JOIN   pg_am as am
187       ON     i.relam = am.oid
188       JOIN   pg_namespace as ns
189       ON     ns.oid = i.relnamespace
190       AND    ns.nspname = ANY(current_schemas(false))").each do |idx|
191       if idx['keys'].match(/to_tsvector/)
192         indexes[idx['table']] ||= []
193         indexes[idx['table']] << idx
194       end
195     end
196     fts_tables =  ["collections", "container_requests", "groups", "jobs",
197                    "pipeline_instances", "pipeline_templates", "workflows"]
198     fts_tables.each do |table|
199       table_class = table.classify.constantize
200       if table_class.respond_to?('full_text_searchable_columns')
201         expect = table_class.full_text_searchable_columns
202         ok = false
203         indexes[table].andand.each do |idx|
204           if expect == idx['keys'].scan(/COALESCE\(([A-Za-z_]+)/).flatten
205             ok = true
206           end
207         end
208         assert ok, "#{table} has no full-text index\nexpect: #{expect.inspect}\nfound: #{indexes[table].inspect}"
209       end
210     end
211   end
212
213   test "selectable_attributes includes database attributes" do
214     assert_includes(Job.selectable_attributes, "success")
215   end
216
217   test "selectable_attributes includes non-database attributes" do
218     assert_includes(Job.selectable_attributes, "node_uuids")
219   end
220
221   test "selectable_attributes includes common attributes in extensions" do
222     assert_includes(Job.selectable_attributes, "uuid")
223   end
224
225   test "selectable_attributes does not include unexposed attributes" do
226     refute_includes(Job.selectable_attributes, "nodes")
227   end
228
229   test "selectable_attributes on a non-default template" do
230     attr_a = Job.selectable_attributes(:common)
231     assert_includes(attr_a, "uuid")
232     refute_includes(attr_a, "success")
233   end
234
235   test 'create and retrieve using created_at time' do
236     set_user_from_auth :active
237     group = Group.create! name: 'test create and retrieve group'
238     assert group.valid?, "group is not valid"
239
240     results = Group.where(created_at: group.created_at)
241     assert_includes results.map(&:uuid), group.uuid,
242       "Expected new group uuid in results when searched with its created_at timestamp"
243   end
244
245   test 'create and update twice and expect different update times' do
246     set_user_from_auth :active
247     group = Group.create! name: 'test create and retrieve group'
248     assert group.valid?, "group is not valid"
249
250     # update 1
251     group.update_attributes!(name: "test create and update name 1")
252     results = Group.where(uuid: group.uuid)
253     assert_equal "test create and update name 1", results.first.name, "Expected name to be updated to 1"
254     updated_at_1 = results.first.updated_at.to_f
255
256     # update 2
257     group.update_attributes!(name: "test create and update name 2")
258     results = Group.where(uuid: group.uuid)
259     assert_equal "test create and update name 2", results.first.name, "Expected name to be updated to 2"
260     updated_at_2 = results.first.updated_at.to_f
261
262     assert_equal true, (updated_at_2 > updated_at_1), "Expected updated time 2 to be newer than 1"
263   end
264
265   test 'jsonb column' do
266     set_user_from_auth :active
267
268     c = Collection.create!(properties: {})
269     assert_equal({}, c.properties)
270
271     c.update_attributes(properties: {'foo' => 'foo'})
272     c.reload
273     assert_equal({'foo' => 'foo'}, c.properties)
274
275     c.update_attributes(properties: nil)
276     c.reload
277     assert_equal({}, c.properties)
278
279     c.update_attributes(properties: {foo: 'bar'})
280     assert_equal({'foo' => 'bar'}, c.properties)
281     c.reload
282     assert_equal({'foo' => 'bar'}, c.properties)
283   end
284 end