20259: Add documentation for banner and tooltip features
[arvados.git] / apps / workbench / test / controllers / collections_controller_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 CollectionsControllerTest < ActionController::TestCase
8   # These tests don't do state-changing API calls. Save some time by
9   # skipping the database reset.
10   reset_api_fixtures :after_each_test, false
11   reset_api_fixtures :after_suite, true
12
13   include PipelineInstancesHelper
14
15   NONEXISTENT_COLLECTION = "ffffffffffffffffffffffffffffffff+0"
16
17   def config_anonymous enable
18     Rails.configuration.Users.AnonymousUserToken =
19       if enable
20         api_token('anonymous')
21       else
22         ""
23       end
24   end
25
26   def collection_params(collection_name, file_name=nil)
27     uuid = api_fixture('collections')[collection_name.to_s]['uuid']
28     params = {uuid: uuid, id: uuid}
29     params[:file] = file_name if file_name
30     params
31   end
32
33   def assert_hash_includes(actual_hash, expected_hash, msg=nil)
34     expected_hash.each do |key, value|
35       if value.nil?
36         assert_nil(actual_hash[key], msg)
37       else
38         assert_equal(value, actual_hash[key], msg)
39       end
40     end
41   end
42
43   def assert_no_session
44     assert_hash_includes(session, {arvados_api_token: nil},
45                          "session includes unexpected API token")
46   end
47
48   def assert_session_for_auth(client_auth)
49     api_token =
50       self.api_token(client_auth.to_s)
51     assert_hash_includes(session, {arvados_api_token: api_token},
52                          "session token does not belong to #{client_auth}")
53   end
54
55   def show_collection(params, session={}, response=:success)
56     params = collection_params(params) if not params.is_a? Hash
57     session = session_for(session) if not session.is_a? Hash
58     get(:show, params: params, session: session)
59     assert_response response
60   end
61
62   test "viewing a collection" do
63     show_collection(:foo_file, :active)
64     assert_equal([['.', 'foo', 3]], assigns(:object).files)
65   end
66
67   test "viewing a collection with spaces in filename" do
68     show_collection(:w_a_z_file, :active)
69     assert_equal([['.', 'w a z', 5]], assigns(:object).files)
70   end
71
72   test "download a file with spaces in filename" do
73     setup_for_keep_web
74     collection = api_fixture('collections')['w_a_z_file']
75     get :show_file, params: {
76       uuid: collection['uuid'],
77       file: 'w a z'
78     }, session: session_for(:active)
79     assert_response :redirect
80     assert_match /w%20a%20z/, response.redirect_url
81   end
82
83   test "viewing a collection fetches related projects" do
84     show_collection({id: api_fixture('collections')["foo_file"]['portable_data_hash']}, :active)
85     assert_includes(assigns(:same_pdh).map(&:owner_uuid),
86                     api_fixture('groups')['aproject']['uuid'],
87                     "controller did not find linked project")
88   end
89
90   test "viewing a collection fetches related permissions" do
91     show_collection(:bar_file, :active)
92     assert_includes(assigns(:permissions).map(&:uuid),
93                     api_fixture('links')['bar_file_readable_by_active']['uuid'],
94                     "controller did not find permission link")
95   end
96
97   test "viewing a collection fetches jobs that output it" do
98     show_collection(:bar_file, :active)
99     assert_includes(assigns(:output_of).map(&:uuid),
100                     api_fixture('jobs')['foobar']['uuid'],
101                     "controller did not find output job")
102   end
103
104   test "viewing a collection fetches jobs that logged it" do
105     show_collection(:baz_file, :active)
106     assert_includes(assigns(:log_of).map(&:uuid),
107                     api_fixture('jobs')['foobar']['uuid'],
108                     "controller did not find logger job")
109   end
110
111   test "sharing auths available to admin" do
112     show_collection("collection_owned_by_active", "admin_trustedclient")
113     assert_not_nil assigns(:search_sharing)
114   end
115
116   test "sharing auths available to owner" do
117     show_collection("collection_owned_by_active", "active_trustedclient")
118     assert_not_nil assigns(:search_sharing)
119   end
120
121   test "sharing auths available to reader" do
122     show_collection("foo_collection_in_aproject",
123                     "project_viewer_trustedclient")
124     assert_not_nil assigns(:search_sharing)
125   end
126
127   test "viewing collection files with a reader token" do
128     params = collection_params(:foo_file)
129     params[:reader_token] = api_token("active_all_collections")
130     get(:show_file_links, params: params)
131     assert_response :redirect
132     assert_no_session
133   end
134
135   test "fetching collection file with reader token" do
136     setup_for_keep_web
137     params = collection_params(:foo_file, "foo")
138     params[:reader_token] = api_token("active_all_collections")
139     get(:show_file, params: params)
140     assert_response :redirect
141     assert_match /foo/, response.redirect_url
142     assert_no_session
143   end
144
145   test "reader token Collection links end with trailing slash" do
146     # Testing the fix for #2937.
147     session = session_for(:active_trustedclient)
148     post(:share, params: collection_params(:foo_file), session: session)
149     assert(@controller.download_link.ends_with? '/',
150            "Collection share link does not end with slash for wget")
151   end
152
153   test "getting a file from Keep" do
154     setup_for_keep_web
155     params = collection_params(:foo_file, 'foo')
156     sess = session_for(:active)
157     get(:show_file, params: params, session: sess)
158     assert_response :redirect
159     assert_match /foo/, response.redirect_url
160   end
161
162   test 'anonymous download' do
163     setup_for_keep_web
164     config_anonymous true
165     get :show_file, params: {
166       uuid: api_fixture('collections')['user_agreement_in_anonymously_accessible_project']['uuid'],
167       file: 'GNU_General_Public_License,_version_3.pdf',
168     }
169     assert_response :redirect
170     assert_match /GNU_General_Public_License/, response.redirect_url
171   end
172
173   test "can't get a file from Keep without permission" do
174     params = collection_params(:foo_file, 'foo')
175     sess = session_for(:spectator)
176     get(:show_file, params: params, session: sess)
177     assert_response 404
178   end
179
180   test "getting a file from Keep with a good reader token" do
181     setup_for_keep_web
182     params = collection_params(:foo_file, 'foo')
183     read_token = api_token('active')
184     params[:reader_token] = read_token
185     get(:show_file, params: params)
186     assert_response :redirect
187     assert_match /foo/, response.redirect_url
188     assert_not_equal(read_token, session[:arvados_api_token],
189                      "using a reader token set the session's API token")
190   end
191
192   [false, true].each do |anon|
193     test "download a file using a reader token with insufficient scope, anon #{anon}" do
194       config_anonymous anon
195       params = collection_params(:foo_file, 'foo')
196       params[:reader_token] =
197         api_token('active_noscope')
198       get(:show_file, params: params)
199       if anon
200         # Some files can be shown without a valid token, but not this one.
201         assert_response 404
202       else
203         # No files will ever be shown without a valid token. You
204         # should log in and try again.
205         assert_response :redirect
206       end
207     end
208   end
209
210   test "can get a file with an unpermissioned auth but in-scope reader token" do
211     setup_for_keep_web
212     params = collection_params(:foo_file, 'foo')
213     sess = session_for(:expired)
214     read_token = api_token('active')
215     params[:reader_token] = read_token
216     get(:show_file, params: params, session: sess)
217     assert_response :redirect
218     assert_not_equal(read_token, session[:arvados_api_token],
219                      "using a reader token set the session's API token")
220   end
221
222   test "inactive user can retrieve user agreement" do
223     setup_for_keep_web
224     ua_collection = api_fixture('collections')['user_agreement']
225     # Here we don't test whether the agreement can be retrieved from
226     # Keep. We only test that show_file decides to send file content.
227     get :show_file, params: {
228       uuid: ua_collection['uuid'],
229       file: ua_collection['manifest_text'].match(/ \d+:\d+:(\S+)/)[1]
230     }, session: session_for(:inactive)
231     assert_nil(assigns(:unsigned_user_agreements),
232                "Did not skip check_user_agreements filter " +
233                "when showing the user agreement.")
234     assert_response :redirect
235   end
236
237   test "requesting nonexistent Collection returns 404" do
238     show_collection({uuid: NONEXISTENT_COLLECTION, id: NONEXISTENT_COLLECTION},
239                     :active, 404)
240   end
241
242   test "show file in a subdirectory of a collection" do
243     setup_for_keep_web
244     params = collection_params(:collection_with_files_in_subdir, 'subdir2/subdir3/subdir4/file1_in_subdir4.txt')
245     get(:show_file, params: params, session: session_for(:user1_with_load))
246     assert_response :redirect
247     assert_match /subdir2\/subdir3\/subdir4\/file1_in_subdir4\.txt/, response.redirect_url
248   end
249
250   test 'provenance graph' do
251     use_token 'admin'
252
253     obj = find_fixture Collection, "graph_test_collection3"
254
255     provenance = obj.provenance.stringify_keys
256
257     [obj[:portable_data_hash]].each do |k|
258       assert_not_nil provenance[k], "Expected key #{k} in provenance set"
259     end
260
261     prov_svg = ProvenanceHelper::create_provenance_graph(provenance, "provenance_svg",
262                                                          {:request => RequestDuck,
263                                                            :direction => :bottom_up,
264                                                            :combine_jobs => :script_only})
265
266     stage1 = find_fixture Job, "graph_stage1"
267     stage3 = find_fixture Job, "graph_stage3"
268     previous_job_run = find_fixture Job, "previous_job_run"
269
270     obj_id = obj.portable_data_hash.gsub('+', '\\\+')
271     stage1_out = stage1.output.gsub('+', '\\\+')
272     stage1_id = "#{stage1.script}_#{Digest::MD5.hexdigest(stage1[:script_parameters].to_json)}"
273     stage3_id = "#{stage3.script}_#{Digest::MD5.hexdigest(stage3[:script_parameters].to_json)}"
274
275     assert /#{obj_id}&#45;&gt;#{stage3_id}/.match(prov_svg)
276
277     assert /#{stage3_id}&#45;&gt;#{stage1_out}/.match(prov_svg)
278
279     assert /#{stage1_out}&#45;&gt;#{stage1_id}/.match(prov_svg)
280
281   end
282
283   test 'used_by graph' do
284     use_token 'admin'
285     obj = find_fixture Collection, "graph_test_collection1"
286
287     used_by = obj.used_by.stringify_keys
288
289     used_by_svg = ProvenanceHelper::create_provenance_graph(used_by, "used_by_svg",
290                                                             {:request => RequestDuck,
291                                                               :direction => :top_down,
292                                                               :combine_jobs => :script_only,
293                                                               :pdata_only => true})
294
295     stage2 = find_fixture Job, "graph_stage2"
296     stage3 = find_fixture Job, "graph_stage3"
297
298     stage2_id = "#{stage2.script}_#{Digest::MD5.hexdigest(stage2[:script_parameters].to_json)}"
299     stage3_id = "#{stage3.script}_#{Digest::MD5.hexdigest(stage3[:script_parameters].to_json)}"
300
301     obj_id = obj.portable_data_hash.gsub('+', '\\\+')
302     stage3_out = stage3.output.gsub('+', '\\\+')
303
304     assert /#{obj_id}&#45;&gt;#{stage2_id}/.match(used_by_svg)
305
306     assert /#{obj_id}&#45;&gt;#{stage3_id}/.match(used_by_svg)
307
308     assert /#{stage3_id}&#45;&gt;#{stage3_out}/.match(used_by_svg)
309
310     assert /#{stage3_id}&#45;&gt;#{stage3_out}/.match(used_by_svg)
311
312   end
313
314   test "view collection with empty properties" do
315     fixture_name = :collection_with_empty_properties
316     show_collection(fixture_name, :active)
317     assert_equal(api_fixture('collections')[fixture_name.to_s]['name'], assigns(:object).name)
318     assert_not_nil(assigns(:object).properties)
319     assert_empty(assigns(:object).properties)
320   end
321
322   test "view collection with one property" do
323     fixture_name = :collection_with_one_property
324     show_collection(fixture_name, :active)
325     fixture = api_fixture('collections')[fixture_name.to_s]
326     assert_equal(fixture['name'], assigns(:object).name)
327     assert_equal(fixture['properties'].values[0], assigns(:object).properties.values[0])
328   end
329
330   test "create collection with properties" do
331     post :create, params: {
332       collection: {
333         name: 'collection created with properties',
334         manifest_text: '',
335         properties: {
336           property_1: 'value_1'
337         },
338       },
339       format: :json
340     }, session: session_for(:active)
341     assert_response :success
342     assert_not_nil assigns(:object).uuid
343     assert_equal 'collection created with properties', assigns(:object).name
344     assert_equal 'value_1', assigns(:object).properties[:property_1]
345   end
346
347   test "update description and check manifest_text is not lost" do
348     collection = api_fixture("collections")["multilevel_collection_1"]
349     post :update, params: {
350       id: collection["uuid"],
351       collection: {
352         description: 'test description update'
353       },
354       format: :json
355     }, session: session_for(:active)
356     assert_response :success
357     assert_not_nil assigns(:object)
358     # Ensure the Workbench response still has the original manifest_text
359     assert_equal 'test description update', assigns(:object).description
360     assert_equal true, strip_signatures_and_compare(collection['manifest_text'], assigns(:object).manifest_text)
361     # Ensure the API server still has the original manifest_text after
362     # we called arvados.v1.collections.update
363     use_token :active do
364       assert_equal true, strip_signatures_and_compare(Collection.find(collection['uuid']).manifest_text,
365                                                       collection['manifest_text'])
366     end
367   end
368
369   # Since we got the initial collection from fixture, there are no signatures in manifest_text.
370   # However, after update or find, the collection retrieved will have singed manifest_text.
371   # Hence, let's compare each line after excluding signatures.
372   def strip_signatures_and_compare m1, m2
373     m1_lines = m1.split "\n"
374     m2_lines = m2.split "\n"
375
376     return false if m1_lines.size != m2_lines.size
377
378     m1_lines.each_with_index do |line, i|
379       m1_words = []
380       line.split.each do |word|
381         m1_words << word.split('+A')[0]
382       end
383       m2_words = []
384       m2_lines[i].split.each do |word|
385         m2_words << word.split('+A')[0]
386       end
387       return false if !m1_words.join(' ').eql?(m2_words.join(' '))
388     end
389
390     return true
391   end
392
393   test "view collection and verify none of the file types listed are disabled" do
394     show_collection(:collection_with_several_supported_file_types, :active)
395
396     files = assigns(:object).files
397     assert_equal true, files.length>0, "Expected one or more files in collection"
398
399     disabled = css_select('[disabled="disabled"]').collect do |el|
400       el
401     end
402     assert_equal 0, disabled.length, "Expected no disabled files in collection viewables list"
403   end
404
405   test "view collection and verify file types listed are all disabled" do
406     show_collection(:collection_with_several_unsupported_file_types, :active)
407
408     files = assigns(:object).files.collect do |_, file, _|
409       file
410     end
411     assert_equal true, files.length>0, "Expected one or more files in collection"
412
413     disabled = css_select('[disabled="disabled"]').collect do |el|
414       el.attributes['title'].value.split[-1]
415     end
416
417     assert_equal files.sort, disabled.sort, "Expected to see all collection files in disabled list of files"
418   end
419
420   test "anonymous user accesses collection in shared project" do
421     config_anonymous true
422     collection = api_fixture('collections')['public_text_file']
423     get(:show, params: {id: collection['uuid']})
424
425     response_object = assigns(:object)
426     assert_equal collection['name'], response_object['name']
427     assert_equal collection['uuid'], response_object['uuid']
428     assert_includes @response.body, 'Hello world'
429     assert_includes @response.body, 'Content address'
430     refute_nil css_select('[href="#Advanced"]')
431   end
432
433   test "can view empty collection" do
434     get :show, params: {id: 'd41d8cd98f00b204e9800998ecf8427e+0'}, session: session_for(:active)
435     assert_includes @response.body, 'The following collections have this content'
436   end
437
438   test "collection portable data hash redirect" do
439     di = api_fixture('collections')['docker_image']
440     get :show, params: {id: di['portable_data_hash']}, session: session_for(:active)
441     assert_match /\/collections\/#{di['uuid']}/, @response.redirect_url
442   end
443
444   test "collection portable data hash with multiple matches" do
445     pdh = api_fixture('collections')['foo_file']['portable_data_hash']
446     get :show, params: {id: pdh}, session: session_for(:admin)
447     matches = api_fixture('collections').select {|k,v| v["portable_data_hash"] == pdh}
448     assert matches.size > 1
449
450     matches.each do |k,v|
451       assert_match /href="\/collections\/#{v['uuid']}">.*#{v['name']}<\/a>/, @response.body
452     end
453
454     assert_includes @response.body, 'The following collections have this content:'
455     assert_not_includes @response.body, 'more results are not shown'
456     assert_not_includes @response.body, 'Activity'
457     assert_not_includes @response.body, 'Sharing and permissions'
458   end
459
460   test "collection page renders name" do
461     collection = api_fixture('collections')['foo_file']
462     get :show, params: {id: collection['uuid']}, session: session_for(:active)
463     assert_includes @response.body, collection['name']
464     assert_match /not authorized to manage collection sharing links/, @response.body
465   end
466
467   test "No Upload tab on non-writable collection" do
468     get :show,
469         params: {id: api_fixture('collections')['user_agreement']['uuid']},
470         session: session_for(:active)
471     assert_not_includes @response.body, '<a href="#Upload"'
472   end
473
474   def setup_for_keep_web cfg='https://*.example', dl_cfg=""
475     Rails.configuration.Services.WebDAV.ExternalURL = URI(cfg)
476     Rails.configuration.Services.WebDAVDownload.ExternalURL = URI(dl_cfg)
477   end
478
479   %w(uuid portable_data_hash).each do |id_type|
480     test "Redirect to keep_web_url via #{id_type}" do
481       setup_for_keep_web
482       tok = api_token('active')
483       id = api_fixture('collections')['w_a_z_file'][id_type]
484       get :show_file,
485           params: {uuid: id, file: "w a z"},
486           session: session_for(:active)
487       assert_response :redirect
488       assert_equal "https://#{id.sub '+', '-'}.example/_/w%20a%20z?api_token=#{URI.escape tok, '/'}", @response.redirect_url
489     end
490
491     test "Redirect to keep_web_url via #{id_type} with reader token" do
492       setup_for_keep_web
493       tok = api_token('active')
494       id = api_fixture('collections')['w_a_z_file'][id_type]
495       get :show_file,
496           params: {uuid: id, file: "w a z", reader_token: tok},
497           session: session_for(:expired)
498       assert_response :redirect
499       assert_equal "https://#{id.sub '+', '-'}.example/t=#{URI.escape tok}/_/w%20a%20z", @response.redirect_url
500     end
501
502     test "Redirect to keep_web_url via #{id_type} with no token" do
503       setup_for_keep_web
504       config_anonymous true
505       id = api_fixture('collections')['public_text_file'][id_type]
506       get :show_file, params: {uuid: id, file: "Hello World.txt"}
507       assert_response :redirect
508       assert_equal "https://#{id.sub '+', '-'}.example/_/Hello%20World.txt", @response.redirect_url
509     end
510
511     test "Redirect to keep_web_url via #{id_type} with disposition param" do
512       setup_for_keep_web
513       config_anonymous true
514       id = api_fixture('collections')['public_text_file'][id_type]
515       get :show_file, params: {
516         uuid: id,
517         file: "Hello World.txt",
518         disposition: 'attachment',
519       }
520       assert_response :redirect
521       assert_equal "https://#{id.sub '+', '-'}.example/_/Hello%20World.txt?disposition=attachment", @response.redirect_url
522     end
523
524     test "Redirect to keep_web_download_url via #{id_type}" do
525       setup_for_keep_web('https://collections.example',
526                          'https://download.example')
527       tok = api_token('active')
528       id = api_fixture('collections')['w_a_z_file'][id_type]
529       get :show_file, params: {uuid: id, file: "w a z"}, session: session_for(:active)
530       assert_response :redirect
531       assert_equal "https://download.example/c=#{id.sub '+', '-'}/_/w%20a%20z?api_token=#{URI.escape tok, '/'}", @response.redirect_url
532     end
533
534     test "Redirect to keep_web_url via #{id_type} when trust_all_content enabled" do
535       Rails.configuration.Collections.TrustAllContent = true
536       setup_for_keep_web('https://collections.example',
537                          'https://download.example')
538       tok = api_token('active')
539       id = api_fixture('collections')['w_a_z_file'][id_type]
540       get :show_file, params: {uuid: id, file: "w a z"}, session: session_for(:active)
541       assert_response :redirect
542       assert_equal "https://collections.example/c=#{id.sub '+', '-'}/_/w%20a%20z?api_token=#{URI.escape tok, '/'}", @response.redirect_url
543     end
544   end
545
546   [false, true].each do |anon|
547     test "No redirect to keep_web_url if collection not found, anon #{anon}" do
548       setup_for_keep_web
549       config_anonymous anon
550       id = api_fixture('collections')['w_a_z_file']['uuid']
551       get :show_file, params: {uuid: id, file: "w a z"}, session: session_for(:spectator)
552       assert_response 404
553     end
554
555     test "Redirect download to keep_web_download_url, anon #{anon}" do
556       config_anonymous anon
557       setup_for_keep_web('https://collections.example/',
558                          'https://download.example/')
559       tok = api_token('active')
560       id = api_fixture('collections')['public_text_file']['uuid']
561       get :show_file, params: {
562         uuid: id,
563         file: 'Hello world.txt',
564         disposition: 'attachment',
565       }, session: session_for(:active)
566       assert_response :redirect
567       expect_url = "https://download.example/c=#{id.sub '+', '-'}/_/Hello%20world.txt"
568       if not anon
569         expect_url += "?api_token=#{URI.escape tok, '/'}"
570       end
571       assert_equal expect_url, @response.redirect_url
572     end
573   end
574
575   test "Error if file is impossible to retrieve from keep_web_url" do
576     # Cannot pass a session token using a single-origin keep-web URL,
577     # cannot read this collection without a session token.
578     setup_for_keep_web 'https://collections.example/', ""
579     id = api_fixture('collections')['w_a_z_file']['uuid']
580     get :show_file, params: {uuid: id, file: "w a z"}, session: session_for(:active)
581     assert_response 422
582   end
583
584   [false, true].each do |trust_all_content|
585     test "Redirect preview to keep_web_download_url when preview is disabled and trust_all_content is #{trust_all_content}" do
586       Rails.configuration.Collections.TrustAllContent = trust_all_content
587       setup_for_keep_web "", 'https://download.example/'
588       tok = api_token('active')
589       id = api_fixture('collections')['w_a_z_file']['uuid']
590       get :show_file, params: {uuid: id, file: "w a z"}, session: session_for(:active)
591       assert_response :redirect
592       assert_equal "https://download.example/c=#{id.sub '+', '-'}/_/w%20a%20z?api_token=#{URI.escape tok, '/'}", @response.redirect_url
593     end
594   end
595
596   test "remove selected files from collection" do
597     use_token :active
598
599     # create a new collection to test; using existing collections will cause other tests to fail,
600     # and resetting fixtures after each test makes it take almost 4 times to run this test file.
601     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:file1 0:0:file2\n./dir1 d41d8cd98f00b204e9800998ecf8427e+0 0:0:file1 0:0:file2\n"
602
603     collection = Collection.create(manifest_text: manifest_text)
604     assert_includes(collection['manifest_text'], "0:0:file1")
605
606     # now remove all files named 'file1' from the collection
607     post :remove_selected_files, params: {
608       id: collection['uuid'],
609       selection: ["#{collection['uuid']}/file1",
610                   "#{collection['uuid']}/dir1/file1"],
611       format: :json
612     }, session: session_for(:active)
613     assert_response :success
614
615     use_token :active
616     # verify no 'file1' in the updated collection
617     collection = Collection.select([:uuid, :manifest_text]).where(uuid: collection['uuid']).first
618     assert_not_includes(collection['manifest_text'], "0:0:file1")
619     assert_includes(collection['manifest_text'], "0:0:file2") # but other files still exist
620   end
621
622   test "remove all files from a subdir of a collection" do
623     use_token :active
624
625     # create a new collection to test
626     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:file1 0:0:file2\n./dir1 d41d8cd98f00b204e9800998ecf8427e+0 0:0:file1 0:0:file2\n"
627
628     collection = Collection.create(manifest_text: manifest_text)
629     assert_includes(collection['manifest_text'], "0:0:file1")
630
631     # now remove all files from "dir1" subdir of the collection
632     post :remove_selected_files, params: {
633       id: collection['uuid'],
634       selection: ["#{collection['uuid']}/dir1/file1",
635                   "#{collection['uuid']}/dir1/file2"],
636       format: :json
637     }, session: session_for(:active)
638     assert_response :success
639
640     # verify that "./dir1" no longer exists in this collection's manifest text
641     use_token :active
642     collection = Collection.select([:uuid, :manifest_text]).where(uuid: collection['uuid']).first
643     assert_match /. d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:file1 0:0:file2\n$/, collection['manifest_text']
644     assert_not_includes(collection['manifest_text'], 'dir1')
645   end
646
647   test "rename file in a collection" do
648     use_token :active
649
650     # create a new collection to test
651     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:file1 0:0:file2\n./dir1 d41d8cd98f00b204e9800998ecf8427e+0 0:0:dir1file1 0:0:dir1file2 0:0:dir1imagefile.png\n"
652
653     collection = Collection.create(manifest_text: manifest_text)
654     assert_includes(collection['manifest_text'], "0:0:file1")
655
656     # rename 'file1' as 'file1renamed' and verify
657     post :update, params: {
658       id: collection['uuid'],
659       collection: {
660         'rename-file-path:file1' => 'file1renamed'
661       },
662       format: :json
663     }, session: session_for(:active)
664     assert_response :success
665
666     use_token :active
667     collection = Collection.select([:uuid, :manifest_text]).where(uuid: collection['uuid']).first
668     assert_match /. d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:file1renamed 0:0:file2\n.\/dir1 d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:dir1file1 0:0:dir1file2 0:0:dir1imagefile.png\n$/, collection['manifest_text']
669
670     # now rename 'file2' such that it is moved into 'dir1'
671     @test_counter = 0
672     post :update, params: {
673       id: collection['uuid'],
674       collection: {
675         'rename-file-path:file2' => 'dir1/file2'
676       },
677       format: :json
678     }, session: session_for(:active)
679     assert_response :success
680
681     use_token :active
682     collection = Collection.select([:uuid, :manifest_text]).where(uuid: collection['uuid']).first
683     assert_match /. d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:file1renamed\n.\/dir1 d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:dir1file1 0:0:dir1file2 0:0:dir1imagefile.png 0:0:file2\n$/, collection['manifest_text']
684
685     # now rename 'dir1/dir1file1' such that it is moved into a new subdir
686     @test_counter = 0
687     post :update, params: {
688       id: collection['uuid'],
689       collection: {
690         'rename-file-path:dir1/dir1file1' => 'dir2/dir3/dir1file1moved'
691       },
692       format: :json
693     }, session: session_for(:active)
694     assert_response :success
695
696     use_token :active
697     collection = Collection.select([:uuid, :manifest_text]).where(uuid: collection['uuid']).first
698     assert_match /. d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:file1renamed\n.\/dir1 d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:dir1file2 0:0:dir1imagefile.png 0:0:file2\n.\/dir2\/dir3 d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:dir1file1moved\n$/, collection['manifest_text']
699
700     # now rename the image file 'dir1/dir1imagefile.png'
701     @test_counter = 0
702     post :update, params: {
703       id: collection['uuid'],
704       collection: {
705         'rename-file-path:dir1/dir1imagefile.png' => 'dir1/dir1imagefilerenamed.png'
706       },
707       format: :json
708     }, session: session_for(:active)
709     assert_response :success
710
711     use_token :active
712     collection = Collection.select([:uuid, :manifest_text]).where(uuid: collection['uuid']).first
713     assert_match /. d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:file1renamed\n.\/dir1 d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:dir1file2 0:0:dir1imagefilerenamed.png 0:0:file2\n.\/dir2\/dir3 d41d8cd98f00b204e9800998ecf8427e\+0\+A(.*) 0:0:dir1file1moved\n$/, collection['manifest_text']
714   end
715
716   test "renaming file with a duplicate name in same stream not allowed" do
717     use_token :active
718
719     # rename 'file2' as 'file1' and expect error
720     post :update, params: {
721       id: 'zzzzz-4zz18-pyw8yp9g3pr7irn',
722       collection: {
723         'rename-file-path:file2' => 'file1'
724       },
725       format: :json
726     }, session: session_for(:active)
727     assert_response 422
728     assert_includes json_response['errors'], 'Duplicate file path'
729   end
730
731   test "renaming file with a duplicate name as another stream not allowed" do
732     use_token :active
733
734     # rename 'file1' as 'dir1/file1' and expect error
735     post :update, params: {
736       id: 'zzzzz-4zz18-pyw8yp9g3pr7irn',
737       collection: {
738         'rename-file-path:file1' => 'dir1/file1'
739       },
740       format: :json
741     }, session: session_for(:active)
742     assert_response 422
743     assert_includes json_response['errors'], 'Duplicate file path'
744   end
745 end