##// END OF EJS Templates
Pass parameters with :params in controller tests....
Jean-Philippe Lang -
r15282:c364e6ee9b2e
parent child
Show More
@@ -1,596 +1,642
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 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 UsersControllerTest < Redmine::ControllerTest
20 class UsersControllerTest < Redmine::ControllerTest
21 include Redmine::I18n
21 include Redmine::I18n
22
22
23 fixtures :users, :email_addresses, :projects, :members, :member_roles, :roles,
23 fixtures :users, :email_addresses, :projects, :members, :member_roles, :roles,
24 :custom_fields, :custom_values, :groups_users,
24 :custom_fields, :custom_values, :groups_users,
25 :auth_sources,
25 :auth_sources,
26 :enabled_modules,
26 :enabled_modules,
27 :issues, :issue_statuses,
27 :issues, :issue_statuses,
28 :trackers
28 :trackers
29
29
30 def setup
30 def setup
31 User.current = nil
31 User.current = nil
32 @request.session[:user_id] = 1 # admin
32 @request.session[:user_id] = 1 # admin
33 end
33 end
34
34
35 def test_index
35 def test_index
36 get :index
36 get :index
37 assert_response :success
37 assert_response :success
38 assert_template 'index'
38 assert_template 'index'
39 assert_not_nil assigns(:users)
39 assert_not_nil assigns(:users)
40 # active users only
40 # active users only
41 assert_nil assigns(:users).detect {|u| !u.active?}
41 assert_nil assigns(:users).detect {|u| !u.active?}
42 end
42 end
43
43
44 def test_index_with_status_filter
44 def test_index_with_status_filter
45 get :index, :status => 3
45 get :index, :params => {:status => 3}
46 assert_response :success
46 assert_response :success
47 assert_template 'index'
47 assert_template 'index'
48 assert_not_nil assigns(:users)
48 assert_not_nil assigns(:users)
49 assert_equal [3], assigns(:users).map(&:status).uniq
49 assert_equal [3], assigns(:users).map(&:status).uniq
50 end
50 end
51
51
52 def test_index_with_name_filter
52 def test_index_with_name_filter
53 get :index, :name => 'john'
53 get :index, :params => {:name => 'john'}
54 assert_response :success
54 assert_response :success
55 assert_template 'index'
55 assert_template 'index'
56 users = assigns(:users)
56 users = assigns(:users)
57 assert_not_nil users
57 assert_not_nil users
58 assert_equal 1, users.size
58 assert_equal 1, users.size
59 assert_equal 'John', users.first.firstname
59 assert_equal 'John', users.first.firstname
60 end
60 end
61
61
62 def test_index_with_group_filter
62 def test_index_with_group_filter
63 get :index, :group_id => '10'
63 get :index, :params => {:group_id => '10'}
64 assert_response :success
64 assert_response :success
65 assert_template 'index'
65 assert_template 'index'
66 users = assigns(:users)
66 users = assigns(:users)
67 assert users.any?
67 assert users.any?
68 assert_equal([], (users - Group.find(10).users))
68 assert_equal([], (users - Group.find(10).users))
69 assert_select 'select[name=group_id]' do
69 assert_select 'select[name=group_id]' do
70 assert_select 'option[value="10"][selected=selected]'
70 assert_select 'option[value="10"][selected=selected]'
71 end
71 end
72 end
72 end
73
73
74 def test_show
74 def test_show
75 @request.session[:user_id] = nil
75 @request.session[:user_id] = nil
76 get :show, :id => 2
76 get :show, :params => {:id => 2}
77 assert_response :success
77 assert_response :success
78 assert_template 'show'
78 assert_template 'show'
79 assert_not_nil assigns(:user)
79 assert_not_nil assigns(:user)
80
80
81 assert_select 'li', :text => /Phone number/
81 assert_select 'li', :text => /Phone number/
82 end
82 end
83
83
84 def test_show_should_not_display_hidden_custom_fields
84 def test_show_should_not_display_hidden_custom_fields
85 @request.session[:user_id] = nil
85 @request.session[:user_id] = nil
86 UserCustomField.find_by_name('Phone number').update_attribute :visible, false
86 UserCustomField.find_by_name('Phone number').update_attribute :visible, false
87 get :show, :id => 2
87 get :show, :params => {:id => 2}
88 assert_response :success
88 assert_response :success
89 assert_template 'show'
89 assert_template 'show'
90 assert_not_nil assigns(:user)
90 assert_not_nil assigns(:user)
91
91
92 assert_select 'li', :text => /Phone number/, :count => 0
92 assert_select 'li', :text => /Phone number/, :count => 0
93 end
93 end
94
94
95 def test_show_should_not_fail_when_custom_values_are_nil
95 def test_show_should_not_fail_when_custom_values_are_nil
96 user = User.find(2)
96 user = User.find(2)
97
97
98 # Create a custom field to illustrate the issue
98 # Create a custom field to illustrate the issue
99 custom_field = CustomField.create!(:name => 'Testing', :field_format => 'text')
99 custom_field = CustomField.create!(:name => 'Testing', :field_format => 'text')
100 custom_value = user.custom_values.build(:custom_field => custom_field).save!
100 custom_value = user.custom_values.build(:custom_field => custom_field).save!
101
101
102 get :show, :id => 2
102 get :show, :params => {:id => 2}
103 assert_response :success
103 assert_response :success
104 end
104 end
105
105
106 def test_show_inactive
106 def test_show_inactive
107 @request.session[:user_id] = nil
107 @request.session[:user_id] = nil
108 get :show, :id => 5
108 get :show, :params => {:id => 5}
109 assert_response 404
109 assert_response 404
110 end
110 end
111
111
112 def test_show_inactive_by_admin
112 def test_show_inactive_by_admin
113 @request.session[:user_id] = 1
113 @request.session[:user_id] = 1
114 get :show, :id => 5
114 get :show, :params => {:id => 5}
115 assert_response 200
115 assert_response 200
116 assert_not_nil assigns(:user)
116 assert_not_nil assigns(:user)
117 end
117 end
118
118
119 def test_show_user_who_is_not_visible_should_return_404
119 def test_show_user_who_is_not_visible_should_return_404
120 Role.anonymous.update! :users_visibility => 'members_of_visible_projects'
120 Role.anonymous.update! :users_visibility => 'members_of_visible_projects'
121 user = User.generate!
121 user = User.generate!
122
122
123 @request.session[:user_id] = nil
123 @request.session[:user_id] = nil
124 get :show, :id => user.id
124 get :show, :params => {:id => user.id}
125 assert_response 404
125 assert_response 404
126 end
126 end
127
127
128 def test_show_displays_memberships_based_on_project_visibility
128 def test_show_displays_memberships_based_on_project_visibility
129 @request.session[:user_id] = 1
129 @request.session[:user_id] = 1
130 get :show, :id => 2
130 get :show, :params => {:id => 2}
131 assert_response :success
131 assert_response :success
132 memberships = assigns(:memberships)
132 memberships = assigns(:memberships)
133 assert_not_nil memberships
133 assert_not_nil memberships
134 project_ids = memberships.map(&:project_id)
134 project_ids = memberships.map(&:project_id)
135 assert project_ids.include?(2) #private project admin can see
135 assert project_ids.include?(2) #private project admin can see
136 end
136 end
137
137
138 def test_show_current_should_require_authentication
138 def test_show_current_should_require_authentication
139 @request.session[:user_id] = nil
139 @request.session[:user_id] = nil
140 get :show, :id => 'current'
140 get :show, :params => {:id => 'current'}
141 assert_response 302
141 assert_response 302
142 end
142 end
143
143
144 def test_show_current
144 def test_show_current
145 @request.session[:user_id] = 2
145 @request.session[:user_id] = 2
146 get :show, :id => 'current'
146 get :show, :params => {:id => 'current'}
147 assert_response :success
147 assert_response :success
148 assert_template 'show'
148 assert_template 'show'
149 assert_equal User.find(2), assigns(:user)
149 assert_equal User.find(2), assigns(:user)
150 end
150 end
151
151
152 def test_new
152 def test_new
153 get :new
153 get :new
154 assert_response :success
154 assert_response :success
155 assert_template :new
155 assert_template :new
156 assert assigns(:user)
156 assert assigns(:user)
157 end
157 end
158
158
159 def test_create
159 def test_create
160 Setting.bcc_recipients = '1'
160 Setting.bcc_recipients = '1'
161
161
162 assert_difference 'User.count' do
162 assert_difference 'User.count' do
163 assert_difference 'ActionMailer::Base.deliveries.size' do
163 assert_difference 'ActionMailer::Base.deliveries.size' do
164 post :create,
164 post :create, :params => {
165 :user => {
165 :user => {
166 :firstname => 'John',
166 :firstname => 'John',
167 :lastname => 'Doe',
167 :lastname => 'Doe',
168 :login => 'jdoe',
168 :login => 'jdoe',
169 :password => 'secret123',
169 :password => 'secret123',
170 :password_confirmation => 'secret123',
170 :password_confirmation => 'secret123',
171 :mail => 'jdoe@gmail.com',
171 :mail => 'jdoe@gmail.com',
172 :mail_notification => 'none'
172 :mail_notification => 'none'
173 },
173 },
174 :send_information => '1'
174 :send_information => '1'
175 }
175 end
176 end
176 end
177 end
177
178
178 user = User.order('id DESC').first
179 user = User.order('id DESC').first
179 assert_redirected_to :controller => 'users', :action => 'edit', :id => user.id
180 assert_redirected_to :controller => 'users', :action => 'edit', :id => user.id
180
181
181 assert_equal 'John', user.firstname
182 assert_equal 'John', user.firstname
182 assert_equal 'Doe', user.lastname
183 assert_equal 'Doe', user.lastname
183 assert_equal 'jdoe', user.login
184 assert_equal 'jdoe', user.login
184 assert_equal 'jdoe@gmail.com', user.mail
185 assert_equal 'jdoe@gmail.com', user.mail
185 assert_equal 'none', user.mail_notification
186 assert_equal 'none', user.mail_notification
186 assert user.check_password?('secret123')
187 assert user.check_password?('secret123')
187
188
188 mail = ActionMailer::Base.deliveries.last
189 mail = ActionMailer::Base.deliveries.last
189 assert_not_nil mail
190 assert_not_nil mail
190 assert_equal [user.mail], mail.bcc
191 assert_equal [user.mail], mail.bcc
191 assert_mail_body_match 'secret', mail
192 assert_mail_body_match 'secret', mail
192 end
193 end
193
194
194 def test_create_with_preferences
195 def test_create_with_preferences
195 assert_difference 'User.count' do
196 assert_difference 'User.count' do
196 post :create,
197 post :create, :params => {
197 :user => {
198 :user => {
198 :firstname => 'John',
199 :firstname => 'John',
199 :lastname => 'Doe',
200 :lastname => 'Doe',
200 :login => 'jdoe',
201 :login => 'jdoe',
201 :password => 'secret123',
202 :password => 'secret123',
202 :password_confirmation => 'secret123',
203 :password_confirmation => 'secret123',
203 :mail => 'jdoe@gmail.com',
204 :mail => 'jdoe@gmail.com',
204 :mail_notification => 'none'
205 :mail_notification => 'none'
205 },
206 },
206 :pref => {
207 :pref => {
207 'hide_mail' => '1',
208 'hide_mail' => '1',
208 'time_zone' => 'Paris',
209 'time_zone' => 'Paris',
209 'comments_sorting' => 'desc',
210 'comments_sorting' => 'desc',
210 'warn_on_leaving_unsaved' => '0'
211 'warn_on_leaving_unsaved' => '0'
211 }
212 }
213 }
212 end
214 end
213 user = User.order('id DESC').first
215 user = User.order('id DESC').first
214 assert_equal 'jdoe', user.login
216 assert_equal 'jdoe', user.login
215 assert_equal true, user.pref.hide_mail
217 assert_equal true, user.pref.hide_mail
216 assert_equal 'Paris', user.pref.time_zone
218 assert_equal 'Paris', user.pref.time_zone
217 assert_equal 'desc', user.pref[:comments_sorting]
219 assert_equal 'desc', user.pref[:comments_sorting]
218 assert_equal '0', user.pref[:warn_on_leaving_unsaved]
220 assert_equal '0', user.pref[:warn_on_leaving_unsaved]
219 end
221 end
220
222
221 def test_create_with_generate_password_should_email_the_password
223 def test_create_with_generate_password_should_email_the_password
222 assert_difference 'User.count' do
224 assert_difference 'User.count' do
223 post :create, :user => {
225 post :create, :params => {
226 :user => {
224 :login => 'randompass',
227 :login => 'randompass',
225 :firstname => 'Random',
228 :firstname => 'Random',
226 :lastname => 'Pass',
229 :lastname => 'Pass',
227 :mail => 'randompass@example.net',
230 :mail => 'randompass@example.net',
228 :language => 'en',
231 :language => 'en',
229 :generate_password => '1',
232 :generate_password => '1',
230 :password => '',
233 :password => '',
231 :password_confirmation => ''
234 :password_confirmation => ''
232 }, :send_information => 1
235 },
236 :send_information => 1
237 }
233 end
238 end
234 user = User.order('id DESC').first
239 user = User.order('id DESC').first
235 assert_equal 'randompass', user.login
240 assert_equal 'randompass', user.login
236
241
237 mail = ActionMailer::Base.deliveries.last
242 mail = ActionMailer::Base.deliveries.last
238 assert_not_nil mail
243 assert_not_nil mail
239 m = mail_body(mail).match(/Password: ([a-zA-Z0-9]+)/)
244 m = mail_body(mail).match(/Password: ([a-zA-Z0-9]+)/)
240 assert m
245 assert m
241 password = m[1]
246 password = m[1]
242 assert user.check_password?(password)
247 assert user.check_password?(password)
243 end
248 end
244
249
245 def test_create_and_continue
250 def test_create_and_continue
246 post :create, :user => {
251 post :create, :params => {
252 :user => {
247 :login => 'randompass',
253 :login => 'randompass',
248 :firstname => 'Random',
254 :firstname => 'Random',
249 :lastname => 'Pass',
255 :lastname => 'Pass',
250 :mail => 'randompass@example.net',
256 :mail => 'randompass@example.net',
251 :generate_password => '1'
257 :generate_password => '1'
252 }, :continue => '1'
258 },
259 :continue => '1'
260 }
253 assert_redirected_to '/users/new?user%5Bgenerate_password%5D=1'
261 assert_redirected_to '/users/new?user%5Bgenerate_password%5D=1'
254 end
262 end
255
263
256 def test_create_with_failure
264 def test_create_with_failure
257 assert_no_difference 'User.count' do
265 assert_no_difference 'User.count' do
258 post :create, :user => {}
266 post :create, :params => {:user => {}}
259 end
267 end
260 assert_response :success
268 assert_response :success
261 assert_template 'new'
269 assert_template 'new'
262 end
270 end
263
271
264 def test_create_with_failure_sould_preserve_preference
272 def test_create_with_failure_sould_preserve_preference
265 assert_no_difference 'User.count' do
273 assert_no_difference 'User.count' do
266 post :create,
274 post :create, :params => {
267 :user => {},
275 :user => {},
268 :pref => {
276 :pref => {
269 'no_self_notified' => '1',
277 'no_self_notified' => '1',
270 'hide_mail' => '1',
278 'hide_mail' => '1',
271 'time_zone' => 'Paris',
279 'time_zone' => 'Paris',
272 'comments_sorting' => 'desc',
280 'comments_sorting' => 'desc',
273 'warn_on_leaving_unsaved' => '0'
281 'warn_on_leaving_unsaved' => '0'
274 }
282 }
283 }
275 end
284 end
276 assert_response :success
285 assert_response :success
277 assert_template 'new'
286 assert_template 'new'
278
287
279 assert_select 'select#pref_time_zone option[selected=selected]', :text => /Paris/
288 assert_select 'select#pref_time_zone option[selected=selected]', :text => /Paris/
280 assert_select 'input#pref_no_self_notified[value="1"][checked=checked]'
289 assert_select 'input#pref_no_self_notified[value="1"][checked=checked]'
281 end
290 end
282
291
283 def test_create_admin_should_send_security_notification
292 def test_create_admin_should_send_security_notification
284 ActionMailer::Base.deliveries.clear
293 ActionMailer::Base.deliveries.clear
285 post :create,
294 post :create, :params => {
286 :user => {
295 :user => {
287 :firstname => 'Edgar',
296 :firstname => 'Edgar',
288 :lastname => 'Schmoe',
297 :lastname => 'Schmoe',
289 :login => 'eschmoe',
298 :login => 'eschmoe',
290 :password => 'secret123',
299 :password => 'secret123',
291 :password_confirmation => 'secret123',
300 :password_confirmation => 'secret123',
292 :mail => 'eschmoe@example.foo',
301 :mail => 'eschmoe@example.foo',
293 :admin => '1'
302 :admin => '1'
294 }
303 }
304 }
295
305
296 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
306 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
297 assert_mail_body_match '0.0.0.0', mail
307 assert_mail_body_match '0.0.0.0', mail
298 assert_mail_body_match I18n.t(:mail_body_security_notification_add, field: I18n.t(:field_admin), value: 'eschmoe'), mail
308 assert_mail_body_match I18n.t(:mail_body_security_notification_add, field: I18n.t(:field_admin), value: 'eschmoe'), mail
299 assert_select_email do
309 assert_select_email do
300 assert_select 'a[href^=?]', 'http://localhost:3000/users', :text => 'Users'
310 assert_select 'a[href^=?]', 'http://localhost:3000/users', :text => 'Users'
301 end
311 end
302
312
303 # All admins should receive this
313 # All admins should receive this
304 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
314 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
305 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
315 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
306 end
316 end
307 end
317 end
308
318
309 def test_create_non_admin_should_not_send_security_notification
319 def test_create_non_admin_should_not_send_security_notification
310 ActionMailer::Base.deliveries.clear
320 ActionMailer::Base.deliveries.clear
311 post :create,
321 post :create, :params => {
312 :user => {
322 :user => {
313 :firstname => 'Edgar',
323 :firstname => 'Edgar',
314 :lastname => 'Schmoe',
324 :lastname => 'Schmoe',
315 :login => 'eschmoe',
325 :login => 'eschmoe',
316 :password => 'secret123',
326 :password => 'secret123',
317 :password_confirmation => 'secret123',
327 :password_confirmation => 'secret123',
318 :mail => 'eschmoe@example.foo',
328 :mail => 'eschmoe@example.foo',
319 :admin => '0'
329 :admin => '0'
320 }
330 }
331 }
321 assert_nil ActionMailer::Base.deliveries.last
332 assert_nil ActionMailer::Base.deliveries.last
322 end
333 end
323
334
324
335
325 def test_edit
336 def test_edit
326 get :edit, :id => 2
337 get :edit, :params => {:id => 2}
327 assert_response :success
338 assert_response :success
328 assert_template 'edit'
339 assert_template 'edit'
329 assert_equal User.find(2), assigns(:user)
340 assert_equal User.find(2), assigns(:user)
330 end
341 end
331
342
332 def test_edit_registered_user
343 def test_edit_registered_user
333 assert User.find(2).register!
344 assert User.find(2).register!
334
345
335 get :edit, :id => 2
346 get :edit, :params => {:id => 2}
336 assert_response :success
347 assert_response :success
337 assert_select 'a', :text => 'Activate'
348 assert_select 'a', :text => 'Activate'
338 end
349 end
339
350
340 def test_update
351 def test_update
341 ActionMailer::Base.deliveries.clear
352 ActionMailer::Base.deliveries.clear
342 put :update, :id => 2,
353 put :update, :params => {
354 :id => 2,
343 :user => {:firstname => 'Changed', :mail_notification => 'only_assigned'},
355 :user => {:firstname => 'Changed', :mail_notification => 'only_assigned'},
344 :pref => {:hide_mail => '1', :comments_sorting => 'desc'}
356 :pref => {:hide_mail => '1', :comments_sorting => 'desc'}
357 }
345 user = User.find(2)
358 user = User.find(2)
346 assert_equal 'Changed', user.firstname
359 assert_equal 'Changed', user.firstname
347 assert_equal 'only_assigned', user.mail_notification
360 assert_equal 'only_assigned', user.mail_notification
348 assert_equal true, user.pref[:hide_mail]
361 assert_equal true, user.pref[:hide_mail]
349 assert_equal 'desc', user.pref[:comments_sorting]
362 assert_equal 'desc', user.pref[:comments_sorting]
350 assert ActionMailer::Base.deliveries.empty?
363 assert ActionMailer::Base.deliveries.empty?
351 end
364 end
352
365
353 def test_update_with_failure
366 def test_update_with_failure
354 assert_no_difference 'User.count' do
367 assert_no_difference 'User.count' do
355 put :update, :id => 2, :user => {:firstname => ''}
368 put :update, :params => {
369 :id => 2,
370 :user => {:firstname => ''}
371 }
356 end
372 end
357 assert_response :success
373 assert_response :success
358 assert_template 'edit'
374 assert_template 'edit'
359 end
375 end
360
376
361 def test_update_with_group_ids_should_assign_groups
377 def test_update_with_group_ids_should_assign_groups
362 put :update, :id => 2, :user => {:group_ids => ['10']}
378 put :update, :params => {
379 :id => 2,
380 :user => {:group_ids => ['10']}
381 }
363 user = User.find(2)
382 user = User.find(2)
364 assert_equal [10], user.group_ids
383 assert_equal [10], user.group_ids
365 end
384 end
366
385
367 def test_update_with_activation_should_send_a_notification
386 def test_update_with_activation_should_send_a_notification
368 u = User.new(:firstname => 'Foo', :lastname => 'Bar', :mail => 'foo.bar@somenet.foo', :language => 'fr')
387 u = User.new(:firstname => 'Foo', :lastname => 'Bar', :mail => 'foo.bar@somenet.foo', :language => 'fr')
369 u.login = 'foo'
388 u.login = 'foo'
370 u.status = User::STATUS_REGISTERED
389 u.status = User::STATUS_REGISTERED
371 u.save!
390 u.save!
372 ActionMailer::Base.deliveries.clear
391 ActionMailer::Base.deliveries.clear
373 Setting.bcc_recipients = '1'
392 Setting.bcc_recipients = '1'
374
393
375 put :update, :id => u.id, :user => {:status => User::STATUS_ACTIVE}
394 put :update, :params => {
395 :id => u.id,
396 :user => {:status => User::STATUS_ACTIVE}
397 }
376 assert u.reload.active?
398 assert u.reload.active?
377 mail = ActionMailer::Base.deliveries.last
399 mail = ActionMailer::Base.deliveries.last
378 assert_not_nil mail
400 assert_not_nil mail
379 assert_equal ['foo.bar@somenet.foo'], mail.bcc
401 assert_equal ['foo.bar@somenet.foo'], mail.bcc
380 assert_mail_body_match ll('fr', :notice_account_activated), mail
402 assert_mail_body_match ll('fr', :notice_account_activated), mail
381 end
403 end
382
404
383 def test_update_with_password_change_should_send_a_notification
405 def test_update_with_password_change_should_send_a_notification
384 ActionMailer::Base.deliveries.clear
406 ActionMailer::Base.deliveries.clear
385 Setting.bcc_recipients = '1'
407 Setting.bcc_recipients = '1'
386
408
387 put :update, :id => 2, :user => {:password => 'newpass123', :password_confirmation => 'newpass123'}, :send_information => '1'
409 put :update, :params => {
410 :id => 2,
411 :user => {:password => 'newpass123', :password_confirmation => 'newpass123'},
412 :send_information => '1'
413 }
388 u = User.find(2)
414 u = User.find(2)
389 assert u.check_password?('newpass123')
415 assert u.check_password?('newpass123')
390
416
391 mail = ActionMailer::Base.deliveries.last
417 mail = ActionMailer::Base.deliveries.last
392 assert_not_nil mail
418 assert_not_nil mail
393 assert_equal [u.mail], mail.bcc
419 assert_equal [u.mail], mail.bcc
394 assert_mail_body_match 'newpass123', mail
420 assert_mail_body_match 'newpass123', mail
395 end
421 end
396
422
397 def test_update_with_generate_password_should_email_the_password
423 def test_update_with_generate_password_should_email_the_password
398 ActionMailer::Base.deliveries.clear
424 ActionMailer::Base.deliveries.clear
399 Setting.bcc_recipients = '1'
425 Setting.bcc_recipients = '1'
400
426
401 put :update, :id => 2, :user => {
427 put :update, :params => {
428 :id => 2,
429 :user => {
402 :generate_password => '1',
430 :generate_password => '1',
403 :password => '',
431 :password => '',
404 :password_confirmation => ''
432 :password_confirmation => ''
405 }, :send_information => '1'
433 },
434 :send_information => '1'
435 }
406
436
407 mail = ActionMailer::Base.deliveries.last
437 mail = ActionMailer::Base.deliveries.last
408 assert_not_nil mail
438 assert_not_nil mail
409 m = mail_body(mail).match(/Password: ([a-zA-Z0-9]+)/)
439 m = mail_body(mail).match(/Password: ([a-zA-Z0-9]+)/)
410 assert m
440 assert m
411 password = m[1]
441 password = m[1]
412 assert User.find(2).check_password?(password)
442 assert User.find(2).check_password?(password)
413 end
443 end
414
444
415 def test_update_without_generate_password_should_not_change_password
445 def test_update_without_generate_password_should_not_change_password
416 put :update, :id => 2, :user => {
446 put :update, :params => {
447 :id => 2, :user => {
417 :firstname => 'changed',
448 :firstname => 'changed',
418 :generate_password => '0',
449 :generate_password => '0',
419 :password => '',
450 :password => '',
420 :password_confirmation => ''
451 :password_confirmation => ''
421 }, :send_information => '1'
452 },
453 :send_information => '1'
454 }
422
455
423 user = User.find(2)
456 user = User.find(2)
424 assert_equal 'changed', user.firstname
457 assert_equal 'changed', user.firstname
425 assert user.check_password?('jsmith')
458 assert user.check_password?('jsmith')
426 end
459 end
427
460
428 def test_update_user_switchin_from_auth_source_to_password_authentication
461 def test_update_user_switchin_from_auth_source_to_password_authentication
429 # Configure as auth source
462 # Configure as auth source
430 u = User.find(2)
463 u = User.find(2)
431 u.auth_source = AuthSource.find(1)
464 u.auth_source = AuthSource.find(1)
432 u.save!
465 u.save!
433
466
434 put :update, :id => u.id, :user => {:auth_source_id => '', :password => 'newpass123', :password_confirmation => 'newpass123'}
467 put :update, :params => {
468 :id => u.id,
469 :user => {:auth_source_id => '', :password => 'newpass123', :password_confirmation => 'newpass123'}
470 }
435
471
436 assert_equal nil, u.reload.auth_source
472 assert_equal nil, u.reload.auth_source
437 assert u.check_password?('newpass123')
473 assert u.check_password?('newpass123')
438 end
474 end
439
475
440 def test_update_notified_project
476 def test_update_notified_project
441 get :edit, :id => 2
477 get :edit, :params => {:id => 2}
442 assert_response :success
478 assert_response :success
443 assert_template 'edit'
479 assert_template 'edit'
444 u = User.find(2)
480 u = User.find(2)
445 assert_equal [1, 2, 5], u.projects.collect{|p| p.id}.sort
481 assert_equal [1, 2, 5], u.projects.collect{|p| p.id}.sort
446 assert_equal [1, 2, 5], u.notified_projects_ids.sort
482 assert_equal [1, 2, 5], u.notified_projects_ids.sort
447 assert_select 'input[name=?][value=?]', 'user[notified_project_ids][]', '1'
483 assert_select 'input[name=?][value=?]', 'user[notified_project_ids][]', '1'
448 assert_equal 'all', u.mail_notification
484 assert_equal 'all', u.mail_notification
449 put :update, :id => 2,
485 put :update, :params => {
486 :id => 2,
450 :user => {
487 :user => {
451 :mail_notification => 'selected',
488 :mail_notification => 'selected',
452 :notified_project_ids => [1, 2]
489 :notified_project_ids => [1, 2]
453 }
490 }
491 }
454 u = User.find(2)
492 u = User.find(2)
455 assert_equal 'selected', u.mail_notification
493 assert_equal 'selected', u.mail_notification
456 assert_equal [1, 2], u.notified_projects_ids.sort
494 assert_equal [1, 2], u.notified_projects_ids.sort
457 end
495 end
458
496
459 def test_update_status_should_not_update_attributes
497 def test_update_status_should_not_update_attributes
460 user = User.find(2)
498 user = User.find(2)
461 user.pref[:no_self_notified] = '1'
499 user.pref[:no_self_notified] = '1'
462 user.pref.save
500 user.pref.save
463
501
464 put :update, :id => 2, :user => {:status => 3}
502 put :update, :params => {
503 :id => 2,
504 :user => {:status => 3}
505 }
465 assert_response 302
506 assert_response 302
466 user = User.find(2)
507 user = User.find(2)
467 assert_equal 3, user.status
508 assert_equal 3, user.status
468 assert_equal '1', user.pref[:no_self_notified]
509 assert_equal '1', user.pref[:no_self_notified]
469 end
510 end
470
511
471 def test_update_assign_admin_should_send_security_notification
512 def test_update_assign_admin_should_send_security_notification
472 ActionMailer::Base.deliveries.clear
513 ActionMailer::Base.deliveries.clear
473 put :update, :id => 2, :user => {
514 put :update, :params => {
474 :admin => 1
515 :id => 2,
516 :user => {:admin => 1}
475 }
517 }
476
518
477 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
519 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
478 assert_mail_body_match I18n.t(:mail_body_security_notification_add, field: I18n.t(:field_admin), value: User.find(2).login), mail
520 assert_mail_body_match I18n.t(:mail_body_security_notification_add, field: I18n.t(:field_admin), value: User.find(2).login), mail
479
521
480 # All admins should receive this
522 # All admins should receive this
481 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
523 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
482 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
524 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
483 end
525 end
484 end
526 end
485
527
486 def test_update_unassign_admin_should_send_security_notification
528 def test_update_unassign_admin_should_send_security_notification
487 user = User.find(2)
529 user = User.find(2)
488 user.admin = true
530 user.admin = true
489 user.save!
531 user.save!
490
532
491 ActionMailer::Base.deliveries.clear
533 ActionMailer::Base.deliveries.clear
492 put :update, :id => user.id, :user => {
534 put :update, :params => {
493 :admin => 0
535 :id => user.id,
536 :user => {:admin => 0}
494 }
537 }
495
538
496 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
539 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
497 assert_mail_body_match I18n.t(:mail_body_security_notification_remove, field: I18n.t(:field_admin), value: user.login), mail
540 assert_mail_body_match I18n.t(:mail_body_security_notification_remove, field: I18n.t(:field_admin), value: user.login), mail
498
541
499 # All admins should receive this
542 # All admins should receive this
500 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
543 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
501 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
544 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
502 end
545 end
503 end
546 end
504
547
505 def test_update_lock_admin_should_send_security_notification
548 def test_update_lock_admin_should_send_security_notification
506 user = User.find(2)
549 user = User.find(2)
507 user.admin = true
550 user.admin = true
508 user.save!
551 user.save!
509
552
510 ActionMailer::Base.deliveries.clear
553 ActionMailer::Base.deliveries.clear
511 put :update, :id => 2, :user => {
554 put :update, :params => {
512 :status => Principal::STATUS_LOCKED
555 :id => 2,
556 :user => {:status => Principal::STATUS_LOCKED}
513 }
557 }
514
558
515 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
559 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
516 assert_mail_body_match I18n.t(:mail_body_security_notification_remove, field: I18n.t(:field_admin), value: User.find(2).login), mail
560 assert_mail_body_match I18n.t(:mail_body_security_notification_remove, field: I18n.t(:field_admin), value: User.find(2).login), mail
517
561
518 # All admins should receive this
562 # All admins should receive this
519 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
563 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
520 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
564 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
521 end
565 end
522
566
523 # if user is already locked, destroying should not send a second mail
567 # if user is already locked, destroying should not send a second mail
524 # (for active admins see furtherbelow)
568 # (for active admins see furtherbelow)
525 ActionMailer::Base.deliveries.clear
569 ActionMailer::Base.deliveries.clear
526 delete :destroy, :id => 1
570 delete :destroy, :params => {:id => 1}
527 assert_nil ActionMailer::Base.deliveries.last
571 assert_nil ActionMailer::Base.deliveries.last
528
572
529 end
573 end
530
574
531 def test_update_unlock_admin_should_send_security_notification
575 def test_update_unlock_admin_should_send_security_notification
532 user = User.find(5) # already locked
576 user = User.find(5) # already locked
533 user.admin = true
577 user.admin = true
534 user.save!
578 user.save!
535 ActionMailer::Base.deliveries.clear
579 ActionMailer::Base.deliveries.clear
536 put :update, :id => user.id, :user => {
580 put :update, :params => {
537 :status => Principal::STATUS_ACTIVE
581 :id => user.id,
582 :user => {:status => Principal::STATUS_ACTIVE}
538 }
583 }
539
584
540 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
585 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
541 assert_mail_body_match I18n.t(:mail_body_security_notification_add, field: I18n.t(:field_admin), value: user.login), mail
586 assert_mail_body_match I18n.t(:mail_body_security_notification_add, field: I18n.t(:field_admin), value: user.login), mail
542
587
543 # All admins should receive this
588 # All admins should receive this
544 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
589 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
545 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
590 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
546 end
591 end
547 end
592 end
548
593
549 def test_update_admin_unrelated_property_should_not_send_security_notification
594 def test_update_admin_unrelated_property_should_not_send_security_notification
550 ActionMailer::Base.deliveries.clear
595 ActionMailer::Base.deliveries.clear
551 put :update, :id => 1, :user => {
596 put :update, :params => {
552 :firstname => 'Jimmy'
597 :id => 1,
598 :user => {:firstname => 'Jimmy'}
553 }
599 }
554 assert_nil ActionMailer::Base.deliveries.last
600 assert_nil ActionMailer::Base.deliveries.last
555 end
601 end
556
602
557 def test_destroy
603 def test_destroy
558 assert_difference 'User.count', -1 do
604 assert_difference 'User.count', -1 do
559 delete :destroy, :id => 2
605 delete :destroy, :params => {:id => 2}
560 end
606 end
561 assert_redirected_to '/users'
607 assert_redirected_to '/users'
562 assert_nil User.find_by_id(2)
608 assert_nil User.find_by_id(2)
563 end
609 end
564
610
565 def test_destroy_should_be_denied_for_non_admin_users
611 def test_destroy_should_be_denied_for_non_admin_users
566 @request.session[:user_id] = 3
612 @request.session[:user_id] = 3
567
613
568 assert_no_difference 'User.count' do
614 assert_no_difference 'User.count' do
569 get :destroy, :id => 2
615 get :destroy, :params => {:id => 2}
570 end
616 end
571 assert_response 403
617 assert_response 403
572 end
618 end
573
619
574 def test_destroy_should_redirect_to_back_url_param
620 def test_destroy_should_redirect_to_back_url_param
575 assert_difference 'User.count', -1 do
621 assert_difference 'User.count', -1 do
576 delete :destroy, :id => 2, :back_url => '/users?name=foo'
622 delete :destroy, :params => {:id => 2, :back_url => '/users?name=foo'}
577 end
623 end
578 assert_redirected_to '/users?name=foo'
624 assert_redirected_to '/users?name=foo'
579 end
625 end
580
626
581 def test_destroy_active_admin_should_send_security_notification
627 def test_destroy_active_admin_should_send_security_notification
582 user = User.find(2)
628 user = User.find(2)
583 user.admin = true
629 user.admin = true
584 user.save!
630 user.save!
585 ActionMailer::Base.deliveries.clear
631 ActionMailer::Base.deliveries.clear
586 delete :destroy, :id => user.id
632 delete :destroy, :params => {:id => user.id}
587
633
588 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
634 assert_not_nil (mail = ActionMailer::Base.deliveries.last)
589 assert_mail_body_match I18n.t(:mail_body_security_notification_remove, field: I18n.t(:field_admin), value: user.login), mail
635 assert_mail_body_match I18n.t(:mail_body_security_notification_remove, field: I18n.t(:field_admin), value: user.login), mail
590
636
591 # All admins should receive this
637 # All admins should receive this
592 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
638 User.where(admin: true, status: Principal::STATUS_ACTIVE).each do |admin|
593 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
639 assert_not_nil ActionMailer::Base.deliveries.detect{|mail| [mail.bcc, mail.cc].flatten.include?(admin.mail) }
594 end
640 end
595 end
641 end
596 end
642 end
@@ -1,366 +1,374
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 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 if ENV["COVERAGE"]
18 if ENV["COVERAGE"]
19 require 'simplecov'
19 require 'simplecov'
20 require File.expand_path(File.dirname(__FILE__) + "/coverage/html_formatter")
20 require File.expand_path(File.dirname(__FILE__) + "/coverage/html_formatter")
21 SimpleCov.formatter = Redmine::Coverage::HtmlFormatter
21 SimpleCov.formatter = Redmine::Coverage::HtmlFormatter
22 SimpleCov.start 'rails'
22 SimpleCov.start 'rails'
23 end
23 end
24
24
25 $redmine_test_ldap_server = ENV['REDMINE_TEST_LDAP_SERVER'] || '127.0.0.1'
25 $redmine_test_ldap_server = ENV['REDMINE_TEST_LDAP_SERVER'] || '127.0.0.1'
26
26
27 ENV["RAILS_ENV"] = "test"
27 ENV["RAILS_ENV"] = "test"
28 require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
28 require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
29 require 'rails/test_help'
29 require 'rails/test_help'
30 require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s
30 require Rails.root.join('test', 'mocks', 'open_id_authentication_mock.rb').to_s
31
31
32 require File.expand_path(File.dirname(__FILE__) + '/object_helpers')
32 require File.expand_path(File.dirname(__FILE__) + '/object_helpers')
33 include ObjectHelpers
33 include ObjectHelpers
34
34
35 require 'net/ldap'
35 require 'net/ldap'
36 require 'mocha/setup'
36 require 'mocha/setup'
37
37
38 Redmine::SudoMode.disable!
38 Redmine::SudoMode.disable!
39
39
40 class ActionView::TestCase
40 class ActionView::TestCase
41 helper :application
41 helper :application
42 include ApplicationHelper
42 include ApplicationHelper
43 end
43 end
44
44
45 class ActiveSupport::TestCase
45 class ActiveSupport::TestCase
46 include ActionDispatch::TestProcess
46 include ActionDispatch::TestProcess
47
47
48 self.use_transactional_fixtures = true
48 self.use_transactional_fixtures = true
49 self.use_instantiated_fixtures = false
49 self.use_instantiated_fixtures = false
50
50
51 def uploaded_test_file(name, mime)
51 def uploaded_test_file(name, mime)
52 fixture_file_upload("files/#{name}", mime, true)
52 fixture_file_upload("files/#{name}", mime, true)
53 end
53 end
54
54
55 # Mock out a file
55 # Mock out a file
56 def self.mock_file
56 def self.mock_file
57 file = 'a_file.png'
57 file = 'a_file.png'
58 file.stubs(:size).returns(32)
58 file.stubs(:size).returns(32)
59 file.stubs(:original_filename).returns('a_file.png')
59 file.stubs(:original_filename).returns('a_file.png')
60 file.stubs(:content_type).returns('image/png')
60 file.stubs(:content_type).returns('image/png')
61 file.stubs(:read).returns(false)
61 file.stubs(:read).returns(false)
62 file
62 file
63 end
63 end
64
64
65 def mock_file
65 def mock_file
66 self.class.mock_file
66 self.class.mock_file
67 end
67 end
68
68
69 def mock_file_with_options(options={})
69 def mock_file_with_options(options={})
70 file = ''
70 file = ''
71 file.stubs(:size).returns(32)
71 file.stubs(:size).returns(32)
72 original_filename = options[:original_filename] || nil
72 original_filename = options[:original_filename] || nil
73 file.stubs(:original_filename).returns(original_filename)
73 file.stubs(:original_filename).returns(original_filename)
74 content_type = options[:content_type] || nil
74 content_type = options[:content_type] || nil
75 file.stubs(:content_type).returns(content_type)
75 file.stubs(:content_type).returns(content_type)
76 file.stubs(:read).returns(false)
76 file.stubs(:read).returns(false)
77 file
77 file
78 end
78 end
79
79
80 # Use a temporary directory for attachment related tests
80 # Use a temporary directory for attachment related tests
81 def set_tmp_attachments_directory
81 def set_tmp_attachments_directory
82 Dir.mkdir "#{Rails.root}/tmp/test" unless File.directory?("#{Rails.root}/tmp/test")
82 Dir.mkdir "#{Rails.root}/tmp/test" unless File.directory?("#{Rails.root}/tmp/test")
83 unless File.directory?("#{Rails.root}/tmp/test/attachments")
83 unless File.directory?("#{Rails.root}/tmp/test/attachments")
84 Dir.mkdir "#{Rails.root}/tmp/test/attachments"
84 Dir.mkdir "#{Rails.root}/tmp/test/attachments"
85 end
85 end
86 Attachment.storage_path = "#{Rails.root}/tmp/test/attachments"
86 Attachment.storage_path = "#{Rails.root}/tmp/test/attachments"
87 end
87 end
88
88
89 def set_fixtures_attachments_directory
89 def set_fixtures_attachments_directory
90 Attachment.storage_path = "#{Rails.root}/test/fixtures/files"
90 Attachment.storage_path = "#{Rails.root}/test/fixtures/files"
91 end
91 end
92
92
93 def with_settings(options, &block)
93 def with_settings(options, &block)
94 saved_settings = options.keys.inject({}) do |h, k|
94 saved_settings = options.keys.inject({}) do |h, k|
95 h[k] = case Setting[k]
95 h[k] = case Setting[k]
96 when Symbol, false, true, nil
96 when Symbol, false, true, nil
97 Setting[k]
97 Setting[k]
98 else
98 else
99 Setting[k].dup
99 Setting[k].dup
100 end
100 end
101 h
101 h
102 end
102 end
103 options.each {|k, v| Setting[k] = v}
103 options.each {|k, v| Setting[k] = v}
104 yield
104 yield
105 ensure
105 ensure
106 saved_settings.each {|k, v| Setting[k] = v} if saved_settings
106 saved_settings.each {|k, v| Setting[k] = v} if saved_settings
107 end
107 end
108
108
109 # Yields the block with user as the current user
109 # Yields the block with user as the current user
110 def with_current_user(user, &block)
110 def with_current_user(user, &block)
111 saved_user = User.current
111 saved_user = User.current
112 User.current = user
112 User.current = user
113 yield
113 yield
114 ensure
114 ensure
115 User.current = saved_user
115 User.current = saved_user
116 end
116 end
117
117
118 def with_locale(locale, &block)
118 def with_locale(locale, &block)
119 saved_localed = ::I18n.locale
119 saved_localed = ::I18n.locale
120 ::I18n.locale = locale
120 ::I18n.locale = locale
121 yield
121 yield
122 ensure
122 ensure
123 ::I18n.locale = saved_localed
123 ::I18n.locale = saved_localed
124 end
124 end
125
125
126 def self.ldap_configured?
126 def self.ldap_configured?
127 @test_ldap = Net::LDAP.new(:host => $redmine_test_ldap_server, :port => 389)
127 @test_ldap = Net::LDAP.new(:host => $redmine_test_ldap_server, :port => 389)
128 return @test_ldap.bind
128 return @test_ldap.bind
129 rescue Exception => e
129 rescue Exception => e
130 # LDAP is not listening
130 # LDAP is not listening
131 return nil
131 return nil
132 end
132 end
133
133
134 def self.convert_installed?
134 def self.convert_installed?
135 Redmine::Thumbnail.convert_available?
135 Redmine::Thumbnail.convert_available?
136 end
136 end
137
137
138 def convert_installed?
138 def convert_installed?
139 self.class.convert_installed?
139 self.class.convert_installed?
140 end
140 end
141
141
142 # Returns the path to the test +vendor+ repository
142 # Returns the path to the test +vendor+ repository
143 def self.repository_path(vendor)
143 def self.repository_path(vendor)
144 path = Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
144 path = Rails.root.join("tmp/test/#{vendor.downcase}_repository").to_s
145 # Unlike ruby, JRuby returns Rails.root with backslashes under Windows
145 # Unlike ruby, JRuby returns Rails.root with backslashes under Windows
146 path.tr("\\", "/")
146 path.tr("\\", "/")
147 end
147 end
148
148
149 # Returns the url of the subversion test repository
149 # Returns the url of the subversion test repository
150 def self.subversion_repository_url
150 def self.subversion_repository_url
151 path = repository_path('subversion')
151 path = repository_path('subversion')
152 path = '/' + path unless path.starts_with?('/')
152 path = '/' + path unless path.starts_with?('/')
153 "file://#{path}"
153 "file://#{path}"
154 end
154 end
155
155
156 # Returns true if the +vendor+ test repository is configured
156 # Returns true if the +vendor+ test repository is configured
157 def self.repository_configured?(vendor)
157 def self.repository_configured?(vendor)
158 File.directory?(repository_path(vendor))
158 File.directory?(repository_path(vendor))
159 end
159 end
160
160
161 def repository_path_hash(arr)
161 def repository_path_hash(arr)
162 hs = {}
162 hs = {}
163 hs[:path] = arr.join("/")
163 hs[:path] = arr.join("/")
164 hs[:param] = arr.join("/")
164 hs[:param] = arr.join("/")
165 hs
165 hs
166 end
166 end
167
167
168 def sqlite?
168 def sqlite?
169 ActiveRecord::Base.connection.adapter_name =~ /sqlite/i
169 ActiveRecord::Base.connection.adapter_name =~ /sqlite/i
170 end
170 end
171
171
172 def mysql?
172 def mysql?
173 ActiveRecord::Base.connection.adapter_name =~ /mysql/i
173 ActiveRecord::Base.connection.adapter_name =~ /mysql/i
174 end
174 end
175
175
176 def postgresql?
176 def postgresql?
177 ActiveRecord::Base.connection.adapter_name =~ /postgresql/i
177 ActiveRecord::Base.connection.adapter_name =~ /postgresql/i
178 end
178 end
179
179
180 def quoted_date(date)
180 def quoted_date(date)
181 date = Date.parse(date) if date.is_a?(String)
181 date = Date.parse(date) if date.is_a?(String)
182 ActiveRecord::Base.connection.quoted_date(date)
182 ActiveRecord::Base.connection.quoted_date(date)
183 end
183 end
184
184
185 # Asserts that a new record for the given class is created
185 # Asserts that a new record for the given class is created
186 # and returns it
186 # and returns it
187 def new_record(klass, &block)
187 def new_record(klass, &block)
188 new_records(klass, 1, &block).first
188 new_records(klass, 1, &block).first
189 end
189 end
190
190
191 # Asserts that count new records for the given class are created
191 # Asserts that count new records for the given class are created
192 # and returns them as an array order by object id
192 # and returns them as an array order by object id
193 def new_records(klass, count, &block)
193 def new_records(klass, count, &block)
194 assert_difference "#{klass}.count", count do
194 assert_difference "#{klass}.count", count do
195 yield
195 yield
196 end
196 end
197 klass.order(:id => :desc).limit(count).to_a.reverse
197 klass.order(:id => :desc).limit(count).to_a.reverse
198 end
198 end
199
199
200 def assert_save(object)
200 def assert_save(object)
201 saved = object.save
201 saved = object.save
202 message = "#{object.class} could not be saved"
202 message = "#{object.class} could not be saved"
203 errors = object.errors.full_messages.map {|m| "- #{m}"}
203 errors = object.errors.full_messages.map {|m| "- #{m}"}
204 message << ":\n#{errors.join("\n")}" if errors.any?
204 message << ":\n#{errors.join("\n")}" if errors.any?
205 assert_equal true, saved, message
205 assert_equal true, saved, message
206 end
206 end
207
207
208 def assert_select_error(arg)
208 def assert_select_error(arg)
209 assert_select '#errorExplanation', :text => arg
209 assert_select '#errorExplanation', :text => arg
210 end
210 end
211
211
212 def assert_include(expected, s, message=nil)
212 def assert_include(expected, s, message=nil)
213 assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
213 assert s.include?(expected), (message || "\"#{expected}\" not found in \"#{s}\"")
214 end
214 end
215
215
216 def assert_not_include(expected, s, message=nil)
216 def assert_not_include(expected, s, message=nil)
217 assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
217 assert !s.include?(expected), (message || "\"#{expected}\" found in \"#{s}\"")
218 end
218 end
219
219
220 def assert_select_in(text, *args, &block)
220 def assert_select_in(text, *args, &block)
221 d = Nokogiri::HTML(CGI::unescapeHTML(String.new(text))).root
221 d = Nokogiri::HTML(CGI::unescapeHTML(String.new(text))).root
222 assert_select(d, *args, &block)
222 assert_select(d, *args, &block)
223 end
223 end
224
224
225 def assert_select_email(*args, &block)
225 def assert_select_email(*args, &block)
226 email = ActionMailer::Base.deliveries.last
226 email = ActionMailer::Base.deliveries.last
227 assert_not_nil email
227 assert_not_nil email
228 html_body = email.parts.detect {|part| part.content_type.include?('text/html')}.try(&:body)
228 html_body = email.parts.detect {|part| part.content_type.include?('text/html')}.try(&:body)
229 assert_not_nil html_body
229 assert_not_nil html_body
230 assert_select_in html_body.encoded, *args, &block
230 assert_select_in html_body.encoded, *args, &block
231 end
231 end
232
232
233 def assert_mail_body_match(expected, mail, message=nil)
233 def assert_mail_body_match(expected, mail, message=nil)
234 if expected.is_a?(String)
234 if expected.is_a?(String)
235 assert_include expected, mail_body(mail), message
235 assert_include expected, mail_body(mail), message
236 else
236 else
237 assert_match expected, mail_body(mail), message
237 assert_match expected, mail_body(mail), message
238 end
238 end
239 end
239 end
240
240
241 def assert_mail_body_no_match(expected, mail, message=nil)
241 def assert_mail_body_no_match(expected, mail, message=nil)
242 if expected.is_a?(String)
242 if expected.is_a?(String)
243 assert_not_include expected, mail_body(mail), message
243 assert_not_include expected, mail_body(mail), message
244 else
244 else
245 assert_no_match expected, mail_body(mail), message
245 assert_no_match expected, mail_body(mail), message
246 end
246 end
247 end
247 end
248
248
249 def mail_body(mail)
249 def mail_body(mail)
250 mail.parts.first.body.encoded
250 mail.parts.first.body.encoded
251 end
251 end
252
252
253 # Returns the lft value for a new root issue
253 # Returns the lft value for a new root issue
254 def new_issue_lft
254 def new_issue_lft
255 1
255 1
256 end
256 end
257 end
257 end
258
258
259 module Redmine
259 module Redmine
260 class RoutingTest < ActionDispatch::IntegrationTest
260 class RoutingTest < ActionDispatch::IntegrationTest
261 def should_route(arg)
261 def should_route(arg)
262 arg = arg.dup
262 arg = arg.dup
263 request = arg.keys.detect {|key| key.is_a?(String)}
263 request = arg.keys.detect {|key| key.is_a?(String)}
264 raise ArgumentError unless request
264 raise ArgumentError unless request
265 options = arg.slice!(request)
265 options = arg.slice!(request)
266
266
267 raise ArgumentError unless request =~ /\A(GET|POST|PUT|PATCH|DELETE)\s+(.+)\z/
267 raise ArgumentError unless request =~ /\A(GET|POST|PUT|PATCH|DELETE)\s+(.+)\z/
268 method, path = $1.downcase.to_sym, $2
268 method, path = $1.downcase.to_sym, $2
269
269
270 raise ArgumentError unless arg.values.first =~ /\A(.+)#(.+)\z/
270 raise ArgumentError unless arg.values.first =~ /\A(.+)#(.+)\z/
271 controller, action = $1, $2
271 controller, action = $1, $2
272
272
273 assert_routing(
273 assert_routing(
274 {:method => method, :path => path},
274 {:method => method, :path => path},
275 options.merge(:controller => controller, :action => action)
275 options.merge(:controller => controller, :action => action)
276 )
276 )
277 end
277 end
278 end
278 end
279
279
280 class ControllerTest < ActionController::TestCase
280 class ControllerTest < ActionController::TestCase
281 def process(method, path, parameters={}, options={})
282 if parameters.key?(:params)
283 raise ArgumentError if options.present?
284 super method, path, parameters[:params], parameters.except(:params)
285 else
286 super
287 end
288 end
281 end
289 end
282
290
283 class IntegrationTest < ActionDispatch::IntegrationTest
291 class IntegrationTest < ActionDispatch::IntegrationTest
284 def log_user(login, password)
292 def log_user(login, password)
285 User.anonymous
293 User.anonymous
286 get "/login"
294 get "/login"
287 assert_equal nil, session[:user_id]
295 assert_equal nil, session[:user_id]
288 assert_response :success
296 assert_response :success
289 assert_template "account/login"
297 assert_template "account/login"
290 post "/login", :username => login, :password => password
298 post "/login", :username => login, :password => password
291 assert_equal login, User.find(session[:user_id]).login
299 assert_equal login, User.find(session[:user_id]).login
292 end
300 end
293
301
294 def credentials(user, password=nil)
302 def credentials(user, password=nil)
295 {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
303 {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password || user)}
296 end
304 end
297 end
305 end
298
306
299 module ApiTest
307 module ApiTest
300 API_FORMATS = %w(json xml).freeze
308 API_FORMATS = %w(json xml).freeze
301
309
302 # Base class for API tests
310 # Base class for API tests
303 class Base < Redmine::IntegrationTest
311 class Base < Redmine::IntegrationTest
304 def setup
312 def setup
305 Setting.rest_api_enabled = '1'
313 Setting.rest_api_enabled = '1'
306 end
314 end
307
315
308 def teardown
316 def teardown
309 Setting.rest_api_enabled = '0'
317 Setting.rest_api_enabled = '0'
310 end
318 end
311
319
312 # Uploads content using the XML API and returns the attachment token
320 # Uploads content using the XML API and returns the attachment token
313 def xml_upload(content, credentials)
321 def xml_upload(content, credentials)
314 upload('xml', content, credentials)
322 upload('xml', content, credentials)
315 end
323 end
316
324
317 # Uploads content using the JSON API and returns the attachment token
325 # Uploads content using the JSON API and returns the attachment token
318 def json_upload(content, credentials)
326 def json_upload(content, credentials)
319 upload('json', content, credentials)
327 upload('json', content, credentials)
320 end
328 end
321
329
322 def upload(format, content, credentials)
330 def upload(format, content, credentials)
323 set_tmp_attachments_directory
331 set_tmp_attachments_directory
324 assert_difference 'Attachment.count' do
332 assert_difference 'Attachment.count' do
325 post "/uploads.#{format}", content, {"CONTENT_TYPE" => 'application/octet-stream'}.merge(credentials)
333 post "/uploads.#{format}", content, {"CONTENT_TYPE" => 'application/octet-stream'}.merge(credentials)
326 assert_response :created
334 assert_response :created
327 end
335 end
328 data = response_data
336 data = response_data
329 assert_kind_of Hash, data['upload']
337 assert_kind_of Hash, data['upload']
330 token = data['upload']['token']
338 token = data['upload']['token']
331 assert_not_nil token
339 assert_not_nil token
332 token
340 token
333 end
341 end
334
342
335 # Parses the response body based on its content type
343 # Parses the response body based on its content type
336 def response_data
344 def response_data
337 unless response.content_type.to_s =~ /^application\/(.+)/
345 unless response.content_type.to_s =~ /^application\/(.+)/
338 raise "Unexpected response type: #{response.content_type}"
346 raise "Unexpected response type: #{response.content_type}"
339 end
347 end
340 format = $1
348 format = $1
341 case format
349 case format
342 when 'xml'
350 when 'xml'
343 Hash.from_xml(response.body)
351 Hash.from_xml(response.body)
344 when 'json'
352 when 'json'
345 ActiveSupport::JSON.decode(response.body)
353 ActiveSupport::JSON.decode(response.body)
346 else
354 else
347 raise "Unknown response format: #{format}"
355 raise "Unknown response format: #{format}"
348 end
356 end
349 end
357 end
350 end
358 end
351
359
352 class Routing < Redmine::RoutingTest
360 class Routing < Redmine::RoutingTest
353 def should_route(arg)
361 def should_route(arg)
354 arg = arg.dup
362 arg = arg.dup
355 request = arg.keys.detect {|key| key.is_a?(String)}
363 request = arg.keys.detect {|key| key.is_a?(String)}
356 raise ArgumentError unless request
364 raise ArgumentError unless request
357 options = arg.slice!(request)
365 options = arg.slice!(request)
358
366
359 API_FORMATS.each do |format|
367 API_FORMATS.each do |format|
360 format_request = request.sub /$/, ".#{format}"
368 format_request = request.sub /$/, ".#{format}"
361 super options.merge(format_request => arg[request], :format => format)
369 super options.merge(format_request => arg[request], :format => format)
362 end
370 end
363 end
371 end
364 end
372 end
365 end
373 end
366 end
374 end
General Comments 0
You need to be logged in to leave comments. Login now