##// END OF EJS Templates
Backported r4357, r4358, r4360 and r4363 to r4367 from trunk....
Jean-Philippe Lang -
r4325:541a371b412a
parent child
Show More
@@ -0,0 +1,31
1 require "#{File.dirname(__FILE__)}/../../test_helper"
2
3 class ApiTest::HttpBasicLoginTest < ActionController::IntegrationTest
4 fixtures :all
5
6 def setup
7 Setting.rest_api_enabled = '1'
8 Setting.login_required = '1'
9 end
10
11 def teardown
12 Setting.rest_api_enabled = '0'
13 Setting.login_required = '0'
14 end
15
16 # Using the NewsController because it's a simple API.
17 context "get /news" do
18 setup do
19 project = Project.find('onlinestore')
20 EnabledModule.create(:project => project, :name => 'news')
21 end
22
23 context "in :xml format" do
24 should_allow_http_basic_auth_with_username_and_password(:get, "/projects/onlinestore/news.xml")
25 end
26
27 context "in :json format" do
28 should_allow_http_basic_auth_with_username_and_password(:get, "/projects/onlinestore/news.json")
29 end
30 end
31 end
@@ -0,0 +1,27
1 require "#{File.dirname(__FILE__)}/../../test_helper"
2
3 class ApiTest::HttpBasicLoginWithApiTokenTest < ActionController::IntegrationTest
4 fixtures :all
5
6 def setup
7 Setting.rest_api_enabled = '1'
8 Setting.login_required = '1'
9 end
10
11 def teardown
12 Setting.rest_api_enabled = '0'
13 Setting.login_required = '0'
14 end
15
16 # Using the NewsController because it's a simple API.
17 context "get /news" do
18
19 context "in :xml format" do
20 should_allow_http_basic_auth_with_key(:get, "/news.xml")
21 end
22
23 context "in :json format" do
24 should_allow_http_basic_auth_with_key(:get, "/news.json")
25 end
26 end
27 end
@@ -0,0 +1,336
1 # Redmine - project management software
2 # Copyright (C) 2006-2010 Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
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
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 require "#{File.dirname(__FILE__)}/../../test_helper"
19
20 class ApiTest::IssuesTest < ActionController::IntegrationTest
21 fixtures :projects,
22 :users,
23 :roles,
24 :members,
25 :member_roles,
26 :issues,
27 :issue_statuses,
28 :versions,
29 :trackers,
30 :projects_trackers,
31 :issue_categories,
32 :enabled_modules,
33 :enumerations,
34 :attachments,
35 :workflows,
36 :custom_fields,
37 :custom_values,
38 :custom_fields_projects,
39 :custom_fields_trackers,
40 :time_entries,
41 :journals,
42 :journal_details,
43 :queries
44
45 def setup
46 Setting.rest_api_enabled = '1'
47 end
48
49 # Use a private project to make sure auth is really working and not just
50 # only showing public issues.
51 context "/index.xml" do
52 should_allow_api_authentication(:get, "/projects/private-child/issues.xml")
53 end
54
55 context "/index.json" do
56 should_allow_api_authentication(:get, "/projects/private-child/issues.json")
57 end
58
59 context "/index.xml with filter" do
60 should_allow_api_authentication(:get, "/projects/private-child/issues.xml?status_id=5")
61
62 should "show only issues with the status_id" do
63 get '/issues.xml?status_id=5'
64 assert_tag :tag => 'issues',
65 :children => { :count => Issue.visible.count(:conditions => {:status_id => 5}),
66 :only => { :tag => 'issue' } }
67 end
68 end
69
70 context "/index.json with filter" do
71 should_allow_api_authentication(:get, "/projects/private-child/issues.json?status_id=5")
72
73 should "show only issues with the status_id" do
74 get '/issues.json?status_id=5'
75
76 json = ActiveSupport::JSON.decode(response.body)
77 status_ids_used = json.collect {|j| j['status_id'] }
78 assert_equal 3, status_ids_used.length
79 assert status_ids_used.all? {|id| id == 5 }
80 end
81
82 end
83
84 # Issue 6 is on a private project
85 context "/issues/6.xml" do
86 should_allow_api_authentication(:get, "/issues/6.xml")
87 end
88
89 context "/issues/6.json" do
90 should_allow_api_authentication(:get, "/issues/6.json")
91 end
92
93 context "POST /issues.xml" do
94 should_allow_api_authentication(:post,
95 '/issues.xml',
96 {:issue => {:project_id => 1, :subject => 'API test', :tracker_id => 2, :status_id => 3}},
97 {:success_code => :created})
98
99 should "create an issue with the attributes" do
100 assert_difference('Issue.count') do
101 post '/issues.xml', {:issue => {:project_id => 1, :subject => 'API test', :tracker_id => 2, :status_id => 3}}, :authorization => credentials('jsmith')
102 end
103
104 issue = Issue.first(:order => 'id DESC')
105 assert_equal 1, issue.project_id
106 assert_equal 2, issue.tracker_id
107 assert_equal 3, issue.status_id
108 assert_equal 'API test', issue.subject
109 end
110 end
111
112 context "POST /issues.xml with failure" do
113 should_allow_api_authentication(:post,
114 '/issues.xml',
115 {:issue => {:project_id => 1}},
116 {:success_code => :unprocessable_entity})
117
118 should "have an errors tag" do
119 assert_no_difference('Issue.count') do
120 post '/issues.xml', {:issue => {:project_id => 1}}, :authorization => credentials('jsmith')
121 end
122
123 assert_tag :errors, :child => {:tag => 'error', :content => "Subject can't be blank"}
124 end
125 end
126
127 context "POST /issues.json" do
128 should_allow_api_authentication(:post,
129 '/issues.json',
130 {:issue => {:project_id => 1, :subject => 'API test', :tracker_id => 2, :status_id => 3}},
131 {:success_code => :created})
132
133 should "create an issue with the attributes" do
134 assert_difference('Issue.count') do
135 post '/issues.json', {:issue => {:project_id => 1, :subject => 'API test', :tracker_id => 2, :status_id => 3}}, :authorization => credentials('jsmith')
136 end
137
138 issue = Issue.first(:order => 'id DESC')
139 assert_equal 1, issue.project_id
140 assert_equal 2, issue.tracker_id
141 assert_equal 3, issue.status_id
142 assert_equal 'API test', issue.subject
143 end
144
145 end
146
147 context "POST /issues.json with failure" do
148 should_allow_api_authentication(:post,
149 '/issues.json',
150 {:issue => {:project_id => 1}},
151 {:success_code => :unprocessable_entity})
152
153 should "have an errors element" do
154 assert_no_difference('Issue.count') do
155 post '/issues.json', {:issue => {:project_id => 1}}, :authorization => credentials('jsmith')
156 end
157
158 json = ActiveSupport::JSON.decode(response.body)
159 assert_equal "can't be blank", json.first['subject']
160 end
161 end
162
163 # Issue 6 is on a private project
164 context "PUT /issues/6.xml" do
165 setup do
166 @parameters = {:issue => {:subject => 'API update', :notes => 'A new note'}}
167 @headers = { :authorization => credentials('jsmith') }
168 end
169
170 should_allow_api_authentication(:put,
171 '/issues/6.xml',
172 {:issue => {:subject => 'API update', :notes => 'A new note'}},
173 {:success_code => :ok})
174
175 should "not create a new issue" do
176 assert_no_difference('Issue.count') do
177 put '/issues/6.xml', @parameters, @headers
178 end
179 end
180
181 should "create a new journal" do
182 assert_difference('Journal.count') do
183 put '/issues/6.xml', @parameters, @headers
184 end
185 end
186
187 should "add the note to the journal" do
188 put '/issues/6.xml', @parameters, @headers
189
190 journal = Journal.last
191 assert_equal "A new note", journal.notes
192 end
193
194 should "update the issue" do
195 put '/issues/6.xml', @parameters, @headers
196
197 issue = Issue.find(6)
198 assert_equal "API update", issue.subject
199 end
200
201 end
202
203 context "PUT /issues/6.xml with failed update" do
204 setup do
205 @parameters = {:issue => {:subject => ''}}
206 @headers = { :authorization => credentials('jsmith') }
207 end
208
209 should_allow_api_authentication(:put,
210 '/issues/6.xml',
211 {:issue => {:subject => ''}}, # Missing subject should fail
212 {:success_code => :unprocessable_entity})
213
214 should "not create a new issue" do
215 assert_no_difference('Issue.count') do
216 put '/issues/6.xml', @parameters, @headers
217 end
218 end
219
220 should "not create a new journal" do
221 assert_no_difference('Journal.count') do
222 put '/issues/6.xml', @parameters, @headers
223 end
224 end
225
226 should "have an errors tag" do
227 put '/issues/6.xml', @parameters, @headers
228
229 assert_tag :errors, :child => {:tag => 'error', :content => "Subject can't be blank"}
230 end
231 end
232
233 context "PUT /issues/6.json" do
234 setup do
235 @parameters = {:issue => {:subject => 'API update', :notes => 'A new note'}}
236 @headers = { :authorization => credentials('jsmith') }
237 end
238
239 should_allow_api_authentication(:put,
240 '/issues/6.json',
241 {:issue => {:subject => 'API update', :notes => 'A new note'}},
242 {:success_code => :ok})
243
244 should "not create a new issue" do
245 assert_no_difference('Issue.count') do
246 put '/issues/6.json', @parameters, @headers
247 end
248 end
249
250 should "create a new journal" do
251 assert_difference('Journal.count') do
252 put '/issues/6.json', @parameters, @headers
253 end
254 end
255
256 should "add the note to the journal" do
257 put '/issues/6.json', @parameters, @headers
258
259 journal = Journal.last
260 assert_equal "A new note", journal.notes
261 end
262
263 should "update the issue" do
264 put '/issues/6.json', @parameters, @headers
265
266 issue = Issue.find(6)
267 assert_equal "API update", issue.subject
268 end
269
270 end
271
272 context "PUT /issues/6.json with failed update" do
273 setup do
274 @parameters = {:issue => {:subject => ''}}
275 @headers = { :authorization => credentials('jsmith') }
276 end
277
278 should_allow_api_authentication(:put,
279 '/issues/6.json',
280 {:issue => {:subject => ''}}, # Missing subject should fail
281 {:success_code => :unprocessable_entity})
282
283 should "not create a new issue" do
284 assert_no_difference('Issue.count') do
285 put '/issues/6.json', @parameters, @headers
286 end
287 end
288
289 should "not create a new journal" do
290 assert_no_difference('Journal.count') do
291 put '/issues/6.json', @parameters, @headers
292 end
293 end
294
295 should "have an errors attribute" do
296 put '/issues/6.json', @parameters, @headers
297
298 json = ActiveSupport::JSON.decode(response.body)
299 assert_equal "can't be blank", json.first['subject']
300 end
301 end
302
303 context "DELETE /issues/1.xml" do
304 should_allow_api_authentication(:delete,
305 '/issues/6.xml',
306 {},
307 {:success_code => :ok})
308
309 should "delete the issue" do
310 assert_difference('Issue.count',-1) do
311 delete '/issues/6.xml', {}, :authorization => credentials('jsmith')
312 end
313
314 assert_nil Issue.find_by_id(6)
315 end
316 end
317
318 context "DELETE /issues/1.json" do
319 should_allow_api_authentication(:delete,
320 '/issues/6.json',
321 {},
322 {:success_code => :ok})
323
324 should "delete the issue" do
325 assert_difference('Issue.count',-1) do
326 delete '/issues/6.json', {}, :authorization => credentials('jsmith')
327 end
328
329 assert_nil Issue.find_by_id(6)
330 end
331 end
332
333 def credentials(user, password=nil)
334 ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)
335 end
336 end
@@ -0,0 +1,26
1 require "#{File.dirname(__FILE__)}/../../test_helper"
2
3 class ApiTest::TokenAuthenticationTest < ActionController::IntegrationTest
4 fixtures :all
5
6 def setup
7 Setting.rest_api_enabled = '1'
8 Setting.login_required = '1'
9 end
10
11 def teardown
12 Setting.rest_api_enabled = '0'
13 Setting.login_required = '0'
14 end
15
16 # Using the NewsController because it's a simple API.
17 context "get /news" do
18 context "in :xml format" do
19 should_allow_key_based_auth(:get, "/news.xml")
20 end
21
22 context "in :json format" do
23 should_allow_key_based_auth(:get, "/news.json")
24 end
25 end
26 end
@@ -1,328 +1,328
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2008 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class IssuesController < ApplicationController
19 19 menu_item :new_issue, :only => [:new, :create]
20 20 default_search_scope :issues
21 21
22 22 before_filter :find_issue, :only => [:show, :edit, :update]
23 23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy]
24 24 before_filter :find_project, :only => [:new, :create]
25 25 before_filter :authorize, :except => [:index]
26 26 before_filter :find_optional_project, :only => [:index]
27 27 before_filter :check_for_default_issue_status, :only => [:new, :create]
28 28 before_filter :build_new_issue_from_params, :only => [:new, :create]
29 accept_key_auth :index, :show
29 accept_key_auth :index, :show, :create, :update, :destroy
30 30
31 31 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
32 32
33 33 helper :journals
34 34 helper :projects
35 35 include ProjectsHelper
36 36 helper :custom_fields
37 37 include CustomFieldsHelper
38 38 helper :issue_relations
39 39 include IssueRelationsHelper
40 40 helper :watchers
41 41 include WatchersHelper
42 42 helper :attachments
43 43 include AttachmentsHelper
44 44 helper :queries
45 45 include QueriesHelper
46 46 helper :sort
47 47 include SortHelper
48 48 include IssuesHelper
49 49 helper :timelog
50 50 include Redmine::Export::PDF
51 51
52 52 verify :method => [:post, :delete],
53 53 :only => :destroy,
54 54 :render => { :nothing => true, :status => :method_not_allowed }
55 55
56 56 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
57 57 verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
58 58 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
59 59
60 60 def index
61 61 retrieve_query
62 62 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
63 63 sort_update(@query.sortable_columns)
64 64
65 65 if @query.valid?
66 66 limit = case params[:format]
67 67 when 'csv', 'pdf'
68 68 Setting.issues_export_limit.to_i
69 69 when 'atom'
70 70 Setting.feeds_limit.to_i
71 71 else
72 72 per_page_option
73 73 end
74 74
75 75 @issue_count = @query.issue_count
76 76 @issue_pages = Paginator.new self, @issue_count, limit, params['page']
77 77 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
78 78 :order => sort_clause,
79 79 :offset => @issue_pages.current.offset,
80 80 :limit => limit)
81 81 @issue_count_by_group = @query.issue_count_by_group
82 82
83 83 respond_to do |format|
84 84 format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
85 85 format.xml { render :layout => false }
86 86 format.json { render :text => @issues.to_json, :layout => false }
87 87 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
88 88 format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
89 89 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
90 90 end
91 91 else
92 92 # Send html if the query is not valid
93 93 render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
94 94 end
95 95 rescue ActiveRecord::RecordNotFound
96 96 render_404
97 97 end
98 98
99 99 def show
100 100 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
101 101 @journals.each_with_index {|j,i| j.indice = i+1}
102 102 @journals.reverse! if User.current.wants_comments_in_reverse_order?
103 103 @changesets = @issue.changesets.visible.all
104 104 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
105 105 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
106 106 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
107 107 @priorities = IssuePriority.all
108 108 @time_entry = TimeEntry.new
109 109 respond_to do |format|
110 110 format.html { render :template => 'issues/show.rhtml' }
111 111 format.xml { render :layout => false }
112 112 format.json { render :text => @issue.to_json, :layout => false }
113 113 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
114 114 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
115 115 end
116 116 end
117 117
118 118 # Add a new issue
119 119 # The new issue will be created from an existing one if copy_from parameter is given
120 120 def new
121 121 respond_to do |format|
122 122 format.html { render :action => 'new', :layout => !request.xhr? }
123 123 format.js { render :partial => 'attributes' }
124 124 end
125 125 end
126 126
127 127 def create
128 128 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
129 129 if @issue.save
130 130 attachments = Attachment.attach_files(@issue, params[:attachments])
131 131 render_attachment_warning_if_needed(@issue)
132 132 flash[:notice] = l(:notice_successful_create)
133 133 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
134 134 respond_to do |format|
135 135 format.html {
136 136 redirect_to(params[:continue] ? { :action => 'new', :project_id => @project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
137 137 { :action => 'show', :id => @issue })
138 138 }
139 139 format.xml { render :action => 'show', :status => :created, :location => url_for(:controller => 'issues', :action => 'show', :id => @issue) }
140 140 format.json { render :text => @issue.to_json, :status => :created, :location => url_for(:controller => 'issues', :action => 'show'), :layout => false }
141 141 end
142 142 return
143 143 else
144 144 respond_to do |format|
145 145 format.html { render :action => 'new' }
146 146 format.xml { render(:xml => @issue.errors, :status => :unprocessable_entity); return }
147 147 format.json { render :text => object_errors_to_json(@issue), :status => :unprocessable_entity, :layout => false }
148 148 end
149 149 end
150 150 end
151 151
152 152 # Attributes that can be updated on workflow transition (without :edit permission)
153 153 # TODO: make it configurable (at least per role)
154 154 UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
155 155
156 156 def edit
157 157 update_issue_from_params
158 158
159 159 @journal = @issue.current_journal
160 160
161 161 respond_to do |format|
162 162 format.html { }
163 163 format.xml { }
164 164 end
165 165 end
166 166
167 167 def update
168 168 update_issue_from_params
169 169
170 170 if @issue.save_issue_with_child_records(params, @time_entry)
171 171 render_attachment_warning_if_needed(@issue)
172 172 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
173 173
174 174 respond_to do |format|
175 175 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
176 176 format.xml { head :ok }
177 177 format.json { head :ok }
178 178 end
179 179 else
180 180 render_attachment_warning_if_needed(@issue)
181 181 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
182 182 @journal = @issue.current_journal
183 183
184 184 respond_to do |format|
185 185 format.html { render :action => 'edit' }
186 186 format.xml { render :xml => @issue.errors, :status => :unprocessable_entity }
187 187 format.json { render :text => object_errors_to_json(@issue), :status => :unprocessable_entity, :layout => false }
188 188 end
189 189 end
190 190 end
191 191
192 192 # Bulk edit a set of issues
193 193 def bulk_edit
194 194 @issues.sort!
195 195 @available_statuses = Workflow.available_statuses(@project)
196 196 @custom_fields = @project.all_issue_custom_fields
197 197 end
198 198
199 199 def bulk_update
200 200 @issues.sort!
201 201 attributes = parse_params_for_bulk_issue_attributes(params)
202 202
203 203 unsaved_issue_ids = []
204 204 @issues.each do |issue|
205 205 issue.reload
206 206 journal = issue.init_journal(User.current, params[:notes])
207 207 issue.safe_attributes = attributes
208 208 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
209 209 unless issue.save
210 210 # Keep unsaved issue ids to display them in flash error
211 211 unsaved_issue_ids << issue.id
212 212 end
213 213 end
214 214 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
215 215 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
216 216 end
217 217
218 218 def destroy
219 219 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
220 220 if @hours > 0
221 221 case params[:todo]
222 222 when 'destroy'
223 223 # nothing to do
224 224 when 'nullify'
225 225 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
226 226 when 'reassign'
227 227 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
228 228 if reassign_to.nil?
229 229 flash.now[:error] = l(:error_issue_not_found_in_project)
230 230 return
231 231 else
232 232 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
233 233 end
234 234 else
235 235 unless params[:format] == 'xml' || params[:format] == 'json'
236 236 # display the destroy form if it's a user request
237 237 return
238 238 end
239 239 end
240 240 end
241 241 @issues.each(&:destroy)
242 242 respond_to do |format|
243 243 format.html { redirect_to :action => 'index', :project_id => @project }
244 244 format.xml { head :ok }
245 245 format.json { head :ok }
246 246 end
247 247 end
248 248
249 249 private
250 250 def find_issue
251 251 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
252 252 @project = @issue.project
253 253 rescue ActiveRecord::RecordNotFound
254 254 render_404
255 255 end
256 256
257 257 def find_project
258 258 project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
259 259 @project = Project.find(project_id)
260 260 rescue ActiveRecord::RecordNotFound
261 261 render_404
262 262 end
263 263
264 264 # Used by #edit and #update to set some common instance variables
265 265 # from the params
266 266 # TODO: Refactor, not everything in here is needed by #edit
267 267 def update_issue_from_params
268 268 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
269 269 @priorities = IssuePriority.all
270 270 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
271 271 @time_entry = TimeEntry.new
272 272
273 273 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
274 274 @issue.init_journal(User.current, @notes)
275 275 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
276 276 if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
277 277 attrs = params[:issue].dup
278 278 attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
279 279 attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
280 280 @issue.safe_attributes = attrs
281 281 end
282 282
283 283 end
284 284
285 285 # TODO: Refactor, lots of extra code in here
286 286 # TODO: Changing tracker on an existing issue should not trigger this
287 287 def build_new_issue_from_params
288 288 if params[:id].blank?
289 289 @issue = Issue.new
290 290 @issue.copy_from(params[:copy_from]) if params[:copy_from]
291 291 @issue.project = @project
292 292 else
293 293 @issue = @project.issues.visible.find(params[:id])
294 294 end
295 295
296 296 @issue.project = @project
297 297 # Tracker must be set before custom field values
298 298 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
299 299 if @issue.tracker.nil?
300 300 render_error l(:error_no_tracker_in_project)
301 301 return false
302 302 end
303 303 @issue.start_date ||= Date.today
304 304 if params[:issue].is_a?(Hash)
305 305 @issue.safe_attributes = params[:issue]
306 306 if User.current.allowed_to?(:add_issue_watchers, @project) && @issue.new_record?
307 307 @issue.watcher_user_ids = params[:issue]['watcher_user_ids']
308 308 end
309 309 end
310 310 @issue.author = User.current
311 311 @priorities = IssuePriority.all
312 312 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
313 313 end
314 314
315 315 def check_for_default_issue_status
316 316 if IssueStatus.default.nil?
317 317 render_error l(:error_no_default_issue_status)
318 318 return false
319 319 end
320 320 end
321 321
322 322 def parse_params_for_bulk_issue_attributes(params)
323 323 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
324 324 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
325 325 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
326 326 attributes
327 327 end
328 328 end
@@ -1,110 +1,110
1 require "#{File.dirname(__FILE__)}/../test_helper"
1 require "#{File.dirname(__FILE__)}/../../test_helper"
2 2
3 class DisabledRestApi < ActionController::IntegrationTest
3 class ApiTest::DisabledRestApiTest < ActionController::IntegrationTest
4 4 fixtures :all
5 5
6 6 def setup
7 7 Setting.rest_api_enabled = '0'
8 8 Setting.login_required = '1'
9 9 end
10 10
11 11 def teardown
12 12 Setting.rest_api_enabled = '1'
13 13 Setting.login_required = '0'
14 14 end
15 15
16 16 # Using the NewsController because it's a simple API.
17 17 context "get /news with the API disabled" do
18 18
19 19 context "in :xml format" do
20 20 context "with a valid api token" do
21 21 setup do
22 22 @user = User.generate_with_protected!
23 23 @token = Token.generate!(:user => @user, :action => 'api')
24 24 get "/news.xml?key=#{@token.value}"
25 25 end
26 26
27 27 should_respond_with :unauthorized
28 28 should_respond_with_content_type :xml
29 29 should "not login as the user" do
30 30 assert_equal User.anonymous, User.current
31 31 end
32 32 end
33 33
34 34 context "with a valid HTTP authentication" do
35 35 setup do
36 36 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password')
37 37 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
38 38 get "/news.xml", nil, :authorization => @authorization
39 39 end
40 40
41 41 should_respond_with :unauthorized
42 42 should_respond_with_content_type :xml
43 43 should "not login as the user" do
44 44 assert_equal User.anonymous, User.current
45 45 end
46 46 end
47 47
48 48 context "with a valid HTTP authentication using the API token" do
49 49 setup do
50 50 @user = User.generate_with_protected!
51 51 @token = Token.generate!(:user => @user, :action => 'api')
52 52 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
53 53 get "/news.xml", nil, :authorization => @authorization
54 54 end
55 55
56 56 should_respond_with :unauthorized
57 57 should_respond_with_content_type :xml
58 58 should "not login as the user" do
59 59 assert_equal User.anonymous, User.current
60 60 end
61 61 end
62 62 end
63 63
64 64 context "in :json format" do
65 65 context "with a valid api token" do
66 66 setup do
67 67 @user = User.generate_with_protected!
68 68 @token = Token.generate!(:user => @user, :action => 'api')
69 69 get "/news.json?key=#{@token.value}"
70 70 end
71 71
72 72 should_respond_with :unauthorized
73 73 should_respond_with_content_type :json
74 74 should "not login as the user" do
75 75 assert_equal User.anonymous, User.current
76 76 end
77 77 end
78 78
79 79 context "with a valid HTTP authentication" do
80 80 setup do
81 81 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password')
82 82 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
83 83 get "/news.json", nil, :authorization => @authorization
84 84 end
85 85
86 86 should_respond_with :unauthorized
87 87 should_respond_with_content_type :json
88 88 should "not login as the user" do
89 89 assert_equal User.anonymous, User.current
90 90 end
91 91 end
92 92
93 93 context "with a valid HTTP authentication using the API token" do
94 94 setup do
95 95 @user = User.generate_with_protected!
96 96 @token = Token.generate!(:user => @user, :action => 'api')
97 97 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'DoesNotMatter')
98 98 get "/news.json", nil, :authorization => @authorization
99 99 end
100 100
101 101 should_respond_with :unauthorized
102 102 should_respond_with_content_type :json
103 103 should "not login as the user" do
104 104 assert_equal User.anonymous, User.current
105 105 end
106 106 end
107 107
108 108 end
109 109 end
110 110 end
@@ -1,102 +1,99
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2010 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 require "#{File.dirname(__FILE__)}/../test_helper"
18 require "#{File.dirname(__FILE__)}/../../test_helper"
19 19
20 class ProjectsApiTest < ActionController::IntegrationTest
20 class ApiTest::ProjectsTest < ActionController::IntegrationTest
21 21 fixtures :projects, :versions, :users, :roles, :members, :member_roles, :issues, :journals, :journal_details,
22 22 :trackers, :projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :boards, :messages,
23 23 :attachments, :custom_fields, :custom_values, :time_entries
24 24
25 25 def setup
26 26 Setting.rest_api_enabled = '1'
27 27 end
28 28
29 29 def test_index
30 30 get '/projects.xml'
31 31 assert_response :success
32 32 assert_equal 'application/xml', @response.content_type
33 33 end
34 34
35 35 def test_show
36 36 get '/projects/1.xml'
37 37 assert_response :success
38 38 assert_equal 'application/xml', @response.content_type
39 39 end
40 40
41 41 def test_create
42 42 attributes = {:name => 'API test', :identifier => 'api-test'}
43 43 assert_difference 'Project.count' do
44 44 post '/projects.xml', {:project => attributes}, :authorization => credentials('admin')
45 45 end
46
46 assert_response :created
47 assert_equal 'application/xml', @response.content_type
47 48 project = Project.first(:order => 'id DESC')
48 49 attributes.each do |attribute, value|
49 50 assert_equal value, project.send(attribute)
50 51 end
51
52 assert_response :created
53 assert_equal 'application/xml', @response.content_type
54 assert_tag 'project', :child => {:tag => 'id', :content => project.id.to_s}
55 52 end
56 53
57 54 def test_create_failure
58 55 attributes = {:name => 'API test'}
59 56 assert_no_difference 'Project.count' do
60 57 post '/projects.xml', {:project => attributes}, :authorization => credentials('admin')
61 58 end
62 59 assert_response :unprocessable_entity
63 60 assert_equal 'application/xml', @response.content_type
64 61 assert_tag :errors, :child => {:tag => 'error', :content => "Identifier can't be blank"}
65 62 end
66 63
67 64 def test_update
68 65 attributes = {:name => 'API update'}
69 66 assert_no_difference 'Project.count' do
70 67 put '/projects/1.xml', {:project => attributes}, :authorization => credentials('jsmith')
71 68 end
72 69 assert_response :ok
73 70 assert_equal 'application/xml', @response.content_type
74 71 project = Project.find(1)
75 72 attributes.each do |attribute, value|
76 73 assert_equal value, project.send(attribute)
77 74 end
78 75 end
79 76
80 77 def test_update_failure
81 78 attributes = {:name => ''}
82 79 assert_no_difference 'Project.count' do
83 80 put '/projects/1.xml', {:project => attributes}, :authorization => credentials('jsmith')
84 81 end
85 82 assert_response :unprocessable_entity
86 83 assert_equal 'application/xml', @response.content_type
87 84 assert_tag :errors, :child => {:tag => 'error', :content => "Name can't be blank"}
88 85 end
89 86
90 87 def test_destroy
91 88 assert_difference 'Project.count', -1 do
92 89 delete '/projects/2.xml', {}, :authorization => credentials('admin')
93 90 end
94 91 assert_response :ok
95 92 assert_equal 'application/xml', @response.content_type
96 93 assert_nil Project.find_by_id(2)
97 94 end
98 95
99 96 def credentials(user, password=nil)
100 97 ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)
101 98 end
102 99 end
@@ -1,184 +1,416
1 1 # redMine - project management software
2 2 # Copyright (C) 2006 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 ENV["RAILS_ENV"] = "test"
19 19 require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
20 20 require 'test_help'
21 21 require File.expand_path(File.dirname(__FILE__) + '/helper_testcase')
22 22 require File.join(RAILS_ROOT,'test', 'mocks', 'open_id_authentication_mock.rb')
23 23
24 24 require File.expand_path(File.dirname(__FILE__) + '/object_daddy_helpers')
25 25 include ObjectDaddyHelpers
26 26
27 27 class ActiveSupport::TestCase
28 28 # Transactional fixtures accelerate your tests by wrapping each test method
29 29 # in a transaction that's rolled back on completion. This ensures that the
30 30 # test database remains unchanged so your fixtures don't have to be reloaded
31 31 # between every test method. Fewer database queries means faster tests.
32 32 #
33 33 # Read Mike Clark's excellent walkthrough at
34 34 # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
35 35 #
36 36 # Every Active Record database supports transactions except MyISAM tables
37 37 # in MySQL. Turn off transactional fixtures in this case; however, if you
38 38 # don't care one way or the other, switching from MyISAM to InnoDB tables
39 39 # is recommended.
40 40 self.use_transactional_fixtures = true
41 41
42 42 # Instantiated fixtures are slow, but give you @david where otherwise you
43 43 # would need people(:david). If you don't want to migrate your existing
44 44 # test cases which use the @david style and don't mind the speed hit (each
45 45 # instantiated fixtures translates to a database query per test method),
46 46 # then set this back to true.
47 47 self.use_instantiated_fixtures = false
48 48
49 49 # Add more helper methods to be used by all tests here...
50 50
51 51 def log_user(login, password)
52 52 User.anonymous
53 53 get "/login"
54 54 assert_equal nil, session[:user_id]
55 55 assert_response :success
56 56 assert_template "account/login"
57 57 post "/login", :username => login, :password => password
58 58 assert_equal login, User.find(session[:user_id]).login
59 59 end
60 60
61 61 def uploaded_test_file(name, mime)
62 62 ActionController::TestUploadedFile.new(ActiveSupport::TestCase.fixture_path + "/files/#{name}", mime)
63 63 end
64 64
65 65 # Mock out a file
66 66 def self.mock_file
67 67 file = 'a_file.png'
68 68 file.stubs(:size).returns(32)
69 69 file.stubs(:original_filename).returns('a_file.png')
70 70 file.stubs(:content_type).returns('image/png')
71 71 file.stubs(:read).returns(false)
72 72 file
73 73 end
74 74
75 75 def mock_file
76 76 self.class.mock_file
77 77 end
78 78
79 79 # Use a temporary directory for attachment related tests
80 80 def set_tmp_attachments_directory
81 81 Dir.mkdir "#{RAILS_ROOT}/tmp/test" unless File.directory?("#{RAILS_ROOT}/tmp/test")
82 82 Dir.mkdir "#{RAILS_ROOT}/tmp/test/attachments" unless File.directory?("#{RAILS_ROOT}/tmp/test/attachments")
83 83 Attachment.storage_path = "#{RAILS_ROOT}/tmp/test/attachments"
84 84 end
85 85
86 86 def with_settings(options, &block)
87 87 saved_settings = options.keys.inject({}) {|h, k| h[k] = Setting[k].dup; h}
88 88 options.each {|k, v| Setting[k] = v}
89 89 yield
90 90 saved_settings.each {|k, v| Setting[k] = v}
91 91 end
92 92
93 93 def change_user_password(login, new_password)
94 94 user = User.first(:conditions => {:login => login})
95 95 user.password, user.password_confirmation = new_password, new_password
96 96 user.save!
97 97 end
98 98
99 99 def self.ldap_configured?
100 100 @test_ldap = Net::LDAP.new(:host => '127.0.0.1', :port => 389)
101 101 return @test_ldap.bind
102 102 rescue Exception => e
103 103 # LDAP is not listening
104 104 return nil
105 105 end
106 106
107 107 # Returns the path to the test +vendor+ repository
108 108 def self.repository_path(vendor)
109 109 File.join(RAILS_ROOT.gsub(%r{config\/\.\.}, ''), "/tmp/test/#{vendor.downcase}_repository")
110 110 end
111 111
112 112 # Returns true if the +vendor+ test repository is configured
113 113 def self.repository_configured?(vendor)
114 114 File.directory?(repository_path(vendor))
115 115 end
116 116
117 117 # Shoulda macros
118 118 def self.should_render_404
119 119 should_respond_with :not_found
120 120 should_render_template 'common/404'
121 121 end
122 122
123 123 def self.should_have_before_filter(expected_method, options = {})
124 124 should_have_filter('before', expected_method, options)
125 125 end
126 126
127 127 def self.should_have_after_filter(expected_method, options = {})
128 128 should_have_filter('after', expected_method, options)
129 129 end
130 130
131 131 def self.should_have_filter(filter_type, expected_method, options)
132 132 description = "have #{filter_type}_filter :#{expected_method}"
133 133 description << " with #{options.inspect}" unless options.empty?
134 134
135 135 should description do
136 136 klass = "action_controller/filters/#{filter_type}_filter".classify.constantize
137 137 expected = klass.new(:filter, expected_method.to_sym, options)
138 138 assert_equal 1, @controller.class.filter_chain.select { |filter|
139 139 filter.method == expected.method && filter.kind == expected.kind &&
140 140 filter.options == expected.options && filter.class == expected.class
141 141 }.size
142 142 end
143 143 end
144 144
145 145 def self.should_show_the_old_and_new_values_for(prop_key, model, &block)
146 146 context "" do
147 147 setup do
148 148 if block_given?
149 149 instance_eval &block
150 150 else
151 151 @old_value = model.generate!
152 152 @new_value = model.generate!
153 153 end
154 154 end
155 155
156 156 should "use the new value's name" do
157 157 @detail = JournalDetail.generate!(:property => 'attr',
158 158 :old_value => @old_value.id,
159 159 :value => @new_value.id,
160 160 :prop_key => prop_key)
161 161
162 162 assert_match @new_value.name, show_detail(@detail, true)
163 163 end
164 164
165 165 should "use the old value's name" do
166 166 @detail = JournalDetail.generate!(:property => 'attr',
167 167 :old_value => @old_value.id,
168 168 :value => @new_value.id,
169 169 :prop_key => prop_key)
170 170
171 171 assert_match @old_value.name, show_detail(@detail, true)
172 172 end
173 173 end
174 174 end
175 175
176 176 def self.should_create_a_new_user(&block)
177 177 should "create a new user" do
178 178 user = instance_eval &block
179 179 assert user
180 180 assert_kind_of User, user
181 181 assert !user.new_record?
182 182 end
183 183 end
184
185 # Test that a request allows the three types of API authentication
186 #
187 # * HTTP Basic with username and password
188 # * HTTP Basic with an api key for the username
189 # * Key based with the key=X parameter
190 #
191 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
192 # @param [String] url the request url
193 # @param [optional, Hash] parameters additional request parameters
194 # @param [optional, Hash] options additional options
195 # @option options [Symbol] :success_code Successful response code (:success)
196 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
197 def self.should_allow_api_authentication(http_method, url, parameters={}, options={})
198 should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters, options)
199 should_allow_http_basic_auth_with_key(http_method, url, parameters, options)
200 should_allow_key_based_auth(http_method, url, parameters, options)
201 end
202
203 # Test that a request allows the username and password for HTTP BASIC
204 #
205 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
206 # @param [String] url the request url
207 # @param [optional, Hash] parameters additional request parameters
208 # @param [optional, Hash] options additional options
209 # @option options [Symbol] :success_code Successful response code (:success)
210 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
211 def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={}, options={})
212 success_code = options[:success_code] || :success
213 failure_code = options[:failure_code] || :unauthorized
214
215 context "should allow http basic auth using a username and password for #{http_method} #{url}" do
216 context "with a valid HTTP authentication" do
217 setup do
218 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password', :admin => true) # Admin so they can access the project
219 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
220 send(http_method, url, parameters, {:authorization => @authorization})
221 end
222
223 should_respond_with success_code
224 should_respond_with_content_type_based_on_url(url)
225 should "login as the user" do
226 assert_equal @user, User.current
227 end
228 end
229
230 context "with an invalid HTTP authentication" do
231 setup do
232 @user = User.generate_with_protected!
233 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
234 send(http_method, url, parameters, {:authorization => @authorization})
235 end
236
237 should_respond_with failure_code
238 should_respond_with_content_type_based_on_url(url)
239 should "not login as the user" do
240 assert_equal User.anonymous, User.current
241 end
242 end
243
244 context "without credentials" do
245 setup do
246 send(http_method, url, parameters, {:authorization => ''})
247 end
248
249 should_respond_with failure_code
250 should_respond_with_content_type_based_on_url(url)
251 should "include_www_authenticate_header" do
252 assert @controller.response.headers.has_key?('WWW-Authenticate')
253 end
254 end
255 end
256
257 end
258
259 # Test that a request allows the API key with HTTP BASIC
260 #
261 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
262 # @param [String] url the request url
263 # @param [optional, Hash] parameters additional request parameters
264 # @param [optional, Hash] options additional options
265 # @option options [Symbol] :success_code Successful response code (:success)
266 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
267 def self.should_allow_http_basic_auth_with_key(http_method, url, parameters={}, options={})
268 success_code = options[:success_code] || :success
269 failure_code = options[:failure_code] || :unauthorized
270
271 context "should allow http basic auth with a key for #{http_method} #{url}" do
272 context "with a valid HTTP authentication using the API token" do
273 setup do
274 @user = User.generate_with_protected!(:admin => true)
275 @token = Token.generate!(:user => @user, :action => 'api')
276 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
277 send(http_method, url, parameters, {:authorization => @authorization})
278 end
279
280 should_respond_with success_code
281 should_respond_with_content_type_based_on_url(url)
282 should_be_a_valid_response_string_based_on_url(url)
283 should "login as the user" do
284 assert_equal @user, User.current
285 end
286 end
287
288 context "with an invalid HTTP authentication" do
289 setup do
290 @user = User.generate_with_protected!
291 @token = Token.generate!(:user => @user, :action => 'feeds')
292 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@token.value, 'X')
293 send(http_method, url, parameters, {:authorization => @authorization})
294 end
295
296 should_respond_with failure_code
297 should_respond_with_content_type_based_on_url(url)
298 should "not login as the user" do
299 assert_equal User.anonymous, User.current
300 end
301 end
302 end
303 end
304
305 # Test that a request allows full key authentication
306 #
307 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
308 # @param [String] url the request url, without the key=ZXY parameter
309 # @param [optional, Hash] parameters additional request parameters
310 # @param [optional, Hash] options additional options
311 # @option options [Symbol] :success_code Successful response code (:success)
312 # @option options [Symbol] :failure_code Failure response code (:unauthorized)
313 def self.should_allow_key_based_auth(http_method, url, parameters={}, options={})
314 success_code = options[:success_code] || :success
315 failure_code = options[:failure_code] || :unauthorized
316
317 context "should allow key based auth using key=X for #{http_method} #{url}" do
318 context "with a valid api token" do
319 setup do
320 @user = User.generate_with_protected!(:admin => true)
321 @token = Token.generate!(:user => @user, :action => 'api')
322 # Simple url parse to add on ?key= or &key=
323 request_url = if url.match(/\?/)
324 url + "&key=#{@token.value}"
325 else
326 url + "?key=#{@token.value}"
327 end
328 send(http_method, request_url, parameters)
329 end
330
331 should_respond_with success_code
332 should_respond_with_content_type_based_on_url(url)
333 should_be_a_valid_response_string_based_on_url(url)
334 should "login as the user" do
335 assert_equal @user, User.current
336 end
337 end
338
339 context "with an invalid api token" do
340 setup do
341 @user = User.generate_with_protected!
342 @token = Token.generate!(:user => @user, :action => 'feeds')
343 # Simple url parse to add on ?key= or &key=
344 request_url = if url.match(/\?/)
345 url + "&key=#{@token.value}"
346 else
347 url + "?key=#{@token.value}"
348 end
349 send(http_method, request_url, parameters)
350 end
351
352 should_respond_with failure_code
353 should_respond_with_content_type_based_on_url(url)
354 should "not login as the user" do
355 assert_equal User.anonymous, User.current
356 end
357 end
358 end
359
360 end
361
362 # Uses should_respond_with_content_type based on what's in the url:
363 #
364 # '/project/issues.xml' => should_respond_with_content_type :xml
365 # '/project/issues.json' => should_respond_with_content_type :json
366 #
367 # @param [String] url Request
368 def self.should_respond_with_content_type_based_on_url(url)
369 case
370 when url.match(/xml/i)
371 should_respond_with_content_type :xml
372 when url.match(/json/i)
373 should_respond_with_content_type :json
374 else
375 raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
376 end
377
378 end
379
380 # Uses the url to assert which format the response should be in
381 #
382 # '/project/issues.xml' => should_be_a_valid_xml_string
383 # '/project/issues.json' => should_be_a_valid_json_string
384 #
385 # @param [String] url Request
386 def self.should_be_a_valid_response_string_based_on_url(url)
387 case
388 when url.match(/xml/i)
389 should_be_a_valid_xml_string
390 when url.match(/json/i)
391 should_be_a_valid_json_string
392 else
393 raise "Unknown content type for should_be_a_valid_response_based_on_url: #{url}"
394 end
395
396 end
397
398 # Checks that the response is a valid JSON string
399 def self.should_be_a_valid_json_string
400 should "be a valid JSON string (or empty)" do
401 assert (response.body.blank? || ActiveSupport::JSON.decode(response.body))
402 end
403 end
404
405 # Checks that the response is a valid XML string
406 def self.should_be_a_valid_xml_string
407 should "be a valid XML string" do
408 assert REXML::Document.new(response.body)
409 end
410 end
411
412 end
413
414 # Simple module to "namespace" all of the API tests
415 module ApiTest
184 416 end
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now