##// END OF EJS Templates
Refactor: convert username/password http basic auth api tests to shoulda macros #6447...
Eric Davis -
r4246:a04d64881cca
parent child
Show More
@@ -1,103 +1,31
1 1 require "#{File.dirname(__FILE__)}/../../test_helper"
2 2
3 3 class ApiTest::HttpBasicLoginTest < ActionController::IntegrationTest
4 4 fixtures :all
5 5
6 6 def setup
7 7 Setting.rest_api_enabled = '1'
8 8 Setting.login_required = '1'
9 9 end
10 10
11 11 def teardown
12 12 Setting.rest_api_enabled = '0'
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" do
18 setup do
19 project = Project.find('onlinestore')
20 EnabledModule.create(:project => project, :name => 'news')
21 end
18 22
19 23 context "in :xml format" do
20 context "with a valid HTTP authentication" do
21 setup do
22 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password')
23 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
24 get "/news.xml", nil, :authorization => @authorization
25 end
26
27 should_respond_with :success
28 should_respond_with_content_type :xml
29 should "login as the user" do
30 assert_equal @user, User.current
31 end
32 end
33
34 context "with an invalid HTTP authentication" do
35 setup do
36 @user = User.generate_with_protected!
37 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
38 get "/news.xml", nil, :authorization => @authorization
39 end
40
41 should_respond_with :unauthorized
42 should_respond_with_content_type :xml
43 should "not login as the user" do
44 assert_equal User.anonymous, User.current
45 end
46 end
47
48 context "without credentials" do
49 setup do
50 get "/projects/onlinestore/news.xml"
51 end
52
53 should_respond_with :unauthorized
54 should_respond_with_content_type :xml
55 should "include_www_authenticate_header" do
56 assert @controller.response.headers.has_key?('WWW-Authenticate')
57 end
58 end
24 should_allow_http_basic_auth_with_username_and_password(:get, "/projects/onlinestore/news.xml")
59 25 end
60 26
61 27 context "in :json format" do
62 context "with a valid HTTP authentication" do
63 setup do
64 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password')
65 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
66 get "/news.json", nil, :authorization => @authorization
67 end
68
69 should_respond_with :success
70 should_respond_with_content_type :json
71 should "login as the user" do
72 assert_equal @user, User.current
73 end
74 end
75
76 context "with an invalid HTTP authentication" do
77 setup do
78 @user = User.generate_with_protected!
79 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
80 get "/news.json", nil, :authorization => @authorization
81 end
82
83 should_respond_with :unauthorized
84 should_respond_with_content_type :json
85 should "not login as the user" do
86 assert_equal User.anonymous, User.current
87 end
88 end
89 end
90
91 context "without credentials" do
92 setup do
93 get "/projects/onlinestore/news.json"
94 end
95
96 should_respond_with :unauthorized
97 should_respond_with_content_type :json
98 should "include_www_authenticate_header" do
99 assert @controller.response.headers.has_key?('WWW-Authenticate')
100 end
28 should_allow_http_basic_auth_with_username_and_password(:get, "/projects/onlinestore/news.json")
101 29 end
102 30 end
103 31 end
@@ -1,247 +1,297
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 def assert_error_tag(options={})
118 118 assert_tag({:tag => 'p', :attributes => { :id => 'errorExplanation' }}.merge(options))
119 119 end
120 120
121 121 # Shoulda macros
122 122 def self.should_render_404
123 123 should_respond_with :not_found
124 124 should_render_template 'common/error'
125 125 end
126 126
127 127 def self.should_have_before_filter(expected_method, options = {})
128 128 should_have_filter('before', expected_method, options)
129 129 end
130 130
131 131 def self.should_have_after_filter(expected_method, options = {})
132 132 should_have_filter('after', expected_method, options)
133 133 end
134 134
135 135 def self.should_have_filter(filter_type, expected_method, options)
136 136 description = "have #{filter_type}_filter :#{expected_method}"
137 137 description << " with #{options.inspect}" unless options.empty?
138 138
139 139 should description do
140 140 klass = "action_controller/filters/#{filter_type}_filter".classify.constantize
141 141 expected = klass.new(:filter, expected_method.to_sym, options)
142 142 assert_equal 1, @controller.class.filter_chain.select { |filter|
143 143 filter.method == expected.method && filter.kind == expected.kind &&
144 144 filter.options == expected.options && filter.class == expected.class
145 145 }.size
146 146 end
147 147 end
148 148
149 149 def self.should_show_the_old_and_new_values_for(prop_key, model, &block)
150 150 context "" do
151 151 setup do
152 152 if block_given?
153 153 instance_eval &block
154 154 else
155 155 @old_value = model.generate!
156 156 @new_value = model.generate!
157 157 end
158 158 end
159 159
160 160 should "use the new value's name" do
161 161 @detail = JournalDetail.generate!(:property => 'attr',
162 162 :old_value => @old_value.id,
163 163 :value => @new_value.id,
164 164 :prop_key => prop_key)
165 165
166 166 assert_match @new_value.name, show_detail(@detail, true)
167 167 end
168 168
169 169 should "use the old value's name" do
170 170 @detail = JournalDetail.generate!(:property => 'attr',
171 171 :old_value => @old_value.id,
172 172 :value => @new_value.id,
173 173 :prop_key => prop_key)
174 174
175 175 assert_match @old_value.name, show_detail(@detail, true)
176 176 end
177 177 end
178 178 end
179 179
180 180 def self.should_create_a_new_user(&block)
181 181 should "create a new user" do
182 182 user = instance_eval &block
183 183 assert user
184 184 assert_kind_of User, user
185 185 assert !user.new_record?
186 186 end
187 187 end
188 188
189 # Test that a request allows the username and password for HTTP BASIC
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 def self.should_allow_http_basic_auth_with_username_and_password(http_method, url, parameters={})
195 context "should allow http basic auth using a username and password for #{http_method} #{url}" do
196 context "with a valid HTTP authentication" do
197 setup do
198 @user = User.generate_with_protected!(:password => 'my_password', :password_confirmation => 'my_password', :admin => true) # Admin so they can access the project
199 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'my_password')
200 send(http_method, url, parameters, {:authorization => @authorization})
201 end
202
203 should_respond_with :success
204 should_respond_with_content_type_based_on_url(url)
205 should "login as the user" do
206 assert_equal @user, User.current
207 end
208 end
209
210 context "with an invalid HTTP authentication" do
211 setup do
212 @user = User.generate_with_protected!
213 @authorization = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, 'wrong_password')
214 send(http_method, url, parameters, {:authorization => @authorization})
215 end
216
217 should_respond_with :unauthorized
218 should_respond_with_content_type_based_on_url(url)
219 should "not login as the user" do
220 assert_equal User.anonymous, User.current
221 end
222 end
223
224 context "without credentials" do
225 setup do
226 send(http_method, url, parameters, {:authorization => ''})
227 end
228
229 should_respond_with :unauthorized
230 should_respond_with_content_type_based_on_url(url)
231 should "include_www_authenticate_header" do
232 assert @controller.response.headers.has_key?('WWW-Authenticate')
233 end
234 end
235 end
236
237 end
238
189 239 # Test that a request allows full key authentication
190 240 #
191 241 # @param [Symbol] http_method the HTTP method for request (:get, :post, :put, :delete)
192 242 # @param [String] url the request url, without the key=ZXY parameter
193 243 def self.should_allow_key_based_auth(http_method, url)
194 context "should allow key based auth using key=X for #{url}" do
244 context "should allow key based auth using key=X for #{http_method} #{url}" do
195 245 context "with a valid api token" do
196 246 setup do
197 247 @user = User.generate_with_protected!
198 248 @token = Token.generate!(:user => @user, :action => 'api')
199 249 send(http_method, url + "?key=#{@token.value}")
200 250 end
201 251
202 252 should_respond_with :success
203 253 should_respond_with_content_type_based_on_url(url)
204 254 should "login as the user" do
205 255 assert_equal @user, User.current
206 256 end
207 257 end
208 258
209 259 context "with an invalid api token" do
210 260 setup do
211 261 @user = User.generate_with_protected!
212 262 @token = Token.generate!(:user => @user, :action => 'feeds')
213 263 send(http_method, url + "?key=#{@token.value}")
214 264 end
215 265
216 266 should_respond_with :unauthorized
217 267 should_respond_with_content_type_based_on_url(url)
218 268 should "not login as the user" do
219 269 assert_equal User.anonymous, User.current
220 270 end
221 271 end
222 272 end
223 273
224 274 end
225 275
226 276 # Uses should_respond_with_content_type based on what's in the url:
227 277 #
228 278 # '/project/issues.xml' => should_respond_with_content_type :xml
229 279 # '/project/issues.json' => should_respond_with_content_type :json
230 280 #
231 281 # @param [String] url Request
232 282 def self.should_respond_with_content_type_based_on_url(url)
233 283 case
234 284 when url.match(/xml/i)
235 285 should_respond_with_content_type :xml
236 286 when url.match(/json/i)
237 287 should_respond_with_content_type :json
238 288 else
239 289 raise "Unknown content type for should_respond_with_content_type_based_on_url: #{url}"
240 290 end
241 291
242 292 end
243 293 end
244 294
245 295 # Simple module to "namespace" all of the API tests
246 296 module ApiTest
247 297 end
General Comments 0
You need to be logged in to leave comments. Login now