##// END OF EJS Templates
API: creating an issue with an invalid project_id should return 422 instead of 403 (#19276)....
Jean-Philippe Lang -
r13759:d5093417971b
parent child
Show More
@@ -1,508 +1,508
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2015 Jean-Philippe Lang
2 # Copyright (C) 2006-2015 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class IssuesController < ApplicationController
18 class IssuesController < ApplicationController
19 menu_item :new_issue, :only => [:new, :create]
19 menu_item :new_issue, :only => [:new, :create]
20 default_search_scope :issues
20 default_search_scope :issues
21
21
22 before_filter :find_issue, :only => [:show, :edit, :update]
22 before_filter :find_issue, :only => [:show, :edit, :update]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
24 before_filter :authorize, :except => [:index, :new, :create]
24 before_filter :authorize, :except => [:index, :new, :create]
25 before_filter :find_optional_project, :only => [:index, :new, :create]
25 before_filter :find_optional_project, :only => [:index, :new, :create]
26 before_filter :build_new_issue_from_params, :only => [:new, :create]
26 before_filter :build_new_issue_from_params, :only => [:new, :create]
27 accept_rss_auth :index, :show
27 accept_rss_auth :index, :show
28 accept_api_auth :index, :show, :create, :update, :destroy
28 accept_api_auth :index, :show, :create, :update, :destroy
29
29
30 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
30 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
31
31
32 helper :journals
32 helper :journals
33 helper :projects
33 helper :projects
34 helper :custom_fields
34 helper :custom_fields
35 helper :issue_relations
35 helper :issue_relations
36 helper :watchers
36 helper :watchers
37 helper :attachments
37 helper :attachments
38 helper :queries
38 helper :queries
39 include QueriesHelper
39 include QueriesHelper
40 helper :repositories
40 helper :repositories
41 helper :sort
41 helper :sort
42 include SortHelper
42 include SortHelper
43 helper :timelog
43 helper :timelog
44
44
45 def index
45 def index
46 retrieve_query
46 retrieve_query
47 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
47 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
48 sort_update(@query.sortable_columns)
48 sort_update(@query.sortable_columns)
49 @query.sort_criteria = sort_criteria.to_a
49 @query.sort_criteria = sort_criteria.to_a
50
50
51 if @query.valid?
51 if @query.valid?
52 case params[:format]
52 case params[:format]
53 when 'csv', 'pdf'
53 when 'csv', 'pdf'
54 @limit = Setting.issues_export_limit.to_i
54 @limit = Setting.issues_export_limit.to_i
55 if params[:columns] == 'all'
55 if params[:columns] == 'all'
56 @query.column_names = @query.available_inline_columns.map(&:name)
56 @query.column_names = @query.available_inline_columns.map(&:name)
57 end
57 end
58 when 'atom'
58 when 'atom'
59 @limit = Setting.feeds_limit.to_i
59 @limit = Setting.feeds_limit.to_i
60 when 'xml', 'json'
60 when 'xml', 'json'
61 @offset, @limit = api_offset_and_limit
61 @offset, @limit = api_offset_and_limit
62 @query.column_names = %w(author)
62 @query.column_names = %w(author)
63 else
63 else
64 @limit = per_page_option
64 @limit = per_page_option
65 end
65 end
66
66
67 @issue_count = @query.issue_count
67 @issue_count = @query.issue_count
68 @issue_pages = Paginator.new @issue_count, @limit, params['page']
68 @issue_pages = Paginator.new @issue_count, @limit, params['page']
69 @offset ||= @issue_pages.offset
69 @offset ||= @issue_pages.offset
70 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
70 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
71 :order => sort_clause,
71 :order => sort_clause,
72 :offset => @offset,
72 :offset => @offset,
73 :limit => @limit)
73 :limit => @limit)
74 @issue_count_by_group = @query.issue_count_by_group
74 @issue_count_by_group = @query.issue_count_by_group
75
75
76 respond_to do |format|
76 respond_to do |format|
77 format.html { render :template => 'issues/index', :layout => !request.xhr? }
77 format.html { render :template => 'issues/index', :layout => !request.xhr? }
78 format.api {
78 format.api {
79 Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
79 Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
80 }
80 }
81 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
81 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
82 format.csv { send_data(query_to_csv(@issues, @query, params), :type => 'text/csv; header=present', :filename => 'issues.csv') }
82 format.csv { send_data(query_to_csv(@issues, @query, params), :type => 'text/csv; header=present', :filename => 'issues.csv') }
83 format.pdf { send_file_headers! :type => 'application/pdf', :filename => 'issues.pdf' }
83 format.pdf { send_file_headers! :type => 'application/pdf', :filename => 'issues.pdf' }
84 end
84 end
85 else
85 else
86 respond_to do |format|
86 respond_to do |format|
87 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
87 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
88 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
88 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
89 format.api { render_validation_errors(@query) }
89 format.api { render_validation_errors(@query) }
90 end
90 end
91 end
91 end
92 rescue ActiveRecord::RecordNotFound
92 rescue ActiveRecord::RecordNotFound
93 render_404
93 render_404
94 end
94 end
95
95
96 def show
96 def show
97 @journals = @issue.journals.includes(:user, :details).
97 @journals = @issue.journals.includes(:user, :details).
98 references(:user, :details).
98 references(:user, :details).
99 reorder("#{Journal.table_name}.id ASC").to_a
99 reorder("#{Journal.table_name}.id ASC").to_a
100 @journals.each_with_index {|j,i| j.indice = i+1}
100 @journals.each_with_index {|j,i| j.indice = i+1}
101 @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
101 @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
102 Journal.preload_journals_details_custom_fields(@journals)
102 Journal.preload_journals_details_custom_fields(@journals)
103 @journals.select! {|journal| journal.notes? || journal.visible_details.any?}
103 @journals.select! {|journal| journal.notes? || journal.visible_details.any?}
104 @journals.reverse! if User.current.wants_comments_in_reverse_order?
104 @journals.reverse! if User.current.wants_comments_in_reverse_order?
105
105
106 @changesets = @issue.changesets.visible.to_a
106 @changesets = @issue.changesets.visible.to_a
107 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
107 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
108
108
109 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
109 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
110 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
110 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
111 @priorities = IssuePriority.active
111 @priorities = IssuePriority.active
112 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
112 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
113 @relation = IssueRelation.new
113 @relation = IssueRelation.new
114
114
115 respond_to do |format|
115 respond_to do |format|
116 format.html {
116 format.html {
117 retrieve_previous_and_next_issue_ids
117 retrieve_previous_and_next_issue_ids
118 render :template => 'issues/show'
118 render :template => 'issues/show'
119 }
119 }
120 format.api
120 format.api
121 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
121 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
122 format.pdf {
122 format.pdf {
123 send_file_headers! :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf"
123 send_file_headers! :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf"
124 }
124 }
125 end
125 end
126 end
126 end
127
127
128 def new
128 def new
129 respond_to do |format|
129 respond_to do |format|
130 format.html { render :action => 'new', :layout => !request.xhr? }
130 format.html { render :action => 'new', :layout => !request.xhr? }
131 format.js
131 format.js
132 end
132 end
133 end
133 end
134
134
135 def create
135 def create
136 unless User.current.allowed_to?(:add_issues, @issue.project)
136 unless User.current.allowed_to?(:add_issues, @issue.project, :global => true)
137 raise ::Unauthorized
137 raise ::Unauthorized
138 end
138 end
139 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
139 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
140 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
140 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
141 if @issue.save
141 if @issue.save
142 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
142 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
143 respond_to do |format|
143 respond_to do |format|
144 format.html {
144 format.html {
145 render_attachment_warning_if_needed(@issue)
145 render_attachment_warning_if_needed(@issue)
146 flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
146 flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
147 redirect_after_create
147 redirect_after_create
148 }
148 }
149 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
149 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
150 end
150 end
151 return
151 return
152 else
152 else
153 respond_to do |format|
153 respond_to do |format|
154 format.html { render :action => 'new' }
154 format.html { render :action => 'new' }
155 format.api { render_validation_errors(@issue) }
155 format.api { render_validation_errors(@issue) }
156 end
156 end
157 end
157 end
158 end
158 end
159
159
160 def edit
160 def edit
161 return unless update_issue_from_params
161 return unless update_issue_from_params
162
162
163 respond_to do |format|
163 respond_to do |format|
164 format.html { }
164 format.html { }
165 format.js
165 format.js
166 end
166 end
167 end
167 end
168
168
169 def update
169 def update
170 return unless update_issue_from_params
170 return unless update_issue_from_params
171 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
171 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
172 saved = false
172 saved = false
173 begin
173 begin
174 saved = save_issue_with_child_records
174 saved = save_issue_with_child_records
175 rescue ActiveRecord::StaleObjectError
175 rescue ActiveRecord::StaleObjectError
176 @conflict = true
176 @conflict = true
177 if params[:last_journal_id]
177 if params[:last_journal_id]
178 @conflict_journals = @issue.journals_after(params[:last_journal_id]).to_a
178 @conflict_journals = @issue.journals_after(params[:last_journal_id]).to_a
179 @conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
179 @conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
180 end
180 end
181 end
181 end
182
182
183 if saved
183 if saved
184 render_attachment_warning_if_needed(@issue)
184 render_attachment_warning_if_needed(@issue)
185 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
185 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
186
186
187 respond_to do |format|
187 respond_to do |format|
188 format.html { redirect_back_or_default issue_path(@issue) }
188 format.html { redirect_back_or_default issue_path(@issue) }
189 format.api { render_api_ok }
189 format.api { render_api_ok }
190 end
190 end
191 else
191 else
192 respond_to do |format|
192 respond_to do |format|
193 format.html { render :action => 'edit' }
193 format.html { render :action => 'edit' }
194 format.api { render_validation_errors(@issue) }
194 format.api { render_validation_errors(@issue) }
195 end
195 end
196 end
196 end
197 end
197 end
198
198
199 # Bulk edit/copy a set of issues
199 # Bulk edit/copy a set of issues
200 def bulk_edit
200 def bulk_edit
201 @issues.sort!
201 @issues.sort!
202 @copy = params[:copy].present?
202 @copy = params[:copy].present?
203 @notes = params[:notes]
203 @notes = params[:notes]
204
204
205 if @copy
205 if @copy
206 unless User.current.allowed_to?(:copy_issues, @projects)
206 unless User.current.allowed_to?(:copy_issues, @projects)
207 raise ::Unauthorized
207 raise ::Unauthorized
208 end
208 end
209 end
209 end
210
210
211 @allowed_projects = Issue.allowed_target_projects
211 @allowed_projects = Issue.allowed_target_projects
212 if params[:issue]
212 if params[:issue]
213 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
213 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
214 if @target_project
214 if @target_project
215 target_projects = [@target_project]
215 target_projects = [@target_project]
216 end
216 end
217 end
217 end
218 target_projects ||= @projects
218 target_projects ||= @projects
219
219
220 if @copy
220 if @copy
221 # Copied issues will get their default statuses
221 # Copied issues will get their default statuses
222 @available_statuses = []
222 @available_statuses = []
223 else
223 else
224 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
224 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
225 end
225 end
226 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields.visible}.reduce(:&)
226 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields.visible}.reduce(:&)
227 @assignables = target_projects.map(&:assignable_users).reduce(:&)
227 @assignables = target_projects.map(&:assignable_users).reduce(:&)
228 @trackers = target_projects.map(&:trackers).reduce(:&)
228 @trackers = target_projects.map(&:trackers).reduce(:&)
229 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
229 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
230 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
230 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
231 if @copy
231 if @copy
232 @attachments_present = @issues.detect {|i| i.attachments.any?}.present?
232 @attachments_present = @issues.detect {|i| i.attachments.any?}.present?
233 @subtasks_present = @issues.detect {|i| !i.leaf?}.present?
233 @subtasks_present = @issues.detect {|i| !i.leaf?}.present?
234 end
234 end
235
235
236 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
236 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
237
237
238 @issue_params = params[:issue] || {}
238 @issue_params = params[:issue] || {}
239 @issue_params[:custom_field_values] ||= {}
239 @issue_params[:custom_field_values] ||= {}
240 end
240 end
241
241
242 def bulk_update
242 def bulk_update
243 @issues.sort!
243 @issues.sort!
244 @copy = params[:copy].present?
244 @copy = params[:copy].present?
245 attributes = parse_params_for_bulk_issue_attributes(params)
245 attributes = parse_params_for_bulk_issue_attributes(params)
246
246
247 if @copy
247 if @copy
248 unless User.current.allowed_to?(:copy_issues, @projects)
248 unless User.current.allowed_to?(:copy_issues, @projects)
249 raise ::Unauthorized
249 raise ::Unauthorized
250 end
250 end
251 target_projects = @projects
251 target_projects = @projects
252 if attributes['project_id'].present?
252 if attributes['project_id'].present?
253 target_projects = Project.where(:id => attributes['project_id']).to_a
253 target_projects = Project.where(:id => attributes['project_id']).to_a
254 end
254 end
255 unless User.current.allowed_to?(:add_issues, target_projects)
255 unless User.current.allowed_to?(:add_issues, target_projects)
256 raise ::Unauthorized
256 raise ::Unauthorized
257 end
257 end
258 end
258 end
259
259
260 unsaved_issues = []
260 unsaved_issues = []
261 saved_issues = []
261 saved_issues = []
262
262
263 if @copy && params[:copy_subtasks].present?
263 if @copy && params[:copy_subtasks].present?
264 # Descendant issues will be copied with the parent task
264 # Descendant issues will be copied with the parent task
265 # Don't copy them twice
265 # Don't copy them twice
266 @issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
266 @issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
267 end
267 end
268
268
269 @issues.each do |orig_issue|
269 @issues.each do |orig_issue|
270 orig_issue.reload
270 orig_issue.reload
271 if @copy
271 if @copy
272 issue = orig_issue.copy({},
272 issue = orig_issue.copy({},
273 :attachments => params[:copy_attachments].present?,
273 :attachments => params[:copy_attachments].present?,
274 :subtasks => params[:copy_subtasks].present?,
274 :subtasks => params[:copy_subtasks].present?,
275 :link => link_copy?(params[:link_copy])
275 :link => link_copy?(params[:link_copy])
276 )
276 )
277 else
277 else
278 issue = orig_issue
278 issue = orig_issue
279 end
279 end
280 journal = issue.init_journal(User.current, params[:notes])
280 journal = issue.init_journal(User.current, params[:notes])
281 issue.safe_attributes = attributes
281 issue.safe_attributes = attributes
282 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
282 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
283 if issue.save
283 if issue.save
284 saved_issues << issue
284 saved_issues << issue
285 else
285 else
286 unsaved_issues << orig_issue
286 unsaved_issues << orig_issue
287 end
287 end
288 end
288 end
289
289
290 if unsaved_issues.empty?
290 if unsaved_issues.empty?
291 flash[:notice] = l(:notice_successful_update) unless saved_issues.empty?
291 flash[:notice] = l(:notice_successful_update) unless saved_issues.empty?
292 if params[:follow]
292 if params[:follow]
293 if @issues.size == 1 && saved_issues.size == 1
293 if @issues.size == 1 && saved_issues.size == 1
294 redirect_to issue_path(saved_issues.first)
294 redirect_to issue_path(saved_issues.first)
295 elsif saved_issues.map(&:project).uniq.size == 1
295 elsif saved_issues.map(&:project).uniq.size == 1
296 redirect_to project_issues_path(saved_issues.map(&:project).first)
296 redirect_to project_issues_path(saved_issues.map(&:project).first)
297 end
297 end
298 else
298 else
299 redirect_back_or_default _project_issues_path(@project)
299 redirect_back_or_default _project_issues_path(@project)
300 end
300 end
301 else
301 else
302 @saved_issues = @issues
302 @saved_issues = @issues
303 @unsaved_issues = unsaved_issues
303 @unsaved_issues = unsaved_issues
304 @issues = Issue.visible.where(:id => @unsaved_issues.map(&:id)).to_a
304 @issues = Issue.visible.where(:id => @unsaved_issues.map(&:id)).to_a
305 bulk_edit
305 bulk_edit
306 render :action => 'bulk_edit'
306 render :action => 'bulk_edit'
307 end
307 end
308 end
308 end
309
309
310 def destroy
310 def destroy
311 @hours = TimeEntry.where(:issue_id => @issues.map(&:id)).sum(:hours).to_f
311 @hours = TimeEntry.where(:issue_id => @issues.map(&:id)).sum(:hours).to_f
312 if @hours > 0
312 if @hours > 0
313 case params[:todo]
313 case params[:todo]
314 when 'destroy'
314 when 'destroy'
315 # nothing to do
315 # nothing to do
316 when 'nullify'
316 when 'nullify'
317 TimeEntry.where(['issue_id IN (?)', @issues]).update_all('issue_id = NULL')
317 TimeEntry.where(['issue_id IN (?)', @issues]).update_all('issue_id = NULL')
318 when 'reassign'
318 when 'reassign'
319 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
319 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
320 if reassign_to.nil?
320 if reassign_to.nil?
321 flash.now[:error] = l(:error_issue_not_found_in_project)
321 flash.now[:error] = l(:error_issue_not_found_in_project)
322 return
322 return
323 else
323 else
324 TimeEntry.where(['issue_id IN (?)', @issues]).
324 TimeEntry.where(['issue_id IN (?)', @issues]).
325 update_all("issue_id = #{reassign_to.id}")
325 update_all("issue_id = #{reassign_to.id}")
326 end
326 end
327 else
327 else
328 # display the destroy form if it's a user request
328 # display the destroy form if it's a user request
329 return unless api_request?
329 return unless api_request?
330 end
330 end
331 end
331 end
332 @issues.each do |issue|
332 @issues.each do |issue|
333 begin
333 begin
334 issue.reload.destroy
334 issue.reload.destroy
335 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
335 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
336 # nothing to do, issue was already deleted (eg. by a parent)
336 # nothing to do, issue was already deleted (eg. by a parent)
337 end
337 end
338 end
338 end
339 respond_to do |format|
339 respond_to do |format|
340 format.html { redirect_back_or_default _project_issues_path(@project) }
340 format.html { redirect_back_or_default _project_issues_path(@project) }
341 format.api { render_api_ok }
341 format.api { render_api_ok }
342 end
342 end
343 end
343 end
344
344
345 private
345 private
346
346
347 def retrieve_previous_and_next_issue_ids
347 def retrieve_previous_and_next_issue_ids
348 retrieve_query_from_session
348 retrieve_query_from_session
349 if @query
349 if @query
350 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
350 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
351 sort_update(@query.sortable_columns, 'issues_index_sort')
351 sort_update(@query.sortable_columns, 'issues_index_sort')
352 limit = 500
352 limit = 500
353 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
353 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
354 if (idx = issue_ids.index(@issue.id)) && idx < limit
354 if (idx = issue_ids.index(@issue.id)) && idx < limit
355 if issue_ids.size < 500
355 if issue_ids.size < 500
356 @issue_position = idx + 1
356 @issue_position = idx + 1
357 @issue_count = issue_ids.size
357 @issue_count = issue_ids.size
358 end
358 end
359 @prev_issue_id = issue_ids[idx - 1] if idx > 0
359 @prev_issue_id = issue_ids[idx - 1] if idx > 0
360 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
360 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
361 end
361 end
362 end
362 end
363 end
363 end
364
364
365 # Used by #edit and #update to set some common instance variables
365 # Used by #edit and #update to set some common instance variables
366 # from the params
366 # from the params
367 def update_issue_from_params
367 def update_issue_from_params
368 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
368 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
369 if params[:time_entry]
369 if params[:time_entry]
370 @time_entry.attributes = params[:time_entry]
370 @time_entry.attributes = params[:time_entry]
371 end
371 end
372
372
373 @issue.init_journal(User.current)
373 @issue.init_journal(User.current)
374
374
375 issue_attributes = params[:issue]
375 issue_attributes = params[:issue]
376 if issue_attributes && params[:conflict_resolution]
376 if issue_attributes && params[:conflict_resolution]
377 case params[:conflict_resolution]
377 case params[:conflict_resolution]
378 when 'overwrite'
378 when 'overwrite'
379 issue_attributes = issue_attributes.dup
379 issue_attributes = issue_attributes.dup
380 issue_attributes.delete(:lock_version)
380 issue_attributes.delete(:lock_version)
381 when 'add_notes'
381 when 'add_notes'
382 issue_attributes = issue_attributes.slice(:notes)
382 issue_attributes = issue_attributes.slice(:notes)
383 when 'cancel'
383 when 'cancel'
384 redirect_to issue_path(@issue)
384 redirect_to issue_path(@issue)
385 return false
385 return false
386 end
386 end
387 end
387 end
388 @issue.safe_attributes = issue_attributes
388 @issue.safe_attributes = issue_attributes
389 @priorities = IssuePriority.active
389 @priorities = IssuePriority.active
390 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
390 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
391 true
391 true
392 end
392 end
393
393
394 # Used by #new and #create to build a new issue from the params
394 # Used by #new and #create to build a new issue from the params
395 # The new issue will be copied from an existing one if copy_from parameter is given
395 # The new issue will be copied from an existing one if copy_from parameter is given
396 def build_new_issue_from_params
396 def build_new_issue_from_params
397 @issue = Issue.new
397 @issue = Issue.new
398 if params[:copy_from]
398 if params[:copy_from]
399 begin
399 begin
400 @issue.init_journal(User.current)
400 @issue.init_journal(User.current)
401 @copy_from = Issue.visible.find(params[:copy_from])
401 @copy_from = Issue.visible.find(params[:copy_from])
402 unless User.current.allowed_to?(:copy_issues, @copy_from.project)
402 unless User.current.allowed_to?(:copy_issues, @copy_from.project)
403 raise ::Unauthorized
403 raise ::Unauthorized
404 end
404 end
405 @link_copy = link_copy?(params[:link_copy]) || request.get?
405 @link_copy = link_copy?(params[:link_copy]) || request.get?
406 @copy_attachments = params[:copy_attachments].present? || request.get?
406 @copy_attachments = params[:copy_attachments].present? || request.get?
407 @copy_subtasks = params[:copy_subtasks].present? || request.get?
407 @copy_subtasks = params[:copy_subtasks].present? || request.get?
408 @issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks, :link => @link_copy)
408 @issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks, :link => @link_copy)
409 rescue ActiveRecord::RecordNotFound
409 rescue ActiveRecord::RecordNotFound
410 render_404
410 render_404
411 return
411 return
412 end
412 end
413 end
413 end
414 @issue.project = @project
414 @issue.project = @project
415 if request.get?
415 if request.get?
416 @issue.project ||= @issue.allowed_target_projects.first
416 @issue.project ||= @issue.allowed_target_projects.first
417 end
417 end
418 @issue.author ||= User.current
418 @issue.author ||= User.current
419 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
419 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
420
420
421 if attrs = params[:issue].deep_dup
421 if attrs = params[:issue].deep_dup
422 if params[:was_default_status] == attrs[:status_id]
422 if params[:was_default_status] == attrs[:status_id]
423 attrs.delete(:status_id)
423 attrs.delete(:status_id)
424 end
424 end
425 @issue.safe_attributes = attrs
425 @issue.safe_attributes = attrs
426 end
426 end
427 if @issue.project
427 if @issue.project
428 @issue.tracker ||= @issue.project.trackers.first
428 @issue.tracker ||= @issue.project.trackers.first
429 if @issue.tracker.nil?
429 if @issue.tracker.nil?
430 render_error l(:error_no_tracker_in_project)
430 render_error l(:error_no_tracker_in_project)
431 return false
431 return false
432 end
432 end
433 if @issue.status.nil?
433 if @issue.status.nil?
434 render_error l(:error_no_default_issue_status)
434 render_error l(:error_no_default_issue_status)
435 return false
435 return false
436 end
436 end
437 end
437 end
438
438
439 @priorities = IssuePriority.active
439 @priorities = IssuePriority.active
440 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, @issue.new_record?)
440 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, @issue.new_record?)
441 end
441 end
442
442
443 def parse_params_for_bulk_issue_attributes(params)
443 def parse_params_for_bulk_issue_attributes(params)
444 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
444 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
445 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
445 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
446 if custom = attributes[:custom_field_values]
446 if custom = attributes[:custom_field_values]
447 custom.reject! {|k,v| v.blank?}
447 custom.reject! {|k,v| v.blank?}
448 custom.keys.each do |k|
448 custom.keys.each do |k|
449 if custom[k].is_a?(Array)
449 if custom[k].is_a?(Array)
450 custom[k] << '' if custom[k].delete('__none__')
450 custom[k] << '' if custom[k].delete('__none__')
451 else
451 else
452 custom[k] = '' if custom[k] == '__none__'
452 custom[k] = '' if custom[k] == '__none__'
453 end
453 end
454 end
454 end
455 end
455 end
456 attributes
456 attributes
457 end
457 end
458
458
459 # Saves @issue and a time_entry from the parameters
459 # Saves @issue and a time_entry from the parameters
460 def save_issue_with_child_records
460 def save_issue_with_child_records
461 Issue.transaction do
461 Issue.transaction do
462 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, @issue.project)
462 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, @issue.project)
463 time_entry = @time_entry || TimeEntry.new
463 time_entry = @time_entry || TimeEntry.new
464 time_entry.project = @issue.project
464 time_entry.project = @issue.project
465 time_entry.issue = @issue
465 time_entry.issue = @issue
466 time_entry.user = User.current
466 time_entry.user = User.current
467 time_entry.spent_on = User.current.today
467 time_entry.spent_on = User.current.today
468 time_entry.attributes = params[:time_entry]
468 time_entry.attributes = params[:time_entry]
469 @issue.time_entries << time_entry
469 @issue.time_entries << time_entry
470 end
470 end
471
471
472 call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
472 call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
473 if @issue.save
473 if @issue.save
474 call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
474 call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
475 else
475 else
476 raise ActiveRecord::Rollback
476 raise ActiveRecord::Rollback
477 end
477 end
478 end
478 end
479 end
479 end
480
480
481 # Returns true if the issue copy should be linked
481 # Returns true if the issue copy should be linked
482 # to the original issue
482 # to the original issue
483 def link_copy?(param)
483 def link_copy?(param)
484 case Setting.link_copied_issue
484 case Setting.link_copied_issue
485 when 'yes'
485 when 'yes'
486 true
486 true
487 when 'no'
487 when 'no'
488 false
488 false
489 when 'ask'
489 when 'ask'
490 param == '1'
490 param == '1'
491 end
491 end
492 end
492 end
493
493
494 # Redirects user after a successful issue creation
494 # Redirects user after a successful issue creation
495 def redirect_after_create
495 def redirect_after_create
496 if params[:continue]
496 if params[:continue]
497 attrs = {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?}
497 attrs = {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?}
498 if params[:project_id]
498 if params[:project_id]
499 redirect_to new_project_issue_path(@issue.project, :issue => attrs)
499 redirect_to new_project_issue_path(@issue.project, :issue => attrs)
500 else
500 else
501 attrs.merge! :project_id => @issue.project_id
501 attrs.merge! :project_id => @issue.project_id
502 redirect_to new_issue_path(:issue => attrs)
502 redirect_to new_issue_path(:issue => attrs)
503 end
503 end
504 else
504 else
505 redirect_to issue_path(@issue)
505 redirect_to issue_path(@issue)
506 end
506 end
507 end
507 end
508 end
508 end
@@ -1,699 +1,704
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2015 Jean-Philippe Lang
2 # Copyright (C) 2006-2015 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require File.expand_path('../../../test_helper', __FILE__)
18 require File.expand_path('../../../test_helper', __FILE__)
19
19
20 class Redmine::ApiTest::IssuesTest < Redmine::ApiTest::Base
20 class Redmine::ApiTest::IssuesTest < Redmine::ApiTest::Base
21 fixtures :projects,
21 fixtures :projects,
22 :users,
22 :users,
23 :roles,
23 :roles,
24 :members,
24 :members,
25 :member_roles,
25 :member_roles,
26 :issues,
26 :issues,
27 :issue_statuses,
27 :issue_statuses,
28 :issue_relations,
28 :issue_relations,
29 :versions,
29 :versions,
30 :trackers,
30 :trackers,
31 :projects_trackers,
31 :projects_trackers,
32 :issue_categories,
32 :issue_categories,
33 :enabled_modules,
33 :enabled_modules,
34 :enumerations,
34 :enumerations,
35 :attachments,
35 :attachments,
36 :workflows,
36 :workflows,
37 :custom_fields,
37 :custom_fields,
38 :custom_values,
38 :custom_values,
39 :custom_fields_projects,
39 :custom_fields_projects,
40 :custom_fields_trackers,
40 :custom_fields_trackers,
41 :time_entries,
41 :time_entries,
42 :journals,
42 :journals,
43 :journal_details,
43 :journal_details,
44 :queries,
44 :queries,
45 :attachments
45 :attachments
46
46
47 test "GET /issues.xml should contain metadata" do
47 test "GET /issues.xml should contain metadata" do
48 get '/issues.xml'
48 get '/issues.xml'
49 assert_select 'issues[type=array][total_count=?][limit="25"][offset="0"]',
49 assert_select 'issues[type=array][total_count=?][limit="25"][offset="0"]',
50 assigns(:issue_count).to_s
50 assigns(:issue_count).to_s
51 end
51 end
52
52
53 test "GET /issues.xml with nometa param should not contain metadata" do
53 test "GET /issues.xml with nometa param should not contain metadata" do
54 get '/issues.xml?nometa=1'
54 get '/issues.xml?nometa=1'
55 assert_select 'issues[type=array]:not([total_count]):not([limit]):not([offset])'
55 assert_select 'issues[type=array]:not([total_count]):not([limit]):not([offset])'
56 end
56 end
57
57
58 test "GET /issues.xml with nometa header should not contain metadata" do
58 test "GET /issues.xml with nometa header should not contain metadata" do
59 get '/issues.xml', {}, {'X-Redmine-Nometa' => '1'}
59 get '/issues.xml', {}, {'X-Redmine-Nometa' => '1'}
60 assert_select 'issues[type=array]:not([total_count]):not([limit]):not([offset])'
60 assert_select 'issues[type=array]:not([total_count]):not([limit]):not([offset])'
61 end
61 end
62
62
63 test "GET /issues.xml with offset and limit" do
63 test "GET /issues.xml with offset and limit" do
64 get '/issues.xml?offset=2&limit=3'
64 get '/issues.xml?offset=2&limit=3'
65
65
66 assert_equal 3, assigns(:limit)
66 assert_equal 3, assigns(:limit)
67 assert_equal 2, assigns(:offset)
67 assert_equal 2, assigns(:offset)
68 assert_select 'issues issue', 3
68 assert_select 'issues issue', 3
69 end
69 end
70
70
71 test "GET /issues.xml with relations" do
71 test "GET /issues.xml with relations" do
72 get '/issues.xml?include=relations'
72 get '/issues.xml?include=relations'
73
73
74 assert_response :success
74 assert_response :success
75 assert_equal 'application/xml', @response.content_type
75 assert_equal 'application/xml', @response.content_type
76
76
77 assert_select 'issue id', :text => '3' do
77 assert_select 'issue id', :text => '3' do
78 assert_select '~ relations relation', 1
78 assert_select '~ relations relation', 1
79 assert_select '~ relations relation[id="2"][issue_id="2"][issue_to_id="3"][relation_type=relates]'
79 assert_select '~ relations relation[id="2"][issue_id="2"][issue_to_id="3"][relation_type=relates]'
80 end
80 end
81
81
82 assert_select 'issue id', :text => '1' do
82 assert_select 'issue id', :text => '1' do
83 assert_select '~ relations'
83 assert_select '~ relations'
84 assert_select '~ relations relation', 0
84 assert_select '~ relations relation', 0
85 end
85 end
86 end
86 end
87
87
88 test "GET /issues.xml with invalid query params" do
88 test "GET /issues.xml with invalid query params" do
89 get '/issues.xml', {:f => ['start_date'], :op => {:start_date => '='}}
89 get '/issues.xml', {:f => ['start_date'], :op => {:start_date => '='}}
90
90
91 assert_response :unprocessable_entity
91 assert_response :unprocessable_entity
92 assert_equal 'application/xml', @response.content_type
92 assert_equal 'application/xml', @response.content_type
93 assert_select 'errors error', :text => "Start date cannot be blank"
93 assert_select 'errors error', :text => "Start date cannot be blank"
94 end
94 end
95
95
96 test "GET /issues.xml with custom field filter" do
96 test "GET /issues.xml with custom field filter" do
97 get '/issues.xml',
97 get '/issues.xml',
98 {:set_filter => 1, :f => ['cf_1'], :op => {:cf_1 => '='}, :v => {:cf_1 => ['MySQL']}}
98 {:set_filter => 1, :f => ['cf_1'], :op => {:cf_1 => '='}, :v => {:cf_1 => ['MySQL']}}
99
99
100 expected_ids = Issue.visible.
100 expected_ids = Issue.visible.
101 joins(:custom_values).
101 joins(:custom_values).
102 where(:custom_values => {:custom_field_id => 1, :value => 'MySQL'}).map(&:id)
102 where(:custom_values => {:custom_field_id => 1, :value => 'MySQL'}).map(&:id)
103 assert expected_ids.any?
103 assert expected_ids.any?
104
104
105 assert_select 'issues > issue > id', :count => expected_ids.count do |ids|
105 assert_select 'issues > issue > id', :count => expected_ids.count do |ids|
106 ids.each { |id| assert expected_ids.delete(id.children.first.content.to_i) }
106 ids.each { |id| assert expected_ids.delete(id.children.first.content.to_i) }
107 end
107 end
108 end
108 end
109
109
110 test "GET /issues.xml with custom field filter (shorthand method)" do
110 test "GET /issues.xml with custom field filter (shorthand method)" do
111 get '/issues.xml', {:cf_1 => 'MySQL'}
111 get '/issues.xml', {:cf_1 => 'MySQL'}
112
112
113 expected_ids = Issue.visible.
113 expected_ids = Issue.visible.
114 joins(:custom_values).
114 joins(:custom_values).
115 where(:custom_values => {:custom_field_id => 1, :value => 'MySQL'}).map(&:id)
115 where(:custom_values => {:custom_field_id => 1, :value => 'MySQL'}).map(&:id)
116 assert expected_ids.any?
116 assert expected_ids.any?
117
117
118 assert_select 'issues > issue > id', :count => expected_ids.count do |ids|
118 assert_select 'issues > issue > id', :count => expected_ids.count do |ids|
119 ids.each { |id| assert expected_ids.delete(id.children.first.content.to_i) }
119 ids.each { |id| assert expected_ids.delete(id.children.first.content.to_i) }
120 end
120 end
121 end
121 end
122
122
123 def test_index_should_include_issue_attributes
123 def test_index_should_include_issue_attributes
124 get '/issues.xml'
124 get '/issues.xml'
125 assert_select 'issues>issue>is_private', :text => 'false'
125 assert_select 'issues>issue>is_private', :text => 'false'
126 end
126 end
127
127
128 def test_index_should_allow_timestamp_filtering
128 def test_index_should_allow_timestamp_filtering
129 Issue.delete_all
129 Issue.delete_all
130 Issue.generate!(:subject => '1').update_column(:updated_on, Time.parse("2014-01-02T10:25:00Z"))
130 Issue.generate!(:subject => '1').update_column(:updated_on, Time.parse("2014-01-02T10:25:00Z"))
131 Issue.generate!(:subject => '2').update_column(:updated_on, Time.parse("2014-01-02T12:13:00Z"))
131 Issue.generate!(:subject => '2').update_column(:updated_on, Time.parse("2014-01-02T12:13:00Z"))
132
132
133 get '/issues.xml',
133 get '/issues.xml',
134 {:set_filter => 1, :f => ['updated_on'], :op => {:updated_on => '<='},
134 {:set_filter => 1, :f => ['updated_on'], :op => {:updated_on => '<='},
135 :v => {:updated_on => ['2014-01-02T12:00:00Z']}}
135 :v => {:updated_on => ['2014-01-02T12:00:00Z']}}
136 assert_select 'issues>issue', :count => 1
136 assert_select 'issues>issue', :count => 1
137 assert_select 'issues>issue>subject', :text => '1'
137 assert_select 'issues>issue>subject', :text => '1'
138
138
139 get '/issues.xml',
139 get '/issues.xml',
140 {:set_filter => 1, :f => ['updated_on'], :op => {:updated_on => '>='},
140 {:set_filter => 1, :f => ['updated_on'], :op => {:updated_on => '>='},
141 :v => {:updated_on => ['2014-01-02T12:00:00Z']}}
141 :v => {:updated_on => ['2014-01-02T12:00:00Z']}}
142 assert_select 'issues>issue', :count => 1
142 assert_select 'issues>issue', :count => 1
143 assert_select 'issues>issue>subject', :text => '2'
143 assert_select 'issues>issue>subject', :text => '2'
144
144
145 get '/issues.xml',
145 get '/issues.xml',
146 {:set_filter => 1, :f => ['updated_on'], :op => {:updated_on => '>='},
146 {:set_filter => 1, :f => ['updated_on'], :op => {:updated_on => '>='},
147 :v => {:updated_on => ['2014-01-02T08:00:00Z']}}
147 :v => {:updated_on => ['2014-01-02T08:00:00Z']}}
148 assert_select 'issues>issue', :count => 2
148 assert_select 'issues>issue', :count => 2
149 end
149 end
150
150
151 test "GET /issues.xml with filter" do
151 test "GET /issues.xml with filter" do
152 get '/issues.xml?status_id=5'
152 get '/issues.xml?status_id=5'
153
153
154 expected_ids = Issue.visible.where(:status_id => 5).map(&:id)
154 expected_ids = Issue.visible.where(:status_id => 5).map(&:id)
155 assert expected_ids.any?
155 assert expected_ids.any?
156
156
157 assert_select 'issues > issue > id', :count => expected_ids.count do |ids|
157 assert_select 'issues > issue > id', :count => expected_ids.count do |ids|
158 ids.each { |id| assert expected_ids.delete(id.children.first.content.to_i) }
158 ids.each { |id| assert expected_ids.delete(id.children.first.content.to_i) }
159 end
159 end
160 end
160 end
161
161
162 test "GET /issues.json with filter" do
162 test "GET /issues.json with filter" do
163 get '/issues.json?status_id=5'
163 get '/issues.json?status_id=5'
164
164
165 json = ActiveSupport::JSON.decode(response.body)
165 json = ActiveSupport::JSON.decode(response.body)
166 status_ids_used = json['issues'].collect {|j| j['status']['id'] }
166 status_ids_used = json['issues'].collect {|j| j['status']['id'] }
167 assert_equal 3, status_ids_used.length
167 assert_equal 3, status_ids_used.length
168 assert status_ids_used.all? {|id| id == 5 }
168 assert status_ids_used.all? {|id| id == 5 }
169 end
169 end
170
170
171 test "GET /issues/:id.xml with journals" do
171 test "GET /issues/:id.xml with journals" do
172 get '/issues/1.xml?include=journals'
172 get '/issues/1.xml?include=journals'
173
173
174 assert_select 'issue journals[type=array]' do
174 assert_select 'issue journals[type=array]' do
175 assert_select 'journal[id="1"]' do
175 assert_select 'journal[id="1"]' do
176 assert_select 'details[type=array]' do
176 assert_select 'details[type=array]' do
177 assert_select 'detail[name=status_id]' do
177 assert_select 'detail[name=status_id]' do
178 assert_select 'old_value', :text => '1'
178 assert_select 'old_value', :text => '1'
179 assert_select 'new_value', :text => '2'
179 assert_select 'new_value', :text => '2'
180 end
180 end
181 end
181 end
182 end
182 end
183 end
183 end
184 end
184 end
185
185
186 test "GET /issues/:id.xml with journals should format timestamps in ISO 8601" do
186 test "GET /issues/:id.xml with journals should format timestamps in ISO 8601" do
187 get '/issues/1.xml?include=journals'
187 get '/issues/1.xml?include=journals'
188
188
189 iso_date = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/
189 iso_date = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/
190 assert_select 'issue>created_on', :text => iso_date
190 assert_select 'issue>created_on', :text => iso_date
191 assert_select 'issue>updated_on', :text => iso_date
191 assert_select 'issue>updated_on', :text => iso_date
192 assert_select 'issue journal>created_on', :text => iso_date
192 assert_select 'issue journal>created_on', :text => iso_date
193 end
193 end
194
194
195 test "GET /issues/:id.xml with custom fields" do
195 test "GET /issues/:id.xml with custom fields" do
196 get '/issues/3.xml'
196 get '/issues/3.xml'
197
197
198 assert_select 'issue custom_fields[type=array]' do
198 assert_select 'issue custom_fields[type=array]' do
199 assert_select 'custom_field[id="1"]' do
199 assert_select 'custom_field[id="1"]' do
200 assert_select 'value', :text => 'MySQL'
200 assert_select 'value', :text => 'MySQL'
201 end
201 end
202 end
202 end
203 assert_nothing_raised do
203 assert_nothing_raised do
204 Hash.from_xml(response.body).to_xml
204 Hash.from_xml(response.body).to_xml
205 end
205 end
206 end
206 end
207
207
208 test "GET /issues/:id.xml with multi custom fields" do
208 test "GET /issues/:id.xml with multi custom fields" do
209 field = CustomField.find(1)
209 field = CustomField.find(1)
210 field.update_attribute :multiple, true
210 field.update_attribute :multiple, true
211 issue = Issue.find(3)
211 issue = Issue.find(3)
212 issue.custom_field_values = {1 => ['MySQL', 'Oracle']}
212 issue.custom_field_values = {1 => ['MySQL', 'Oracle']}
213 issue.save!
213 issue.save!
214
214
215 get '/issues/3.xml'
215 get '/issues/3.xml'
216 assert_response :success
216 assert_response :success
217
217
218 assert_select 'issue custom_fields[type=array]' do
218 assert_select 'issue custom_fields[type=array]' do
219 assert_select 'custom_field[id="1"]' do
219 assert_select 'custom_field[id="1"]' do
220 assert_select 'value[type=array] value', 2
220 assert_select 'value[type=array] value', 2
221 end
221 end
222 end
222 end
223 xml = Hash.from_xml(response.body)
223 xml = Hash.from_xml(response.body)
224 custom_fields = xml['issue']['custom_fields']
224 custom_fields = xml['issue']['custom_fields']
225 assert_kind_of Array, custom_fields
225 assert_kind_of Array, custom_fields
226 field = custom_fields.detect {|f| f['id'] == '1'}
226 field = custom_fields.detect {|f| f['id'] == '1'}
227 assert_kind_of Hash, field
227 assert_kind_of Hash, field
228 assert_equal ['MySQL', 'Oracle'], field['value'].sort
228 assert_equal ['MySQL', 'Oracle'], field['value'].sort
229 end
229 end
230
230
231 test "GET /issues/:id.json with multi custom fields" do
231 test "GET /issues/:id.json with multi custom fields" do
232 field = CustomField.find(1)
232 field = CustomField.find(1)
233 field.update_attribute :multiple, true
233 field.update_attribute :multiple, true
234 issue = Issue.find(3)
234 issue = Issue.find(3)
235 issue.custom_field_values = {1 => ['MySQL', 'Oracle']}
235 issue.custom_field_values = {1 => ['MySQL', 'Oracle']}
236 issue.save!
236 issue.save!
237
237
238 get '/issues/3.json'
238 get '/issues/3.json'
239 assert_response :success
239 assert_response :success
240
240
241 json = ActiveSupport::JSON.decode(response.body)
241 json = ActiveSupport::JSON.decode(response.body)
242 custom_fields = json['issue']['custom_fields']
242 custom_fields = json['issue']['custom_fields']
243 assert_kind_of Array, custom_fields
243 assert_kind_of Array, custom_fields
244 field = custom_fields.detect {|f| f['id'] == 1}
244 field = custom_fields.detect {|f| f['id'] == 1}
245 assert_kind_of Hash, field
245 assert_kind_of Hash, field
246 assert_equal ['MySQL', 'Oracle'], field['value'].sort
246 assert_equal ['MySQL', 'Oracle'], field['value'].sort
247 end
247 end
248
248
249 test "GET /issues/:id.xml with empty value for multi custom field" do
249 test "GET /issues/:id.xml with empty value for multi custom field" do
250 field = CustomField.find(1)
250 field = CustomField.find(1)
251 field.update_attribute :multiple, true
251 field.update_attribute :multiple, true
252 issue = Issue.find(3)
252 issue = Issue.find(3)
253 issue.custom_field_values = {1 => ['']}
253 issue.custom_field_values = {1 => ['']}
254 issue.save!
254 issue.save!
255
255
256 get '/issues/3.xml'
256 get '/issues/3.xml'
257
257
258 assert_select 'issue custom_fields[type=array]' do
258 assert_select 'issue custom_fields[type=array]' do
259 assert_select 'custom_field[id="1"]' do
259 assert_select 'custom_field[id="1"]' do
260 assert_select 'value[type=array]:empty'
260 assert_select 'value[type=array]:empty'
261 end
261 end
262 end
262 end
263 xml = Hash.from_xml(response.body)
263 xml = Hash.from_xml(response.body)
264 custom_fields = xml['issue']['custom_fields']
264 custom_fields = xml['issue']['custom_fields']
265 assert_kind_of Array, custom_fields
265 assert_kind_of Array, custom_fields
266 field = custom_fields.detect {|f| f['id'] == '1'}
266 field = custom_fields.detect {|f| f['id'] == '1'}
267 assert_kind_of Hash, field
267 assert_kind_of Hash, field
268 assert_equal [], field['value']
268 assert_equal [], field['value']
269 end
269 end
270
270
271 test "GET /issues/:id.json with empty value for multi custom field" do
271 test "GET /issues/:id.json with empty value for multi custom field" do
272 field = CustomField.find(1)
272 field = CustomField.find(1)
273 field.update_attribute :multiple, true
273 field.update_attribute :multiple, true
274 issue = Issue.find(3)
274 issue = Issue.find(3)
275 issue.custom_field_values = {1 => ['']}
275 issue.custom_field_values = {1 => ['']}
276 issue.save!
276 issue.save!
277
277
278 get '/issues/3.json'
278 get '/issues/3.json'
279 assert_response :success
279 assert_response :success
280 json = ActiveSupport::JSON.decode(response.body)
280 json = ActiveSupport::JSON.decode(response.body)
281 custom_fields = json['issue']['custom_fields']
281 custom_fields = json['issue']['custom_fields']
282 assert_kind_of Array, custom_fields
282 assert_kind_of Array, custom_fields
283 field = custom_fields.detect {|f| f['id'] == 1}
283 field = custom_fields.detect {|f| f['id'] == 1}
284 assert_kind_of Hash, field
284 assert_kind_of Hash, field
285 assert_equal [], field['value'].sort
285 assert_equal [], field['value'].sort
286 end
286 end
287
287
288 test "GET /issues/:id.xml with attachments" do
288 test "GET /issues/:id.xml with attachments" do
289 get '/issues/3.xml?include=attachments'
289 get '/issues/3.xml?include=attachments'
290
290
291 assert_select 'issue attachments[type=array]' do
291 assert_select 'issue attachments[type=array]' do
292 assert_select 'attachment', 4
292 assert_select 'attachment', 4
293 assert_select 'attachment id', :text => '1' do
293 assert_select 'attachment id', :text => '1' do
294 assert_select '~ filename', :text => 'error281.txt'
294 assert_select '~ filename', :text => 'error281.txt'
295 assert_select '~ content_url', :text => 'http://www.example.com/attachments/download/1/error281.txt'
295 assert_select '~ content_url', :text => 'http://www.example.com/attachments/download/1/error281.txt'
296 end
296 end
297 end
297 end
298 end
298 end
299
299
300 test "GET /issues/:id.xml with subtasks" do
300 test "GET /issues/:id.xml with subtasks" do
301 issue = Issue.generate_with_descendants!(:project_id => 1)
301 issue = Issue.generate_with_descendants!(:project_id => 1)
302 get "/issues/#{issue.id}.xml?include=children"
302 get "/issues/#{issue.id}.xml?include=children"
303
303
304 assert_select 'issue id', :text => issue.id.to_s do
304 assert_select 'issue id', :text => issue.id.to_s do
305 assert_select '~ children[type=array] > issue', 2
305 assert_select '~ children[type=array] > issue', 2
306 assert_select '~ children[type=array] > issue > children', 1
306 assert_select '~ children[type=array] > issue > children', 1
307 end
307 end
308 end
308 end
309
309
310 test "GET /issues/:id.json with subtasks" do
310 test "GET /issues/:id.json with subtasks" do
311 issue = Issue.generate_with_descendants!(:project_id => 1)
311 issue = Issue.generate_with_descendants!(:project_id => 1)
312 get "/issues/#{issue.id}.json?include=children"
312 get "/issues/#{issue.id}.json?include=children"
313
313
314 json = ActiveSupport::JSON.decode(response.body)
314 json = ActiveSupport::JSON.decode(response.body)
315 assert_equal 2, json['issue']['children'].size
315 assert_equal 2, json['issue']['children'].size
316 assert_equal 1, json['issue']['children'].select {|child| child.key?('children')}.size
316 assert_equal 1, json['issue']['children'].select {|child| child.key?('children')}.size
317 end
317 end
318
318
319 def test_show_should_include_issue_attributes
319 def test_show_should_include_issue_attributes
320 get '/issues/1.xml'
320 get '/issues/1.xml'
321 assert_select 'issue>is_private', :text => 'false'
321 assert_select 'issue>is_private', :text => 'false'
322 end
322 end
323
323
324 test "GET /issues/:id.xml?include=watchers should include watchers" do
324 test "GET /issues/:id.xml?include=watchers should include watchers" do
325 Watcher.create!(:user_id => 3, :watchable => Issue.find(1))
325 Watcher.create!(:user_id => 3, :watchable => Issue.find(1))
326
326
327 get '/issues/1.xml?include=watchers', {}, credentials('jsmith')
327 get '/issues/1.xml?include=watchers', {}, credentials('jsmith')
328
328
329 assert_response :ok
329 assert_response :ok
330 assert_equal 'application/xml', response.content_type
330 assert_equal 'application/xml', response.content_type
331 assert_select 'issue' do
331 assert_select 'issue' do
332 assert_select 'watchers', Issue.find(1).watchers.count
332 assert_select 'watchers', Issue.find(1).watchers.count
333 assert_select 'watchers' do
333 assert_select 'watchers' do
334 assert_select 'user[id="3"]'
334 assert_select 'user[id="3"]'
335 end
335 end
336 end
336 end
337 end
337 end
338
338
339 test "POST /issues.xml should create an issue with the attributes" do
339 test "POST /issues.xml should create an issue with the attributes" do
340
340
341 payload = <<-XML
341 payload = <<-XML
342 <?xml version="1.0" encoding="UTF-8" ?>
342 <?xml version="1.0" encoding="UTF-8" ?>
343 <issue>
343 <issue>
344 <project_id>1</project_id>
344 <project_id>1</project_id>
345 <tracker_id>2</tracker_id>
345 <tracker_id>2</tracker_id>
346 <status_id>3</status_id>
346 <status_id>3</status_id>
347 <subject>API test</subject>
347 <subject>API test</subject>
348 </issue>
348 </issue>
349 XML
349 XML
350
350
351 assert_difference('Issue.count') do
351 assert_difference('Issue.count') do
352 post '/issues.xml', payload, {"CONTENT_TYPE" => 'application/xml'}.merge(credentials('jsmith'))
352 post '/issues.xml', payload, {"CONTENT_TYPE" => 'application/xml'}.merge(credentials('jsmith'))
353 end
353 end
354 issue = Issue.order('id DESC').first
354 issue = Issue.order('id DESC').first
355 assert_equal 1, issue.project_id
355 assert_equal 1, issue.project_id
356 assert_equal 2, issue.tracker_id
356 assert_equal 2, issue.tracker_id
357 assert_equal 3, issue.status_id
357 assert_equal 3, issue.status_id
358 assert_equal 'API test', issue.subject
358 assert_equal 'API test', issue.subject
359
359
360 assert_response :created
360 assert_response :created
361 assert_equal 'application/xml', @response.content_type
361 assert_equal 'application/xml', @response.content_type
362 assert_select 'issue > id', :text => issue.id.to_s
362 assert_select 'issue > id', :text => issue.id.to_s
363 end
363 end
364
364
365 test "POST /issues.xml with watcher_user_ids should create issue with watchers" do
365 test "POST /issues.xml with watcher_user_ids should create issue with watchers" do
366 assert_difference('Issue.count') do
366 assert_difference('Issue.count') do
367 post '/issues.xml',
367 post '/issues.xml',
368 {:issue => {:project_id => 1, :subject => 'Watchers',
368 {:issue => {:project_id => 1, :subject => 'Watchers',
369 :tracker_id => 2, :status_id => 3, :watcher_user_ids => [3, 1]}}, credentials('jsmith')
369 :tracker_id => 2, :status_id => 3, :watcher_user_ids => [3, 1]}}, credentials('jsmith')
370 assert_response :created
370 assert_response :created
371 end
371 end
372 issue = Issue.order('id desc').first
372 issue = Issue.order('id desc').first
373 assert_equal 2, issue.watchers.size
373 assert_equal 2, issue.watchers.size
374 assert_equal [1, 3], issue.watcher_user_ids.sort
374 assert_equal [1, 3], issue.watcher_user_ids.sort
375 end
375 end
376
376
377 test "POST /issues.xml with failure should return errors" do
377 test "POST /issues.xml with failure should return errors" do
378 assert_no_difference('Issue.count') do
378 assert_no_difference('Issue.count') do
379 post '/issues.xml', {:issue => {:project_id => 1}}, credentials('jsmith')
379 post '/issues.xml', {:issue => {:project_id => 1}}, credentials('jsmith')
380 end
380 end
381
381
382 assert_select 'errors error', :text => "Subject cannot be blank"
382 assert_select 'errors error', :text => "Subject cannot be blank"
383 end
383 end
384
384
385 test "POST /issues.json should create an issue with the attributes" do
385 test "POST /issues.json should create an issue with the attributes" do
386
386
387 payload = <<-JSON
387 payload = <<-JSON
388 {
388 {
389 "issue": {
389 "issue": {
390 "project_id": "1",
390 "project_id": "1",
391 "tracker_id": "2",
391 "tracker_id": "2",
392 "status_id": "3",
392 "status_id": "3",
393 "subject": "API test"
393 "subject": "API test"
394 }
394 }
395 }
395 }
396 JSON
396 JSON
397
397
398 assert_difference('Issue.count') do
398 assert_difference('Issue.count') do
399 post '/issues.json', payload, {"CONTENT_TYPE" => 'application/json'}.merge(credentials('jsmith'))
399 post '/issues.json', payload, {"CONTENT_TYPE" => 'application/json'}.merge(credentials('jsmith'))
400 end
400 end
401
401
402 issue = Issue.order('id DESC').first
402 issue = Issue.order('id DESC').first
403 assert_equal 1, issue.project_id
403 assert_equal 1, issue.project_id
404 assert_equal 2, issue.tracker_id
404 assert_equal 2, issue.tracker_id
405 assert_equal 3, issue.status_id
405 assert_equal 3, issue.status_id
406 assert_equal 'API test', issue.subject
406 assert_equal 'API test', issue.subject
407 end
407 end
408
408
409 test "POST /issues.json without tracker_id should accept custom fields" do
409 test "POST /issues.json without tracker_id should accept custom fields" do
410 field = IssueCustomField.generate!(
410 field = IssueCustomField.generate!(
411 :field_format => 'list',
411 :field_format => 'list',
412 :multiple => true,
412 :multiple => true,
413 :possible_values => ["V1", "V2", "V3"],
413 :possible_values => ["V1", "V2", "V3"],
414 :default_value => "V2",
414 :default_value => "V2",
415 :is_for_all => true,
415 :is_for_all => true,
416 :trackers => Tracker.all.to_a
416 :trackers => Tracker.all.to_a
417 )
417 )
418
418
419 payload = <<-JSON
419 payload = <<-JSON
420 {
420 {
421 "issue": {
421 "issue": {
422 "project_id": "1",
422 "project_id": "1",
423 "subject": "Multivalued custom field",
423 "subject": "Multivalued custom field",
424 "custom_field_values":{"#{field.id}":["V1","V3"]}
424 "custom_field_values":{"#{field.id}":["V1","V3"]}
425 }
425 }
426 }
426 }
427 JSON
427 JSON
428
428
429 assert_difference('Issue.count') do
429 assert_difference('Issue.count') do
430 post '/issues.json', payload, {"CONTENT_TYPE" => 'application/json'}.merge(credentials('jsmith'))
430 post '/issues.json', payload, {"CONTENT_TYPE" => 'application/json'}.merge(credentials('jsmith'))
431 end
431 end
432
432
433 assert_response :created
433 assert_response :created
434 issue = Issue.order('id DESC').first
434 issue = Issue.order('id DESC').first
435 assert_equal ["V1", "V3"], issue.custom_field_value(field).sort
435 assert_equal ["V1", "V3"], issue.custom_field_value(field).sort
436 end
436 end
437
437
438 test "POST /issues.json with failure should return errors" do
438 test "POST /issues.json with failure should return errors" do
439 assert_no_difference('Issue.count') do
439 assert_no_difference('Issue.count') do
440 post '/issues.json', {:issue => {:project_id => 1}}, credentials('jsmith')
440 post '/issues.json', {:issue => {:project_id => 1}}, credentials('jsmith')
441 end
441 end
442
442
443 json = ActiveSupport::JSON.decode(response.body)
443 json = ActiveSupport::JSON.decode(response.body)
444 assert json['errors'].include?("Subject cannot be blank")
444 assert json['errors'].include?("Subject cannot be blank")
445 end
445 end
446
446
447 test "POST /issues.json with invalid project_id should respond with 422" do
448 post '/issues.json', {:issue => {:project_id => 999, :subject => "API"}}, credentials('jsmith')
449 assert_response 422
450 end
451
447 test "PUT /issues/:id.xml" do
452 test "PUT /issues/:id.xml" do
448 assert_difference('Journal.count') do
453 assert_difference('Journal.count') do
449 put '/issues/6.xml',
454 put '/issues/6.xml',
450 {:issue => {:subject => 'API update', :notes => 'A new note'}},
455 {:issue => {:subject => 'API update', :notes => 'A new note'}},
451 credentials('jsmith')
456 credentials('jsmith')
452 end
457 end
453
458
454 issue = Issue.find(6)
459 issue = Issue.find(6)
455 assert_equal "API update", issue.subject
460 assert_equal "API update", issue.subject
456 journal = Journal.last
461 journal = Journal.last
457 assert_equal "A new note", journal.notes
462 assert_equal "A new note", journal.notes
458 end
463 end
459
464
460 test "PUT /issues/:id.xml with custom fields" do
465 test "PUT /issues/:id.xml with custom fields" do
461 put '/issues/3.xml',
466 put '/issues/3.xml',
462 {:issue => {:custom_fields => [
467 {:issue => {:custom_fields => [
463 {'id' => '1', 'value' => 'PostgreSQL' },
468 {'id' => '1', 'value' => 'PostgreSQL' },
464 {'id' => '2', 'value' => '150'}
469 {'id' => '2', 'value' => '150'}
465 ]}},
470 ]}},
466 credentials('jsmith')
471 credentials('jsmith')
467
472
468 issue = Issue.find(3)
473 issue = Issue.find(3)
469 assert_equal '150', issue.custom_value_for(2).value
474 assert_equal '150', issue.custom_value_for(2).value
470 assert_equal 'PostgreSQL', issue.custom_value_for(1).value
475 assert_equal 'PostgreSQL', issue.custom_value_for(1).value
471 end
476 end
472
477
473 test "PUT /issues/:id.xml with multi custom fields" do
478 test "PUT /issues/:id.xml with multi custom fields" do
474 field = CustomField.find(1)
479 field = CustomField.find(1)
475 field.update_attribute :multiple, true
480 field.update_attribute :multiple, true
476
481
477 put '/issues/3.xml',
482 put '/issues/3.xml',
478 {:issue => {:custom_fields => [
483 {:issue => {:custom_fields => [
479 {'id' => '1', 'value' => ['MySQL', 'PostgreSQL'] },
484 {'id' => '1', 'value' => ['MySQL', 'PostgreSQL'] },
480 {'id' => '2', 'value' => '150'}
485 {'id' => '2', 'value' => '150'}
481 ]}},
486 ]}},
482 credentials('jsmith')
487 credentials('jsmith')
483
488
484 issue = Issue.find(3)
489 issue = Issue.find(3)
485 assert_equal '150', issue.custom_value_for(2).value
490 assert_equal '150', issue.custom_value_for(2).value
486 assert_equal ['MySQL', 'PostgreSQL'], issue.custom_field_value(1).sort
491 assert_equal ['MySQL', 'PostgreSQL'], issue.custom_field_value(1).sort
487 end
492 end
488
493
489 test "PUT /issues/:id.xml with project change" do
494 test "PUT /issues/:id.xml with project change" do
490 put '/issues/3.xml',
495 put '/issues/3.xml',
491 {:issue => {:project_id => 2, :subject => 'Project changed'}},
496 {:issue => {:project_id => 2, :subject => 'Project changed'}},
492 credentials('jsmith')
497 credentials('jsmith')
493
498
494 issue = Issue.find(3)
499 issue = Issue.find(3)
495 assert_equal 2, issue.project_id
500 assert_equal 2, issue.project_id
496 assert_equal 'Project changed', issue.subject
501 assert_equal 'Project changed', issue.subject
497 end
502 end
498
503
499 test "PUT /issues/:id.xml with notes only" do
504 test "PUT /issues/:id.xml with notes only" do
500 assert_difference('Journal.count') do
505 assert_difference('Journal.count') do
501 put '/issues/6.xml',
506 put '/issues/6.xml',
502 {:issue => {:notes => 'Notes only'}},
507 {:issue => {:notes => 'Notes only'}},
503 credentials('jsmith')
508 credentials('jsmith')
504 end
509 end
505
510
506 journal = Journal.last
511 journal = Journal.last
507 assert_equal "Notes only", journal.notes
512 assert_equal "Notes only", journal.notes
508 end
513 end
509
514
510 test "PUT /issues/:id.xml with failed update" do
515 test "PUT /issues/:id.xml with failed update" do
511 put '/issues/6.xml', {:issue => {:subject => ''}}, credentials('jsmith')
516 put '/issues/6.xml', {:issue => {:subject => ''}}, credentials('jsmith')
512
517
513 assert_response :unprocessable_entity
518 assert_response :unprocessable_entity
514 assert_select 'errors error', :text => "Subject cannot be blank"
519 assert_select 'errors error', :text => "Subject cannot be blank"
515 end
520 end
516
521
517 test "PUT /issues/:id.json" do
522 test "PUT /issues/:id.json" do
518 assert_difference('Journal.count') do
523 assert_difference('Journal.count') do
519 put '/issues/6.json',
524 put '/issues/6.json',
520 {:issue => {:subject => 'API update', :notes => 'A new note'}},
525 {:issue => {:subject => 'API update', :notes => 'A new note'}},
521 credentials('jsmith')
526 credentials('jsmith')
522
527
523 assert_response :ok
528 assert_response :ok
524 assert_equal '', response.body
529 assert_equal '', response.body
525 end
530 end
526
531
527 issue = Issue.find(6)
532 issue = Issue.find(6)
528 assert_equal "API update", issue.subject
533 assert_equal "API update", issue.subject
529 journal = Journal.last
534 journal = Journal.last
530 assert_equal "A new note", journal.notes
535 assert_equal "A new note", journal.notes
531 end
536 end
532
537
533 test "PUT /issues/:id.json with failed update" do
538 test "PUT /issues/:id.json with failed update" do
534 put '/issues/6.json', {:issue => {:subject => ''}}, credentials('jsmith')
539 put '/issues/6.json', {:issue => {:subject => ''}}, credentials('jsmith')
535
540
536 assert_response :unprocessable_entity
541 assert_response :unprocessable_entity
537 json = ActiveSupport::JSON.decode(response.body)
542 json = ActiveSupport::JSON.decode(response.body)
538 assert json['errors'].include?("Subject cannot be blank")
543 assert json['errors'].include?("Subject cannot be blank")
539 end
544 end
540
545
541 test "DELETE /issues/:id.xml" do
546 test "DELETE /issues/:id.xml" do
542 assert_difference('Issue.count', -1) do
547 assert_difference('Issue.count', -1) do
543 delete '/issues/6.xml', {}, credentials('jsmith')
548 delete '/issues/6.xml', {}, credentials('jsmith')
544
549
545 assert_response :ok
550 assert_response :ok
546 assert_equal '', response.body
551 assert_equal '', response.body
547 end
552 end
548 assert_nil Issue.find_by_id(6)
553 assert_nil Issue.find_by_id(6)
549 end
554 end
550
555
551 test "DELETE /issues/:id.json" do
556 test "DELETE /issues/:id.json" do
552 assert_difference('Issue.count', -1) do
557 assert_difference('Issue.count', -1) do
553 delete '/issues/6.json', {}, credentials('jsmith')
558 delete '/issues/6.json', {}, credentials('jsmith')
554
559
555 assert_response :ok
560 assert_response :ok
556 assert_equal '', response.body
561 assert_equal '', response.body
557 end
562 end
558 assert_nil Issue.find_by_id(6)
563 assert_nil Issue.find_by_id(6)
559 end
564 end
560
565
561 test "POST /issues/:id/watchers.xml should add watcher" do
566 test "POST /issues/:id/watchers.xml should add watcher" do
562 assert_difference 'Watcher.count' do
567 assert_difference 'Watcher.count' do
563 post '/issues/1/watchers.xml', {:user_id => 3}, credentials('jsmith')
568 post '/issues/1/watchers.xml', {:user_id => 3}, credentials('jsmith')
564
569
565 assert_response :ok
570 assert_response :ok
566 assert_equal '', response.body
571 assert_equal '', response.body
567 end
572 end
568 watcher = Watcher.order('id desc').first
573 watcher = Watcher.order('id desc').first
569 assert_equal Issue.find(1), watcher.watchable
574 assert_equal Issue.find(1), watcher.watchable
570 assert_equal User.find(3), watcher.user
575 assert_equal User.find(3), watcher.user
571 end
576 end
572
577
573 test "DELETE /issues/:id/watchers/:user_id.xml should remove watcher" do
578 test "DELETE /issues/:id/watchers/:user_id.xml should remove watcher" do
574 Watcher.create!(:user_id => 3, :watchable => Issue.find(1))
579 Watcher.create!(:user_id => 3, :watchable => Issue.find(1))
575
580
576 assert_difference 'Watcher.count', -1 do
581 assert_difference 'Watcher.count', -1 do
577 delete '/issues/1/watchers/3.xml', {}, credentials('jsmith')
582 delete '/issues/1/watchers/3.xml', {}, credentials('jsmith')
578
583
579 assert_response :ok
584 assert_response :ok
580 assert_equal '', response.body
585 assert_equal '', response.body
581 end
586 end
582 assert_equal false, Issue.find(1).watched_by?(User.find(3))
587 assert_equal false, Issue.find(1).watched_by?(User.find(3))
583 end
588 end
584
589
585 def test_create_issue_with_uploaded_file
590 def test_create_issue_with_uploaded_file
586 token = xml_upload('test_create_with_upload', credentials('jsmith'))
591 token = xml_upload('test_create_with_upload', credentials('jsmith'))
587 attachment = Attachment.find_by_token(token)
592 attachment = Attachment.find_by_token(token)
588
593
589 # create the issue with the upload's token
594 # create the issue with the upload's token
590 assert_difference 'Issue.count' do
595 assert_difference 'Issue.count' do
591 post '/issues.xml',
596 post '/issues.xml',
592 {:issue => {:project_id => 1, :subject => 'Uploaded file',
597 {:issue => {:project_id => 1, :subject => 'Uploaded file',
593 :uploads => [{:token => token, :filename => 'test.txt',
598 :uploads => [{:token => token, :filename => 'test.txt',
594 :content_type => 'text/plain'}]}},
599 :content_type => 'text/plain'}]}},
595 credentials('jsmith')
600 credentials('jsmith')
596 assert_response :created
601 assert_response :created
597 end
602 end
598 issue = Issue.order('id DESC').first
603 issue = Issue.order('id DESC').first
599 assert_equal 1, issue.attachments.count
604 assert_equal 1, issue.attachments.count
600 assert_equal attachment, issue.attachments.first
605 assert_equal attachment, issue.attachments.first
601
606
602 attachment.reload
607 attachment.reload
603 assert_equal 'test.txt', attachment.filename
608 assert_equal 'test.txt', attachment.filename
604 assert_equal 'text/plain', attachment.content_type
609 assert_equal 'text/plain', attachment.content_type
605 assert_equal 'test_create_with_upload'.size, attachment.filesize
610 assert_equal 'test_create_with_upload'.size, attachment.filesize
606 assert_equal 2, attachment.author_id
611 assert_equal 2, attachment.author_id
607
612
608 # get the issue with its attachments
613 # get the issue with its attachments
609 get "/issues/#{issue.id}.xml", :include => 'attachments'
614 get "/issues/#{issue.id}.xml", :include => 'attachments'
610 assert_response :success
615 assert_response :success
611 xml = Hash.from_xml(response.body)
616 xml = Hash.from_xml(response.body)
612 attachments = xml['issue']['attachments']
617 attachments = xml['issue']['attachments']
613 assert_kind_of Array, attachments
618 assert_kind_of Array, attachments
614 assert_equal 1, attachments.size
619 assert_equal 1, attachments.size
615 url = attachments.first['content_url']
620 url = attachments.first['content_url']
616 assert_not_nil url
621 assert_not_nil url
617
622
618 # download the attachment
623 # download the attachment
619 get url
624 get url
620 assert_response :success
625 assert_response :success
621 assert_equal 'test_create_with_upload', response.body
626 assert_equal 'test_create_with_upload', response.body
622 end
627 end
623
628
624 def test_create_issue_with_multiple_uploaded_files_as_xml
629 def test_create_issue_with_multiple_uploaded_files_as_xml
625 token1 = xml_upload('File content 1', credentials('jsmith'))
630 token1 = xml_upload('File content 1', credentials('jsmith'))
626 token2 = xml_upload('File content 2', credentials('jsmith'))
631 token2 = xml_upload('File content 2', credentials('jsmith'))
627
632
628 payload = <<-XML
633 payload = <<-XML
629 <?xml version="1.0" encoding="UTF-8" ?>
634 <?xml version="1.0" encoding="UTF-8" ?>
630 <issue>
635 <issue>
631 <project_id>1</project_id>
636 <project_id>1</project_id>
632 <tracker_id>1</tracker_id>
637 <tracker_id>1</tracker_id>
633 <subject>Issue with multiple attachments</subject>
638 <subject>Issue with multiple attachments</subject>
634 <uploads type="array">
639 <uploads type="array">
635 <upload>
640 <upload>
636 <token>#{token1}</token>
641 <token>#{token1}</token>
637 <filename>test1.txt</filename>
642 <filename>test1.txt</filename>
638 </upload>
643 </upload>
639 <upload>
644 <upload>
640 <token>#{token2}</token>
645 <token>#{token2}</token>
641 <filename>test1.txt</filename>
646 <filename>test1.txt</filename>
642 </upload>
647 </upload>
643 </uploads>
648 </uploads>
644 </issue>
649 </issue>
645 XML
650 XML
646
651
647 assert_difference 'Issue.count' do
652 assert_difference 'Issue.count' do
648 post '/issues.xml', payload, {"CONTENT_TYPE" => 'application/xml'}.merge(credentials('jsmith'))
653 post '/issues.xml', payload, {"CONTENT_TYPE" => 'application/xml'}.merge(credentials('jsmith'))
649 assert_response :created
654 assert_response :created
650 end
655 end
651 issue = Issue.order('id DESC').first
656 issue = Issue.order('id DESC').first
652 assert_equal 2, issue.attachments.count
657 assert_equal 2, issue.attachments.count
653 end
658 end
654
659
655 def test_create_issue_with_multiple_uploaded_files_as_json
660 def test_create_issue_with_multiple_uploaded_files_as_json
656 token1 = json_upload('File content 1', credentials('jsmith'))
661 token1 = json_upload('File content 1', credentials('jsmith'))
657 token2 = json_upload('File content 2', credentials('jsmith'))
662 token2 = json_upload('File content 2', credentials('jsmith'))
658
663
659 payload = <<-JSON
664 payload = <<-JSON
660 {
665 {
661 "issue": {
666 "issue": {
662 "project_id": "1",
667 "project_id": "1",
663 "tracker_id": "1",
668 "tracker_id": "1",
664 "subject": "Issue with multiple attachments",
669 "subject": "Issue with multiple attachments",
665 "uploads": [
670 "uploads": [
666 {"token": "#{token1}", "filename": "test1.txt"},
671 {"token": "#{token1}", "filename": "test1.txt"},
667 {"token": "#{token2}", "filename": "test2.txt"}
672 {"token": "#{token2}", "filename": "test2.txt"}
668 ]
673 ]
669 }
674 }
670 }
675 }
671 JSON
676 JSON
672
677
673 assert_difference 'Issue.count' do
678 assert_difference 'Issue.count' do
674 post '/issues.json', payload, {"CONTENT_TYPE" => 'application/json'}.merge(credentials('jsmith'))
679 post '/issues.json', payload, {"CONTENT_TYPE" => 'application/json'}.merge(credentials('jsmith'))
675 assert_response :created
680 assert_response :created
676 end
681 end
677 issue = Issue.order('id DESC').first
682 issue = Issue.order('id DESC').first
678 assert_equal 2, issue.attachments.count
683 assert_equal 2, issue.attachments.count
679 end
684 end
680
685
681 def test_update_issue_with_uploaded_file
686 def test_update_issue_with_uploaded_file
682 token = xml_upload('test_upload_with_upload', credentials('jsmith'))
687 token = xml_upload('test_upload_with_upload', credentials('jsmith'))
683 attachment = Attachment.find_by_token(token)
688 attachment = Attachment.find_by_token(token)
684
689
685 # update the issue with the upload's token
690 # update the issue with the upload's token
686 assert_difference 'Journal.count' do
691 assert_difference 'Journal.count' do
687 put '/issues/1.xml',
692 put '/issues/1.xml',
688 {:issue => {:notes => 'Attachment added',
693 {:issue => {:notes => 'Attachment added',
689 :uploads => [{:token => token, :filename => 'test.txt',
694 :uploads => [{:token => token, :filename => 'test.txt',
690 :content_type => 'text/plain'}]}},
695 :content_type => 'text/plain'}]}},
691 credentials('jsmith')
696 credentials('jsmith')
692 assert_response :ok
697 assert_response :ok
693 assert_equal '', @response.body
698 assert_equal '', @response.body
694 end
699 end
695
700
696 issue = Issue.find(1)
701 issue = Issue.find(1)
697 assert_include attachment, issue.attachments
702 assert_include attachment, issue.attachments
698 end
703 end
699 end
704 end
General Comments 0
You need to be logged in to leave comments. Login now