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