diff options
Diffstat (limited to 'actionpack/test/controller')
33 files changed, 1247 insertions, 1292 deletions
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index ea56048f37..cb7922efd2 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -326,11 +326,11 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase # check if we were rendered by a file-based template? def test_rendered_action process :nothing - assert_nil @response.rendered_template + assert_nil @response.rendered[:template] process :hello_world - assert @response.rendered_template - assert 'hello_world', @response.rendered_template.to_s + assert @response.rendered[:template] + assert 'hello_world', @response.rendered[:template].to_s end # check the redirection location @@ -500,17 +500,17 @@ class ActionPackHeaderTest < ActionController::TestCase def test_rendering_xml_sets_content_type process :hello_xml_world - assert_equal('application/xml; charset=utf-8', @response.headers['type']) + assert_equal('application/xml; charset=utf-8', @response.headers['Content-Type']) end def test_rendering_xml_respects_content_type @response.headers['type'] = 'application/pdf' process :hello_xml_world - assert_equal('application/pdf; charset=utf-8', @response.headers['type']) + assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type']) end def test_render_text_with_custom_content_type get :render_text_with_custom_content_type - assert_equal 'application/rss+xml; charset=utf-8', @response.headers['type'] + assert_equal 'application/rss+xml; charset=utf-8', @response.headers['Content-Type'] end end diff --git a/actionpack/test/controller/addresses_render_test.rb b/actionpack/test/controller/addresses_render_test.rb index b26cae24fb..556b0593ea 100644 --- a/actionpack/test/controller/addresses_render_test.rb +++ b/actionpack/test/controller/addresses_render_test.rb @@ -19,17 +19,14 @@ class AddressesTestController < ActionController::Base def self.controller_path; "addresses"; end end -class AddressesTest < Test::Unit::TestCase - def setup - @controller = AddressesTestController.new +class AddressesTest < ActionController::TestCase + tests AddressesTestController + def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @request.host = "www.nextangle.com" end diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index ed8c4427c9..99c57c0c91 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -248,6 +248,14 @@ class AssertSelectTest < ActionController::TestCase end end + def test_assert_select_rjs_for_positioned_insert_should_fail_when_mixing_arguments + render_rjs do |page| + page.insert_html :top, "test1", "<div id=\"1\">foo</div>" + page.insert_html :bottom, "test2", "<div id=\"2\">foo</div>" + end + assert_raises(Assertion) {assert_select_rjs :insert, :top, "test2"} + end + # # Test css_select. # diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 18d185b264..9523189f41 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -129,6 +129,8 @@ class PerformActionTest < ActionController::TestCase @response = ActionController::TestResponse.new @request.host = "www.nextangle.com" + + rescue_action_in_public! end def test_get_on_priv_should_show_selector @@ -164,14 +166,12 @@ class PerformActionTest < ActionController::TestCase end end -class DefaultUrlOptionsTest < Test::Unit::TestCase - def setup - @controller = DefaultUrlOptionsController.new - - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new +class DefaultUrlOptionsTest < ActionController::TestCase + tests DefaultUrlOptionsController + def setup @request.host = 'www.example.com' + rescue_action_in_public! end def test_default_url_options_are_used_if_set @@ -189,14 +189,12 @@ class DefaultUrlOptionsTest < Test::Unit::TestCase end end -class EmptyUrlOptionsTest < Test::Unit::TestCase - def setup - @controller = NonEmptyController.new - - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new +class EmptyUrlOptionsTest < ActionController::TestCase + tests NonEmptyController + def setup @request.host = 'www.example.com' + rescue_action_in_public! end def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set diff --git a/actionpack/test/controller/benchmark_test.rb b/actionpack/test/controller/benchmark_test.rb index 608ea5f5a9..f9100a2313 100644 --- a/actionpack/test/controller/benchmark_test.rb +++ b/actionpack/test/controller/benchmark_test.rb @@ -11,17 +11,17 @@ class BenchmarkedController < ActionController::Base end end -class BenchmarkTest < Test::Unit::TestCase +class BenchmarkTest < ActionController::TestCase + tests BenchmarkedController + class MockLogger def method_missing(*args) end end def setup - @controller = BenchmarkedController.new # benchmark doesn't do anything unless a logger is set @controller.logger = MockLogger.new - @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new @request.host = "test.actioncontroller.i" end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 7e7f488df6..7f8e47ba58 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -48,6 +48,7 @@ class PageCachingTest < ActionController::TestCase ActionController::Routing::Routes.draw do |map| map.main '', :controller => 'posts' + map.formatted_posts 'posts.:format', :controller => 'posts' map.resources :posts map.connect ':controller/:action/:id' end @@ -120,8 +121,7 @@ class PageCachingTest < ActionController::TestCase [:get, :post, :put, :delete].each do |method| unless method == :get and status == :ok define_method "test_shouldnt_cache_#{method}_with_#{status}_status" do - @request.env['REQUEST_METHOD'] = method.to_s.upcase - process status + send(method, status) assert_response status assert_page_not_cached status, "#{method} with #{status} status shouldn't have been cached" end @@ -168,7 +168,7 @@ class ActionCachingTestController < ActionController::Base def forbidden render :text => "Forbidden" - headers["Status"] = "403 Forbidden" + response.status = "403 Forbidden" end def with_layout diff --git a/actionpack/test/controller/capture_test.rb b/actionpack/test/controller/capture_test.rb index 5ded6a5d26..6dfa0995eb 100644 --- a/actionpack/test/controller/capture_test.rb +++ b/actionpack/test/controller/capture_test.rb @@ -23,17 +23,14 @@ class CaptureController < ActionController::Base def rescue_action(e) raise end end -class CaptureTest < Test::Unit::TestCase - def setup - @controller = CaptureController.new +class CaptureTest < ActionController::TestCase + tests CaptureController + def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @request.host = "www.nextangle.com" end diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb index ae71d62e11..32c1757ef9 100644 --- a/actionpack/test/controller/content_type_test.rb +++ b/actionpack/test/controller/content_type_test.rb @@ -50,16 +50,13 @@ class ContentTypeController < ActionController::Base def rescue_action(e) raise end end -class ContentTypeTest < Test::Unit::TestCase - def setup - @controller = ContentTypeController.new +class ContentTypeTest < ActionController::TestCase + tests ContentTypeController + def setup # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". @controller.logger = Logger.new(nil) - - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new end def test_render_defaults diff --git a/actionpack/test/controller/cookie_test.rb b/actionpack/test/controller/cookie_test.rb index 5a6fb49861..9508348ca1 100644 --- a/actionpack/test/controller/cookie_test.rb +++ b/actionpack/test/controller/cookie_test.rb @@ -1,24 +1,24 @@ require 'abstract_unit' -class CookieTest < Test::Unit::TestCase +class CookieTest < ActionController::TestCase class TestController < ActionController::Base def authenticate cookies["user_name"] = "david" end def authenticate_for_fourteen_days - cookies["user_name"] = { "value" => "david", "expires" => Time.local(2005, 10, 10) } + cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) } end def authenticate_for_fourteen_days_with_symbols - cookies[:user_name] = { :value => "david", :expires => Time.local(2005, 10, 10) } + cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) } end def set_multiple_cookies - cookies["user_name"] = { "value" => "david", "expires" => Time.local(2005, 10, 10) } + cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) } cookies["login"] = "XJ-122" end - + def access_frozen_cookies cookies["will"] = "work" end @@ -36,57 +36,61 @@ class CookieTest < Test::Unit::TestCase cookies["user_name"] = { :value => "david", :http_only => true } end - def rescue_action(e) - raise unless ActionView::MissingTemplate # No templates here, and we don't care about the output + def rescue_action(e) + raise unless ActionView::MissingTemplate # No templates here, and we don't care about the output end end - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new + tests TestController - @controller = TestController.new + def setup @request.host = "www.nextangle.com" end def test_setting_cookie get :authenticate - assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], @response.headers["cookie"] + assert_equal ["user_name=david; path=/"], @response.headers["Set-Cookie"] + assert_equal({"user_name" => "david"}, @response.cookies) end def test_setting_cookie_for_fourteen_days get :authenticate_for_fourteen_days - assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], @response.headers["cookie"] + assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"] + assert_equal({"user_name" => "david"}, @response.cookies) end def test_setting_cookie_for_fourteen_days_with_symbols get :authenticate_for_fourteen_days_with_symbols - assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], @response.headers["cookie"] + assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"] + assert_equal({"user_name" => "david"}, @response.cookies) end def test_setting_cookie_with_http_only get :authenticate_with_http_only - assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "http_only" => true) ], @response.headers["cookie"] - assert_equal CGI::Cookie::new("name" => "user_name", "value" => "david", "path" => "/", "http_only" => true).to_s, @response.headers["cookie"][0].to_s + assert_equal ["user_name=david; path=/; HttpOnly"], @response.headers["Set-Cookie"] + assert_equal({"user_name" => "david"}, @response.cookies) end def test_multiple_cookies get :set_multiple_cookies assert_equal 2, @response.cookies.size + assert_equal "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", @response.headers["Set-Cookie"][0] + assert_equal "login=XJ-122; path=/", @response.headers["Set-Cookie"][1] + assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies) end def test_setting_test_cookie assert_nothing_raised { get :access_frozen_cookies } end - + def test_expiring_cookie get :logout - assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "", "expires" => Time.at(0)) ], @response.headers["cookie"] - assert_equal CGI::Cookie::new("name" => "user_name", "value" => "", "expires" => Time.at(0)).value, [] - end - + assert_equal ["user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"] + assert_equal({"user_name" => nil}, @response.cookies) + end + def test_cookiejar_accessor - @request.cookies["user_name"] = CGI::Cookie.new("name" => "user_name", "value" => "david", "expires" => Time.local(2025, 10, 10)) + @request.cookies["user_name"] = "david" @controller.request = @request jar = ActionController::CookieJar.new(@controller) assert_equal "david", jar["user_name"] @@ -94,53 +98,14 @@ class CookieTest < Test::Unit::TestCase end def test_cookiejar_accessor_with_array_value - a = %w{1 2 3} - @request.cookies["pages"] = CGI::Cookie.new("name" => "pages", "value" => a, "expires" => Time.local(2025, 10, 10)) + @request.cookies["pages"] = %w{1 2 3} @controller.request = @request jar = ActionController::CookieJar.new(@controller) - assert_equal a, jar["pages"] + assert_equal %w{1 2 3}, jar["pages"] end - + def test_delete_cookie_with_path get :delete_cookie_with_path - assert_equal "/beaten", @response.headers["cookie"].first.path - assert_not_equal "/", @response.headers["cookie"].first.path - end - - def test_cookie_to_s_simple_values - assert_equal 'myname=myvalue; path=', CGI::Cookie.new('myname', 'myvalue').to_s - end - - def test_cookie_to_s_hash - cookie_str = CGI::Cookie.new( - 'name' => 'myname', - 'value' => 'myvalue', - 'domain' => 'mydomain', - 'path' => 'mypath', - 'expires' => Time.utc(2007, 10, 20), - 'secure' => true, - 'http_only' => true).to_s - assert_equal 'myname=myvalue; domain=mydomain; path=mypath; expires=Sat, 20 Oct 2007 00:00:00 GMT; secure; HttpOnly', cookie_str - end - - def test_cookie_to_s_hash_default_not_secure_not_http_only - cookie_str = CGI::Cookie.new( - 'name' => 'myname', - 'value' => 'myvalue', - 'domain' => 'mydomain', - 'path' => 'mypath', - 'expires' => Time.utc(2007, 10, 20)) - assert cookie_str !~ /secure/ - assert cookie_str !~ /HttpOnly/ - end - - def test_cookies_should_not_be_split_on_ampersand_values - cookies = CGI::Cookie.parse('return_to=http://rubyonrails.org/search?term=api&scope=all&global=true') - assert_equal({"return_to" => ["http://rubyonrails.org/search?term=api&scope=all&global=true"]}, cookies) - end - - def test_cookies_should_not_be_split_on_values_with_newlines - cookies = CGI::Cookie.new("name" => "val", "value" => "this\nis\na\ntest") - assert cookies.size == 1 + assert_equal ["user_name=; path=/beaten; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"] end end diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb index 30dda87bb4..7cd4e71aa1 100644 --- a/actionpack/test/controller/dispatcher_test.rb +++ b/actionpack/test/controller/dispatcher_test.rb @@ -32,11 +32,6 @@ class DispatcherTest < Test::Unit::TestCase dispatch(false) end - def test_clears_asset_tag_cache_before_dispatch_if_in_loading_mode - ActionView::Helpers::AssetTagHelper::AssetTag::Cache.expects(:clear).once - dispatch(false) - end - def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode ActionController::Routing::Routes.expects(:reload).never ActiveSupport::Dependencies.expects(:clear).never @@ -50,7 +45,7 @@ class DispatcherTest < Test::Unit::TestCase end def test_failsafe_response - Dispatcher.any_instance.expects(:dispatch_unlocked).raises('b00m') + Dispatcher.any_instance.expects(:dispatch).raises('b00m') ActionController::Failsafe.any_instance.expects(:log_failsafe_exception) assert_nothing_raised do @@ -96,7 +91,7 @@ class DispatcherTest < Test::Unit::TestCase private def dispatch(cache_classes = true) - Dispatcher.any_instance.stubs(:handle_request).returns([200, {}, 'response']) + ActionController::Routing::RouteSet.any_instance.stubs(:call).returns([200, {}, 'response']) Dispatcher.define_dispatcher_callbacks(cache_classes) @dispatcher.call({}) end diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index dafa344473..e83fde2349 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -634,9 +634,11 @@ class FilterTest < Test::Unit::TestCase private def test_process(controller, action = "show") + ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest request = ActionController::TestRequest.new request.action = action - controller.process(request, ActionController::TestResponse.new) + controller = controller.new if controller.is_a?(Class) + controller.process_with_test(request, ActionController::TestResponse.new) end end @@ -874,8 +876,10 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase protected def test_process(controller, action = "show") + ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest request = ActionController::TestRequest.new request.action = action - controller.process(request, ActionController::TestResponse.new) + controller = controller.new if controller.is_a?(Class) + controller.process_with_test(request, ActionController::TestResponse.new) end end diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb index e562531bf3..d8a892811e 100644 --- a/actionpack/test/controller/flash_test.rb +++ b/actionpack/test/controller/flash_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class FlashTest < Test::Unit::TestCase +class FlashTest < ActionController::TestCase class TestController < ActionController::Base def set_flash flash["that"] = "hello" @@ -73,11 +73,7 @@ class FlashTest < Test::Unit::TestCase end end - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = TestController.new - end + tests TestController def test_flash get :set_flash diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb new file mode 100644 index 0000000000..d5c8636a9e --- /dev/null +++ b/actionpack/test/controller/http_digest_authentication_test.rb @@ -0,0 +1,73 @@ +require 'abstract_unit' + +class HttpDigestAuthenticationTest < Test::Unit::TestCase + include ActionController::HttpAuthentication::Digest + + class DummyController + attr_accessor :headers, :renders, :request, :response + + def initialize + @headers, @renders = {}, [] + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + request.session.session_id = "test_session" + end + + def render(options) + self.renderers << options + end + end + + def setup + @controller = DummyController.new + @credentials = { + :username => "dhh", + :realm => "testrealm@host.com", + :nonce => ActionController::HttpAuthentication::Digest.nonce(@controller.request), + :qop => "auth", + :nc => "00000001", + :cnonce => "0a4f113b", + :opaque => ActionController::HttpAuthentication::Digest.opaque(@controller.request), + :uri => "http://test.host/" + } + @encoded_credentials = ActionController::HttpAuthentication::Digest.encode_credentials("GET", @credentials, "secret") + end + + def test_decode_credentials + set_headers + assert_equal @credentials, decode_credentials(@controller.request) + end + + def test_nonce_format + assert_nothing_thrown do + validate_nonce(@controller.request, nonce(@controller.request)) + end + end + + def test_authenticate_should_raise_for_nil_password + set_headers ActionController::HttpAuthentication::Digest.encode_credentials(:get, @credentials, nil) + assert_raise ActionController::HttpAuthentication::Error do + authenticate(@controller, @credentials[:realm]) { |user| user == "dhh" && "secret" } + end + end + + def test_authenticate_should_raise_for_incorrect_password + set_headers + assert_raise ActionController::HttpAuthentication::Error do + authenticate(@controller, @credentials[:realm]) { |user| user == "dhh" && "bad password" } + end + end + + def test_authenticate_should_not_raise_for_correct_password + set_headers + assert_nothing_thrown do + authenticate(@controller, @credentials[:realm]) { |user| user == "dhh" && "secret" } + end + end + + private + def set_headers(value = @encoded_credentials, name = 'HTTP_AUTHORIZATION', method = "GET") + @controller.request.env[name] = value + @controller.request.env["REQUEST_METHOD"] = method + end +end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 4735b2927b..7ac9d97096 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -4,11 +4,29 @@ uses_mocha 'integration' do class SessionTest < Test::Unit::TestCase StubApp = lambda { |env| - [200, {"Content-Type" => "text/html"}, "Hello, World!"] + [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, "Hello, World!"] } def setup + @credentials = { + :username => "username", + :realm => "MyApp", + :nonce => ActionController::HttpAuthentication::Digest.nonce("session_id"), + :qop => "auth", + :nc => "00000001", + :cnonce => "0a4f113b", + :opaque => ActionController::HttpAuthentication::Digest.opaque("session_id"), + :uri => "/index" + } + @session = ActionController::Integration::Session.new(StubApp) + @session.nonce = @credentials[:nonce] + @session.opaque = @credentials[:opaque] + @session.realm = @credentials[:realm] + end + + def encoded_credentials(method) + ActionController::HttpAuthentication::Digest.encode_credentials(method, @credentials, "password") end def test_https_bang_works_and_sets_truth_by_default @@ -30,14 +48,6 @@ class SessionTest < Test::Unit::TestCase assert_raise(RuntimeError) { @session.follow_redirect! } end - def test_follow_redirect_calls_get_and_returns_status - @session.stubs(:redirect?).returns(true) - @session.stubs(:headers).returns({"location" => ["www.google.com"]}) - @session.stubs(:status).returns(200) - @session.expects(:get) - assert_equal 200, @session.follow_redirect! - end - def test_request_via_redirect_uses_given_method path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"} @session.expects(:put).with(path, args, headers) @@ -140,6 +150,76 @@ class SessionTest < Test::Unit::TestCase @session.head(path,params,headers) end + def test_get_with_basic + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => "Basic dXNlcm5hbWU6cGFzc3dvcmQ=\n") + @session.expects(:process).with(:get,path,params,expected_headers) + @session.get_with_basic(path,params,headers,'username','password') + end + + def test_post_with_basic + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => "Basic dXNlcm5hbWU6cGFzc3dvcmQ=\n") + @session.expects(:process).with(:post,path,params,expected_headers) + @session.post_with_basic(path,params,headers,'username','password') + end + + def test_put_with_basic + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => "Basic dXNlcm5hbWU6cGFzc3dvcmQ=\n") + @session.expects(:process).with(:put,path,params,expected_headers) + @session.put_with_basic(path,params,headers,'username','password') + end + + def test_delete_with_basic + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => "Basic dXNlcm5hbWU6cGFzc3dvcmQ=\n") + @session.expects(:process).with(:delete,path,params,expected_headers) + @session.delete_with_basic(path,params,headers,'username','password') + end + + def test_head_with_basic + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => "Basic dXNlcm5hbWU6cGFzc3dvcmQ=\n") + @session.expects(:process).with(:head,path,params,expected_headers) + @session.head_with_basic(path,params,headers,'username','password') + end + + def test_get_with_digest + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => encoded_credentials(:get)) + @session.expects(:process).with(:get,path,params,expected_headers) + @session.get_with_digest(path,params,headers,'username','password') + end + + def test_post_with_digest + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => encoded_credentials(:post)) + @session.expects(:process).with(:post,path,params,expected_headers) + @session.post_with_digest(path,params,headers,'username','password') + end + + def test_put_with_digest + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => encoded_credentials(:put)) + @session.expects(:process).with(:put,path,params,expected_headers) + @session.put_with_digest(path,params,headers,'username','password') + end + + def test_delete_with_digest + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => encoded_credentials(:delete)) + @session.expects(:process).with(:delete,path,params,expected_headers) + @session.delete_with_digest(path,params,headers,'username','password') + end + + def test_head_with_digest + path = "/index"; params = "blah"; headers = {:location => 'blah'} + expected_headers = headers.merge(:authorization => encoded_credentials(:head)) + @session.expects(:process).with(:head,path,params,expected_headers) + @session.head_with_digest(path,params,headers,'username','password') + end + def test_xml_http_request_get path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( @@ -239,8 +319,6 @@ end class IntegrationProcessTest < ActionController::IntegrationTest class IntegrationController < ActionController::Base - session :off - def get respond_to do |format| format.html { render :text => "OK", :status => 200 } @@ -323,6 +401,10 @@ class IntegrationProcessTest < ActionController::IntegrationTest assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body assert_kind_of HTML::Document, html_document assert_equal 1, request_count + + follow_redirect! + assert_response :success + assert_equal "/get", path end end @@ -379,4 +461,35 @@ class IntegrationProcessTest < ActionController::IntegrationTest end end +class MetalTest < ActionController::IntegrationTest + class Poller + def self.call(env) + if env["PATH_INFO"] =~ /^\/success/ + [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, "Hello World!"] + else + [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, ''] + end + end + end + + def setup + @integration_session = ActionController::Integration::Session.new(Poller) + end + + def test_successful_get + get "/success" + assert_response 200 + assert_response :success + assert_response :ok + assert_equal "Hello World!", response.body + end + + def test_failed_get + get "/failure" + assert_response 404 + assert_response :not_found + assert_equal '', response.body + end +end + end diff --git a/actionpack/test/controller/integration_upload_test.rb b/actionpack/test/controller/integration_upload_test.rb deleted file mode 100644 index b1dd6a6341..0000000000 --- a/actionpack/test/controller/integration_upload_test.rb +++ /dev/null @@ -1,41 +0,0 @@ -require 'abstract_unit' - -unless defined? ApplicationController - class ApplicationController < ActionController::Base - end -end - -class UploadTestController < ActionController::Base - session :off - - def update - SessionUploadTest.last_request_type = ActionController::Base.param_parsers[request.content_type] - render :text => "got here" - end -end - -class SessionUploadTest < ActionController::IntegrationTest - FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart' - - class << self - attr_accessor :last_request_type - end - - # def setup - # @session = ActionController::Integration::Session.new - # end - def test_post_with_upload - uses_mocha "test_post_with_upload" do - ActiveSupport::Dependencies.stubs(:load?).returns(false) - with_routing do |set| - set.draw do |map| - map.update 'update', :controller => "upload_test", :action => "update", :method => :post - end - - params = { :uploaded_data => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg") } - post '/update', params, :location => 'blah' - assert_equal(:multipart_form, SessionUploadTest.last_request_type) - end - end - end -end diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 18c01f755c..2f5e830fba 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -146,8 +146,7 @@ class LayoutExceptionRaised < ActionController::TestCase def test_exception_raised_when_layout_file_not_found @controller = SetsNonExistentLayoutFile.new get :hello - @response.template.class.module_eval { attr_accessor :exception } - assert_equal ActionView::MissingTemplate, @response.template.exception.class + assert_kind_of ActionView::MissingTemplate, @response.template.instance_eval { @exception } end end @@ -165,15 +164,17 @@ class LayoutStatusIsRenderedTest < ActionController::TestCase end end -class LayoutSymlinkedTest < LayoutTest - layout "symlinked/symlinked_layout" -end +unless RUBY_PLATFORM =~ /(:?mswin|mingw|bccwin)/ + class LayoutSymlinkedTest < LayoutTest + layout "symlinked/symlinked_layout" + end -class LayoutSymlinkedIsRenderedTest < ActionController::TestCase - def test_symlinked_layout_is_rendered - @controller = LayoutSymlinkedTest.new - get :hello - assert_response 200 - assert_equal "layouts/symlinked/symlinked_layout", @response.layout + class LayoutSymlinkedIsRenderedTest < ActionController::TestCase + def test_symlinked_layout_is_rendered + @controller = LayoutSymlinkedTest.new + get :hello + assert_response 200 + assert_equal "layouts/symlinked/symlinked_layout", @response.layout + end end end diff --git a/actionpack/test/controller/middleware_stack_test.rb b/actionpack/test/controller/middleware_stack_test.rb new file mode 100644 index 0000000000..5029f5f609 --- /dev/null +++ b/actionpack/test/controller/middleware_stack_test.rb @@ -0,0 +1,70 @@ +require 'abstract_unit' + +class MiddlewareStackTest < ActiveSupport::TestCase + class FooMiddleware; end + class BarMiddleware; end + class BazMiddleware; end + + def setup + @stack = ActionController::MiddlewareStack.new + @stack.use FooMiddleware + @stack.use BarMiddleware + end + + test "use should push middleware as class onto the stack" do + assert_difference "@stack.size" do + @stack.use BazMiddleware + end + assert_equal BazMiddleware, @stack.last.klass + end + + test "use should push middleware as a string onto the stack" do + assert_difference "@stack.size" do + @stack.use "MiddlewareStackTest::BazMiddleware" + end + assert_equal BazMiddleware, @stack.last.klass + end + + test "use should push middleware as a symbol onto the stack" do + assert_difference "@stack.size" do + @stack.use :"MiddlewareStackTest::BazMiddleware" + end + assert_equal BazMiddleware, @stack.last.klass + end + + test "use should push middleware class with arguments onto the stack" do + assert_difference "@stack.size" do + @stack.use BazMiddleware, true, :foo => "bar" + end + assert_equal BazMiddleware, @stack.last.klass + assert_equal([true, {:foo => "bar"}], @stack.last.args) + end + + test "insert inserts middleware at the integer index" do + @stack.insert(1, BazMiddleware) + assert_equal BazMiddleware, @stack[1].klass + end + + test "insert_after inserts middleware after the integer index" do + @stack.insert_after(1, BazMiddleware) + assert_equal BazMiddleware, @stack[2].klass + end + + test "insert_before inserts middleware before another middleware class" do + @stack.insert_before(BarMiddleware, BazMiddleware) + assert_equal BazMiddleware, @stack[1].klass + end + + test "insert_after inserts middleware after another middleware class" do + @stack.insert_after(BarMiddleware, BazMiddleware) + assert_equal BazMiddleware, @stack[2].klass + end + + test "active returns all only enabled middleware" do + assert_no_difference "@stack.active.size" do + assert_difference "@stack.size" do + @stack.use BazMiddleware, :if => lambda { false } + end + end + end +end diff --git a/actionpack/test/controller/mime_type_test.rb b/actionpack/test/controller/mime_type_test.rb index 21ae0419f1..c7faa621d9 100644 --- a/actionpack/test/controller/mime_type_test.rb +++ b/actionpack/test/controller/mime_type_test.rb @@ -81,4 +81,13 @@ class MimeTypeTest < Test::Unit::TestCase assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" } assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" } end + + def test_regexp_matcher + assert Mime::JS =~ "text/javascript" + assert Mime::JS =~ "application/javascript" + assert Mime::JS !~ "text/html" + assert !(Mime::JS !~ "text/javascript") + assert !(Mime::JS !~ "application/javascript") + assert Mime::HTML =~ 'application/xhtml+xml' + end end diff --git a/actionpack/test/controller/rack_test.rb b/actionpack/test/controller/rack_test.rb index 641ef9626e..8fd004a9e9 100644 --- a/actionpack/test/controller/rack_test.rb +++ b/actionpack/test/controller/rack_test.rb @@ -4,7 +4,7 @@ class BaseRackTest < Test::Unit::TestCase def setup @env = { "HTTP_MAX_FORWARDS" => "10", - "SERVER_NAME" => "glu.ttono.us:8007", + "SERVER_NAME" => "glu.ttono.us", "FCGI_ROLE" => "RESPONDER", "AUTH_TYPE" => "Basic", "HTTP_X_FORWARDED_HOST" => "glu.ttono.us", @@ -43,10 +43,10 @@ class BaseRackTest < Test::Unit::TestCase "REDIRECT_STATUS" => "200", "REQUEST_METHOD" => "GET" } - @request = ActionController::RackRequest.new(@env) + @request = ActionController::Request.new(@env) # some Nokia phone browsers omit the space after the semicolon separator. # some developers have grown accustomed to using comma in cookie values. - @alt_cookie_fmt_request = ActionController::RackRequest.new(@env.merge({"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"})) + @alt_cookie_fmt_request = ActionController::Request.new(@env.merge({"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"})) end def default_test; end @@ -145,7 +145,7 @@ class RackRequestTest < BaseRackTest assert_equal "kevin", @request.remote_user assert_equal :get, @request.request_method assert_equal "/dispatch.fcgi", @request.script_name - assert_equal "glu.ttono.us:8007", @request.server_name + assert_equal "glu.ttono.us", @request.server_name assert_equal 8007, @request.server_port assert_equal "HTTP/1.1", @request.server_protocol assert_equal "lighttpd", @request.server_software @@ -187,29 +187,6 @@ class RackRequestContentTypeTest < BaseRackTest end end -class RackRequestMethodTest < BaseRackTest - def test_get - assert_equal :get, @request.request_method - end - - def test_post - @request.env['REQUEST_METHOD'] = 'POST' - assert_equal :post, @request.request_method - end - - def test_put - set_content_data '_method=put' - - assert_equal :put, @request.request_method - end - - def test_delete - set_content_data '_method=delete' - - assert_equal :delete, @request.request_method - end -end - class RackRequestNeedsRewoundTest < BaseRackTest def test_body_should_be_rewound data = 'foo' @@ -218,7 +195,7 @@ class RackRequestNeedsRewoundTest < BaseRackTest @env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' # Read the request body by parsing params. - request = ActionController::RackRequest.new(@env) + request = ActionController::Request.new(@env) request.request_parameters # Should have rewound the body. @@ -229,15 +206,15 @@ end class RackResponseTest < BaseRackTest def setup super - @response = ActionController::RackResponse.new(@request) + @response = ActionController::Response.new end def test_simple_output @response.body = "Hello, World!" @response.prepare! - status, headers, body = @response.out - assert_equal "200 OK", status + status, headers, body = @response.to_a + assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "private, max-age=0, must-revalidate", @@ -257,53 +234,36 @@ class RackResponseTest < BaseRackTest end @response.prepare! - status, headers, body = @response.out - assert_equal "200 OK", status - assert_equal({"Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "no-cache", "Set-Cookie" => []}, headers) - - parts = [] - body.each { |part| parts << part } - assert_equal ["0", "1", "2", "3", "4"], parts - end - - def test_set_session_cookie - cookie = CGI::Cookie.new({"name" => "name", "value" => "Josh"}) - @request.cgi.send :instance_variable_set, '@output_cookies', [cookie] - - @response.body = "Hello, World!" - @response.prepare! - - status, headers, body = @response.out - assert_equal "200 OK", status + status, headers, body = @response.to_a + assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8", - "Cache-Control" => "private, max-age=0, must-revalidate", - "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"', - "Set-Cookie" => ["name=Josh; path="], - "Content-Length" => "13" + "Content-Length" => "", + "Cache-Control" => "no-cache", + "Set-Cookie" => [] }, headers) parts = [] body.each { |part| parts << part } - assert_equal ["Hello, World!"], parts + assert_equal ["0", "1", "2", "3", "4"], parts end end class RackResponseHeadersTest < BaseRackTest def setup super - @response = ActionController::RackResponse.new(@request) - @response.headers['Status'] = "200 OK" + @response = ActionController::Response.new + @response.status = "200 OK" end def test_content_type [204, 304].each do |c| - @response.headers['Status'] = c.to_s + @response.status = c.to_s assert !response_headers.has_key?("Content-Type"), "#{c} should not have Content-Type header" end [200, 302, 404, 500].each do |c| - @response.headers['Status'] = c.to_s + @response.status = c.to_s assert response_headers.has_key?("Content-Type"), "#{c} did not have Content-Type header" end end @@ -315,6 +275,6 @@ class RackResponseHeadersTest < BaseRackTest private def response_headers @response.prepare! - @response.out[1] + @response.to_a[1] end end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index c5496a9af5..8809aa7c34 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -21,6 +21,8 @@ class MockLogger end class TestController < ActionController::Base + protect_from_forgery + class LabellingFormBuilder < ActionView::Helpers::FormBuilder end @@ -79,6 +81,10 @@ class TestController < ActionController::Base render :action => "hello_world" end + def render_action_hello_world_as_string + render "hello_world" + end + def render_action_hello_world_with_symbol render :action => :hello_world end @@ -102,6 +108,12 @@ class TestController < ActionController::Base render :file => path end + def render_file_as_string_with_instance_variables + @secret = 'in the sauce' + path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) + render path + end + def render_file_not_using_full_path @secret = 'in the sauce' render :file => 'test/render_file_with_ivar' @@ -122,6 +134,11 @@ class TestController < ActionController::Base render :file => path, :locals => {:secret => 'in the sauce'} end + def render_file_as_string_with_locals + path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')) + render path, :locals => {:secret => 'in the sauce'} + end + def accessing_request_in_template render :inline => "Hello: <%= request.host %>" end @@ -180,10 +197,6 @@ class TestController < ActionController::Base render :text => "appended" end - def render_invalid_args - render("test/hello") - end - def render_vanilla_js_hello render :js => "alert('hello')" end @@ -193,6 +206,11 @@ class TestController < ActionController::Base render :template => "test/hello" end + def render_xml_hello_as_string_template + @name = "David" + render "test/hello" + end + def render_xml_with_custom_content_type render :xml => "<blah/>", :content_type => "application/atomsvc+xml" end @@ -209,6 +227,10 @@ class TestController < ActionController::Base # let's just rely on the template end + def blank_response + render :text => ' ' + end + def layout_test render :action => "hello_world" end @@ -278,6 +300,14 @@ class TestController < ActionController::Base render :action => "hello_world", :layout => "standard" end + def layout_test_with_different_layout_and_string_action + render "hello_world", :layout => "standard" + end + + def layout_test_with_different_layout_and_symbol_action + render :hello_world, :layout => "standard" + end + def rendering_without_layout render :action => "hello_world", :layout => false end @@ -319,6 +349,10 @@ class TestController < ActionController::Base render :template => "test/hello_world" end + def render_with_explicit_string_template + render "test/hello_world" + end + def render_with_explicit_template_with_locals render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' } end @@ -641,6 +675,7 @@ class TestController < ActionController::Base "accessing_params_in_template", "accessing_params_in_template_with_layout", "render_with_explicit_template", + "render_with_explicit_string_template", "render_js_with_explicit_template", "render_js_with_explicit_action_template", "delete_with_js", "update_page", "update_page_with_instance_variables" @@ -720,6 +755,12 @@ class RenderTest < ActionController::TestCase assert_template "test/hello_world" end + def test_render_action_hello_world_as_string + get :render_action_hello_world_as_string + assert_equal "Hello world!", @response.body + assert_template "test/hello_world" + end + def test_render_action_with_symbol get :render_action_hello_world_with_symbol assert_template "test/hello_world" @@ -745,6 +786,11 @@ class RenderTest < ActionController::TestCase assert_equal "The secret is in the sauce\n", @response.body end + def test_render_file_as_string_with_instance_variables + get :render_file_as_string_with_instance_variables + assert_equal "The secret is in the sauce\n", @response.body + end + def test_render_file_not_using_full_path get :render_file_not_using_full_path assert_equal "The secret is in the sauce\n", @response.body @@ -760,6 +806,11 @@ class RenderTest < ActionController::TestCase assert_equal "The secret is in the sauce\n", @response.body end + def test_render_file_as_string_with_locals + get :render_file_as_string_with_locals + assert_equal "The secret is in the sauce\n", @response.body + end + def test_render_file_from_template get :render_file_from_template assert_equal "The secret is in the sauce\n", @response.body @@ -825,10 +876,6 @@ class RenderTest < ActionController::TestCase assert_equal 'appended', @response.body end - def test_attempt_to_render_with_invalid_arguments - assert_raises(ActionController::RenderError) { get :render_invalid_args } - end - def test_attempt_to_access_object_method assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } end @@ -869,6 +916,12 @@ class RenderTest < ActionController::TestCase assert_equal "application/xml", @response.content_type end + def test_render_xml_as_string_template + get :render_xml_hello_as_string_template + assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body + assert_equal "application/xml", @response.content_type + end + def test_render_xml_with_default get :greeting assert_equal "<p>This is grand!</p>\n", @response.body @@ -1008,6 +1061,16 @@ class RenderTest < ActionController::TestCase assert_equal "<html>Hello world!</html>", @response.body end + def test_layout_test_with_different_layout_and_string_action + get :layout_test_with_different_layout_and_string_action + assert_equal "<html>Hello world!</html>", @response.body + end + + def test_layout_test_with_different_layout_and_symbol_action + get :layout_test_with_different_layout_and_symbol_action + assert_equal "<html>Hello world!</html>", @response.body + end + def test_rendering_without_layout get :rendering_without_layout assert_equal "Hello world!", @response.body @@ -1054,6 +1117,11 @@ class RenderTest < ActionController::TestCase assert_response :success end + def test_render_with_explicit_string_template + get :render_with_explicit_string_template + assert_equal "<html>Hello world!</html>", @response.body + end + def test_double_render assert_raises(ActionController::DoubleRenderError) { get :double_render } end @@ -1095,14 +1163,14 @@ class RenderTest < ActionController::TestCase def test_update_page get :update_page assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] + assert_equal 'text/javascript; charset=utf-8', @response.headers['Content-Type'] assert_equal 2, @response.body.split($/).length end def test_update_page_with_instance_variables get :update_page_with_instance_variables assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] + assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"] assert_match /balance/, @response.body assert_match /\$37/, @response.body end @@ -1110,7 +1178,7 @@ class RenderTest < ActionController::TestCase def test_update_page_with_view_method get :update_page_with_view_method assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] + assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"] assert_match /2 people/, @response.body end @@ -1143,13 +1211,18 @@ class RenderTest < ActionController::TestCase def test_head_with_symbolic_status get :head_with_symbolic_status, :status => "ok" - assert_equal "200 OK", @response.headers["Status"] + assert_equal "200 OK", @response.status assert_response :ok get :head_with_symbolic_status, :status => "not_found" - assert_equal "404 Not Found", @response.headers["Status"] + assert_equal "404 Not Found", @response.status assert_response :not_found + get :head_with_symbolic_status, :status => "no_content" + assert_equal "204 No Content", @response.status + assert !@response.headers.include?('Content-Length') + assert_response :no_content + ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code| get :head_with_symbolic_status, :status => status.to_s assert_equal code, @response.response_code @@ -1310,21 +1383,28 @@ class RenderTest < ActionController::TestCase def test_partial_collection_with_spacer get :partial_collection_with_spacer assert_equal "Hello: davidonly partialHello: mary", @response.body + assert_template :partial => 'test/_partial_only' + assert_template :partial => '_customer' end def test_partial_collection_shorthand_with_locals get :partial_collection_shorthand_with_locals assert_equal "Bonjour: davidBonjour: mary", @response.body + assert_template :partial => 'customers/_customer', :count => 2 + assert_template :partial => '_completely_fake_and_made_up_template_that_cannot_possibly_be_rendered', :count => 0 end def test_partial_collection_shorthand_with_different_types_of_records get :partial_collection_shorthand_with_different_types_of_records assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body + assert_template :partial => 'good_customers/_good_customer', :count => 3 + assert_template :partial => 'bad_customers/_bad_customer', :count => 3 end def test_empty_partial_collection get :empty_partial_collection assert_equal " ", @response.body + assert_template :partial => false end def test_partial_with_hash_object @@ -1374,6 +1454,11 @@ class EtagRenderTest < ActionController::TestCase @expected_bang_etag = etag_for(expand_key([:foo, 123])) end + def test_render_blank_body_shouldnt_set_etag + get :blank_response + assert !@response.etag? + end + def test_render_200_should_set_etag get :render_hello_world_from_variable assert_equal etag_for("hello david"), @response.headers['ETag'] @@ -1390,7 +1475,7 @@ class EtagRenderTest < ActionController::TestCase def test_render_against_etag_request_should_have_no_content_length_when_match @request.if_none_match = etag_for("hello david") get :render_hello_world_from_variable - assert !@response.headers.has_key?("Content-Length") + assert !@response.headers.has_key?("Content-Length"), @response.headers['Content-Length'] end def test_render_against_etag_request_should_200_when_no_match diff --git a/actionpack/test/controller/request/json_params_parsing_test.rb b/actionpack/test/controller/request/json_params_parsing_test.rb new file mode 100644 index 0000000000..a3dde72c4e --- /dev/null +++ b/actionpack/test/controller/request/json_params_parsing_test.rb @@ -0,0 +1,45 @@ +require 'abstract_unit' + +class JsonParamsParsingTest < ActionController::IntegrationTest + class TestController < ActionController::Base + class << self + attr_accessor :last_request_parameters + end + + def parse + self.class.last_request_parameters = request.request_parameters + head :ok + end + end + + def teardown + TestController.last_request_parameters = nil + end + + test "parses json params for application json" do + assert_parses( + {"person" => {"name" => "David"}}, + "{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/json' } + ) + end + + test "parses json params for application jsonrequest" do + assert_parses( + {"person" => {"name" => "David"}}, + "{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/jsonrequest' } + ) + end + + private + def assert_parses(expected, actual, headers = {}) + with_routing do |set| + set.draw do |map| + map.connect ':action', :controller => "json_params_parsing_test/test" + end + + post "/parse", actual, headers + assert_response :ok + assert_equal(expected, TestController.last_request_parameters) + end + end +end diff --git a/actionpack/test/controller/request/multipart_params_parsing_test.rb b/actionpack/test/controller/request/multipart_params_parsing_test.rb new file mode 100644 index 0000000000..03ab164972 --- /dev/null +++ b/actionpack/test/controller/request/multipart_params_parsing_test.rb @@ -0,0 +1,167 @@ +require 'abstract_unit' + +class MultipartParamsParsingTest < ActionController::IntegrationTest + class TestController < ActionController::Base + class << self + attr_accessor :last_request_parameters, :last_request_type + end + + def parse + self.class.last_request_type = ActionController::Base.param_parsers[request.content_type] + self.class.last_request_parameters = request.request_parameters + head :ok + end + + def read + render :text => "File: #{params[:uploaded_data].read}" + end + end + + FIXTURE_PATH = File.dirname(__FILE__) + '/../../fixtures/multipart' + + def teardown + TestController.last_request_parameters = nil + TestController.last_request_type = nil + end + + test "parses single parameter" do + assert_equal({ 'foo' => 'bar' }, parse_multipart('single_parameter')) + end + + test "parses bracketed parameters" do + assert_equal({ 'foo' => { 'baz' => 'bar'}}, parse_multipart('bracketed_param')) + end + + test "parses text file" do + params = parse_multipart('text_file') + assert_equal %w(file foo), params.keys.sort + assert_equal 'bar', params['foo'] + + file = params['file'] + assert_kind_of StringIO, file + assert_equal 'file.txt', file.original_filename + assert_equal "text/plain", file.content_type + assert_equal 'contents', file.read + end + + test "parses boundary problem file" do + params = parse_multipart('boundary_problem_file') + assert_equal %w(file foo), params.keys.sort + + file = params['file'] + foo = params['foo'] + + assert_kind_of Tempfile, file + + assert_equal 'file.txt', file.original_filename + assert_equal "text/plain", file.content_type + + assert_equal 'bar', foo + end + + test "parses large text file" do + params = parse_multipart('large_text_file') + assert_equal %w(file foo), params.keys.sort + assert_equal 'bar', params['foo'] + + file = params['file'] + + assert_kind_of Tempfile, file + + assert_equal 'file.txt', file.original_filename + assert_equal "text/plain", file.content_type + assert ('a' * 20480) == file.read + end + + test "parses binary file" do + params = parse_multipart('binary_file') + assert_equal %w(file flowers foo), params.keys.sort + assert_equal 'bar', params['foo'] + + file = params['file'] + assert_kind_of StringIO, file + assert_equal 'file.csv', file.original_filename + assert_nil file.content_type + assert_equal 'contents', file.read + + file = params['flowers'] + assert_kind_of StringIO, file + assert_equal 'flowers.jpg', file.original_filename + assert_equal "image/jpeg", file.content_type + assert_equal 19512, file.size + end + + test "parses mixed files" do + params = parse_multipart('mixed_files') + assert_equal %w(files foo), params.keys.sort + assert_equal 'bar', params['foo'] + + # Ruby CGI doesn't handle multipart/mixed for us. + files = params['files'] + assert_kind_of String, files + files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding) + assert_equal 19756, files.size + end + + test "uploads and parses parameters" do + with_test_routing do + params = { :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/mona_lisa.jpg", "image/jpg") } + post '/parse', params, :location => 'blah' + assert_equal(:multipart_form, TestController.last_request_type) + end + end + + test "uploads and reads file" do + with_test_routing do + post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain") + assert_equal "File: Hello", response.body + end + end + + # The lint wrapper is used in integration tests + # instead of a normal StringIO class + InputWrapper = Rack::Lint::InputWrapper + + test "parses unwindable stream" do + InputWrapper.any_instance.expects(:rewind).raises(Errno::ESPIPE) + params = parse_multipart('large_text_file') + assert_equal %w(file foo), params.keys.sort + assert_equal 'bar', params['foo'] + end + + test "uploads and reads file with unwindable input" do + InputWrapper.any_instance.expects(:rewind).raises(Errno::ESPIPE) + + with_test_routing do + post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain") + assert_equal "File: Hello", response.body + end + end + + private + def fixture(name) + File.open(File.join(FIXTURE_PATH, name), 'rb') do |file| + { "rack.input" => file.read, + "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", + "CONTENT_LENGTH" => file.stat.size.to_s } + end + end + + def parse_multipart(name) + with_test_routing do + headers = fixture(name) + post "/parse", headers.delete("rack.input"), headers + assert_response :ok + TestController.last_request_parameters + end + end + + def with_test_routing + with_routing do |set| + set.draw do |map| + map.connect ':action', :controller => "multipart_params_parsing_test/test" + end + yield + end + end +end diff --git a/actionpack/test/controller/request/query_string_parsing_test.rb b/actionpack/test/controller/request/query_string_parsing_test.rb new file mode 100644 index 0000000000..a31e326ddf --- /dev/null +++ b/actionpack/test/controller/request/query_string_parsing_test.rb @@ -0,0 +1,120 @@ +require 'abstract_unit' + +class QueryStringParsingTest < ActionController::IntegrationTest + class TestController < ActionController::Base + class << self + attr_accessor :last_query_parameters + end + + def parse + self.class.last_query_parameters = request.query_parameters + head :ok + end + end + + def teardown + TestController.last_query_parameters = nil + end + + test "query string" do + assert_parses( + {"action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"}, + "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1" + ) + end + + test "deep query string" do + assert_parses( + {'x' => {'y' => {'z' => '10'}}}, + "x[y][z]=10" + ) + end + + test "deep query string with array" do + assert_parses({'x' => {'y' => {'z' => ['10']}}}, 'x[y][z][]=10') + assert_parses({'x' => {'y' => {'z' => ['10', '5']}}}, 'x[y][z][]=10&x[y][z][]=5') + end + + test "deep query string with array of hash" do + assert_parses({'x' => {'y' => [{'z' => '10'}]}}, 'x[y][][z]=10') + assert_parses({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, 'x[y][][z]=10&x[y][][w]=10') + assert_parses({'x' => {'y' => [{'z' => '10', 'v' => {'w' => '10'}}]}}, 'x[y][][z]=10&x[y][][v][w]=10') + end + + test "deep query string with array of hashes with one pair" do + assert_parses({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, 'x[y][][z]=10&x[y][][z]=20') + end + + test "deep query string with array of hashes with multiple pairs" do + assert_parses( + {'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}}, + 'x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b' + ) + end + + test "query string with nil" do + assert_parses( + { "action" => "create_customer", "full_name" => ''}, + "action=create_customer&full_name=" + ) + end + + test "query string with array" do + assert_parses( + { "action" => "create_customer", "selected" => ["1", "2", "3"]}, + "action=create_customer&selected[]=1&selected[]=2&selected[]=3" + ) + end + + test "query string with amps" do + assert_parses( + { "action" => "create_customer", "name" => "Don't & Does"}, + "action=create_customer&name=Don%27t+%26+Does" + ) + end + + test "query string with many equal" do + assert_parses( + { "action" => "create_customer", "full_name" => "abc=def=ghi"}, + "action=create_customer&full_name=abc=def=ghi" + ) + end + + test "query string without equal" do + assert_parses({ "action" => nil }, "action") + end + + test "query string with empty key" do + assert_parses( + { "action" => "create_customer", "full_name" => "David Heinemeier Hansson" }, + "action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save" + ) + end + + test "query string with many ampersands" do + assert_parses( + { "action" => "create_customer", "full_name" => "David Heinemeier Hansson"}, + "&action=create_customer&&&full_name=David%20Heinemeier%20Hansson" + ) + end + + test "unbalanced query string with array" do + assert_parses( + {'location' => ["1", "2"], 'age_group' => ["2"]}, + "location[]=1&location[]=2&age_group[]=2" + ) + end + + private + def assert_parses(expected, actual) + with_routing do |set| + set.draw do |map| + map.connect ':action', :controller => "query_string_parsing_test/test" + end + + get "/parse", actual + assert_response :ok + assert_equal(expected, TestController.last_query_parameters) + end + end +end diff --git a/actionpack/test/controller/request/xml_params_parsing_test.rb b/actionpack/test/controller/request/xml_params_parsing_test.rb new file mode 100644 index 0000000000..ee764e726e --- /dev/null +++ b/actionpack/test/controller/request/xml_params_parsing_test.rb @@ -0,0 +1,88 @@ +require 'abstract_unit' + +class XmlParamsParsingTest < ActionController::IntegrationTest + class TestController < ActionController::Base + class << self + attr_accessor :last_request_parameters + end + + def parse + self.class.last_request_parameters = request.request_parameters + head :ok + end + end + + def teardown + TestController.last_request_parameters = nil + end + + test "parses hash params" do + with_test_routing do + xml = "<person><name>David</name></person>" + post "/parse", xml, default_headers + assert_response :ok + assert_equal({"person" => {"name" => "David"}}, TestController.last_request_parameters) + end + end + + test "parses single file" do + with_test_routing do + xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></person>" + post "/parse", xml, default_headers + assert_response :ok + + person = TestController.last_request_parameters + assert_equal "image/jpg", person['person']['avatar'].content_type + assert_equal "me.jpg", person['person']['avatar'].original_filename + assert_equal "ABC", person['person']['avatar'].read + end + end + + test "parses multiple files" do + xml = <<-end_body + <person> + <name>David</name> + <avatars> + <avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar> + <avatar type='file' name='you.gif' content_type='image/gif'>#{ActiveSupport::Base64.encode64('DEF')}</avatar> + </avatars> + </person> + end_body + + with_test_routing do + post "/parse", xml, default_headers + assert_response :ok + end + + person = TestController.last_request_parameters + + assert_equal "image/jpg", person['person']['avatars']['avatar'].first.content_type + assert_equal "me.jpg", person['person']['avatars']['avatar'].first.original_filename + assert_equal "ABC", person['person']['avatars']['avatar'].first.read + + assert_equal "image/gif", person['person']['avatars']['avatar'].last.content_type + assert_equal "you.gif", person['person']['avatars']['avatar'].last.original_filename + assert_equal "DEF", person['person']['avatars']['avatar'].last.read + end + + private + def with_test_routing + with_routing do |set| + set.draw do |map| + map.connect ':action', :controller => "xml_params_parsing_test/test" + end + yield + end + end + + def default_headers + {'CONTENT_TYPE' => 'application/xml'} + end +end + +class LegacyXmlParamsParsingTest < XmlParamsParsingTest + private + def default_headers + {'HTTP_X_POST_DATA_FORMAT' => 'xml'} + end +end diff --git a/actionpack/test/controller/request_test.rb b/actionpack/test/controller/request_test.rb index 71da50fab0..3256774b6d 100644 --- a/actionpack/test/controller/request_test.rb +++ b/actionpack/test/controller/request_test.rb @@ -303,18 +303,16 @@ class RequestTest < ActiveSupport::TestCase end def test_allow_method_hacking_on_post - self.request_method = :post [:get, :head, :options, :put, :post, :delete].each do |method| - @request.instance_eval { @parameters = { :_method => method.to_s } ; @request_method = nil } + self.request_method = method @request.request_method(true) assert_equal(method == :head ? :get : method, @request.method) end end def test_invalid_method_hacking_on_post_raises_exception - self.request_method = :post - @request.instance_eval { @parameters = { :_method => :random_method } ; @request_method = nil } assert_raises(ActionController::UnknownHttpMethod) do + self.request_method = :_random_method @request.request_method(true) end end @@ -393,8 +391,8 @@ class RequestTest < ActiveSupport::TestCase end def test_parameters - @request.instance_eval { @request_parameters = { "foo" => 1 } } - @request.instance_eval { @query_parameters = { "bar" => 2 } } + @request.stubs(:request_parameters).returns({ "foo" => 1 }) + @request.stubs(:query_parameters).returns({ "bar" => 2 }) assert_equal({"foo" => 1, "bar" => 2}, @request.parameters) assert_equal({"foo" => 1}, @request.request_parameters) @@ -409,113 +407,10 @@ class RequestTest < ActiveSupport::TestCase end class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase - def setup - @query_string = "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1" - @query_string_with_empty = "action=create_customer&full_name=" - @query_string_with_array = "action=create_customer&selected[]=1&selected[]=2&selected[]=3" - @query_string_with_amps = "action=create_customer&name=Don%27t+%26+Does" - @query_string_with_multiple_of_same_name = - "action=update_order&full_name=Lau%20Taarnskov&products=4&products=2&products=3" - @query_string_with_many_equal = "action=create_customer&full_name=abc=def=ghi" - @query_string_without_equal = "action" - @query_string_with_many_ampersands = - "&action=create_customer&&&full_name=David%20Heinemeier%20Hansson" - @query_string_with_empty_key = "action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save" - end - - def test_query_string - assert_equal( - { "action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"}, - ActionController::AbstractRequest.parse_query_parameters(@query_string) - ) - end - - def test_deep_query_string - expected = {'x' => {'y' => {'z' => '10'}}} - assert_equal(expected, ActionController::AbstractRequest.parse_query_parameters('x[y][z]=10')) - end - - def test_deep_query_string_with_array - assert_equal({'x' => {'y' => {'z' => ['10']}}}, ActionController::AbstractRequest.parse_query_parameters('x[y][z][]=10')) - assert_equal({'x' => {'y' => {'z' => ['10', '5']}}}, ActionController::AbstractRequest.parse_query_parameters('x[y][z][]=10&x[y][z][]=5')) - end - - def test_deep_query_string_with_array_of_hash - assert_equal({'x' => {'y' => [{'z' => '10'}]}}, ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10')) - assert_equal({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][w]=10')) - end - - def test_deep_query_string_with_array_of_hashes_with_one_pair - assert_equal({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][z]=20')) - assert_equal("10", ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][z]=20')["x"]["y"].first["z"]) - assert_equal("10", ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][z]=20').with_indifferent_access[:x][:y].first[:z]) - end - - def test_deep_query_string_with_array_of_hashes_with_multiple_pairs - assert_equal( - {'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}}, - ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b') - ) - end - - def test_query_string_with_nil - assert_equal( - { "action" => "create_customer", "full_name" => ''}, - ActionController::AbstractRequest.parse_query_parameters(@query_string_with_empty) - ) - end - - def test_query_string_with_array - assert_equal( - { "action" => "create_customer", "selected" => ["1", "2", "3"]}, - ActionController::AbstractRequest.parse_query_parameters(@query_string_with_array) - ) - end - - def test_query_string_with_amps - assert_equal( - { "action" => "create_customer", "name" => "Don't & Does"}, - ActionController::AbstractRequest.parse_query_parameters(@query_string_with_amps) - ) - end - - def test_query_string_with_many_equal - assert_equal( - { "action" => "create_customer", "full_name" => "abc=def=ghi"}, - ActionController::AbstractRequest.parse_query_parameters(@query_string_with_many_equal) - ) - end - - def test_query_string_without_equal - assert_equal( - { "action" => nil }, - ActionController::AbstractRequest.parse_query_parameters(@query_string_without_equal) - ) - end - - def test_query_string_with_empty_key - assert_equal( - { "action" => "create_customer", "full_name" => "David Heinemeier Hansson" }, - ActionController::AbstractRequest.parse_query_parameters(@query_string_with_empty_key) - ) - end - - def test_query_string_with_many_ampersands - assert_equal( - { "action" => "create_customer", "full_name" => "David Heinemeier Hansson"}, - ActionController::AbstractRequest.parse_query_parameters(@query_string_with_many_ampersands) - ) - end - def test_unbalanced_query_string_with_array assert_equal( {'location' => ["1", "2"], 'age_group' => ["2"]}, - ActionController::AbstractRequest.parse_query_parameters("location[]=1&location[]=2&age_group[]=2") - ) - assert_equal( - {'location' => ["1", "2"], 'age_group' => ["2"]}, - ActionController::AbstractRequest.parse_request_parameters({'location[]' => ["1", "2"], - 'age_group[]' => ["2"]}) + ActionController::RequestParser.parse_request_parameters({'location[]' => ["1", "2"], 'age_group[]' => ["2"]}) ) end @@ -527,7 +422,7 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase expected = { "note" => { "viewers"=>{"viewer"=>[{ "id"=>"1", "type"=>"User"}, {"type"=>"Group", "id"=>"2"} ]} } } - assert_equal(expected, ActionController::AbstractRequest.parse_request_parameters(query)) + assert_equal(expected, ActionController::RequestParser.parse_request_parameters(query)) end def test_parse_params @@ -566,7 +461,7 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase } } - assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected_output, ActionController::RequestParser.parse_request_parameters(input) end UploadedStringIO = ActionController::UploadedStringIO @@ -621,7 +516,7 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase "text_part" => "abc" } - params = ActionController::AbstractRequest.parse_request_parameters(input) + params = ActionController::RequestParser.parse_request_parameters(input) assert_equal expected_output, params # Lone filenames are preserved. @@ -652,7 +547,7 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase "logo" => File.new(File.dirname(__FILE__) + "/rack_test.rb").path, } - assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected_output, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_array @@ -660,234 +555,54 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase expected_output = { "selected" => [ "1", "2", "3" ] } - assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected_output, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_non_alphanumeric_name input = { "a/b[c]" => %w(d) } expected = { "a/b" => { "c" => "d" }} - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_single_brackets_in_middle input = { "a/b[c]d" => %w(e) } expected = { "a/b" => {} } - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_separated_brackets input = { "a/b@[c]d[e]" => %w(f) } expected = { "a/b@" => { }} - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_separated_brackets_and_array input = { "a/b@[c]d[e][]" => %w(f) } expected = { "a/b@" => { }} - assert_equal expected , ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected , ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_unmatched_brackets_and_array input = { "a/b@[c][d[e][]" => %w(f) } expected = { "a/b@" => { "c" => { }}} - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_nil_key input = { nil => nil, "test2" => %w(value1) } expected = { "test2" => "value1" } - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_array_prefix_and_hashes input = { "a[][b][c]" => %w(d) } expected = {"a" => [{"b" => {"c" => "d"}}]} - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end def test_parse_params_with_complex_nesting input = { "a[][b][c][][d][]" => %w(e) } expected = {"a" => [{"b" => {"c" => [{"d" => ["e"]}]}}]} - assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input) - end -end - -class MultipartRequestParameterParsingTest < ActiveSupport::TestCase - FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart' - - def test_single_parameter - params = parse_multipart('single_parameter') - assert_equal({ 'foo' => 'bar' }, params) - end - - def test_bracketed_param - assert_equal({ 'foo' => { 'baz' => 'bar'}}, parse_multipart('bracketed_param')) - end - - def test_text_file - params = parse_multipart('text_file') - assert_equal %w(file foo), params.keys.sort - assert_equal 'bar', params['foo'] - - file = params['file'] - assert_kind_of StringIO, file - assert_equal 'file.txt', file.original_filename - assert_equal "text/plain", file.content_type - assert_equal 'contents', file.read - end - - def test_boundary_problem_file - params = parse_multipart('boundary_problem_file') - assert_equal %w(file foo), params.keys.sort - - file = params['file'] - foo = params['foo'] - - assert_kind_of Tempfile, file - - assert_equal 'file.txt', file.original_filename - assert_equal "text/plain", file.content_type - - assert_equal 'bar', foo - end - - def test_large_text_file - params = parse_multipart('large_text_file') - assert_equal %w(file foo), params.keys.sort - assert_equal 'bar', params['foo'] - - file = params['file'] - - assert_kind_of Tempfile, file - - assert_equal 'file.txt', file.original_filename - assert_equal "text/plain", file.content_type - assert ('a' * 20480) == file.read - end - - uses_mocha "test_no_rewind_stream" do - def test_no_rewind_stream - # Ensures that parse_multipart_form_parameters works with streams that cannot be rewound - file = File.open(File.join(FIXTURE_PATH, 'large_text_file'), 'rb') - file.expects(:rewind).raises(Errno::ESPIPE) - params = ActionController::AbstractRequest.parse_multipart_form_parameters(file, 'AaB03x', file.stat.size, {}) - assert_not_equal 0, file.pos # file was not rewound after reading - end - end - - def test_binary_file - params = parse_multipart('binary_file') - assert_equal %w(file flowers foo), params.keys.sort - assert_equal 'bar', params['foo'] - - file = params['file'] - assert_kind_of StringIO, file - assert_equal 'file.csv', file.original_filename - assert_nil file.content_type - assert_equal 'contents', file.read - - file = params['flowers'] - assert_kind_of StringIO, file - assert_equal 'flowers.jpg', file.original_filename - assert_equal "image/jpeg", file.content_type - assert_equal 19512, file.size - #assert_equal File.read(File.dirname(__FILE__) + '/../../../activerecord/test/fixtures/flowers.jpg'), file.read - end - - def test_mixed_files - params = parse_multipart('mixed_files') - assert_equal %w(files foo), params.keys.sort - assert_equal 'bar', params['foo'] - - # Ruby CGI doesn't handle multipart/mixed for us. - files = params['files'] - assert_kind_of String, files - files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding) - assert_equal 19756, files.size - end - - private - def parse_multipart(name) - File.open(File.join(FIXTURE_PATH, name), 'rb') do |file| - params = ActionController::AbstractRequest.parse_multipart_form_parameters(file, 'AaB03x', file.stat.size, {}) - assert_equal 0, file.pos # file was rewound after reading - params - end - end -end - -class XmlParamsParsingTest < ActiveSupport::TestCase - def test_hash_params - person = parse_body("<person><name>David</name></person>")[:person] - assert_kind_of Hash, person - assert_equal 'David', person['name'] - end - - def test_single_file - person = parse_body("<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></person>") - - assert_equal "image/jpg", person['person']['avatar'].content_type - assert_equal "me.jpg", person['person']['avatar'].original_filename - assert_equal "ABC", person['person']['avatar'].read - end - - def test_multiple_files - person = parse_body(<<-end_body) - <person> - <name>David</name> - <avatars> - <avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar> - <avatar type='file' name='you.gif' content_type='image/gif'>#{ActiveSupport::Base64.encode64('DEF')}</avatar> - </avatars> - </person> - end_body - - assert_equal "image/jpg", person['person']['avatars']['avatar'].first.content_type - assert_equal "me.jpg", person['person']['avatars']['avatar'].first.original_filename - assert_equal "ABC", person['person']['avatars']['avatar'].first.read - - assert_equal "image/gif", person['person']['avatars']['avatar'].last.content_type - assert_equal "you.gif", person['person']['avatars']['avatar'].last.original_filename - assert_equal "DEF", person['person']['avatars']['avatar'].last.read - end - - private - def parse_body(body) - env = { 'rack.input' => StringIO.new(body), - 'CONTENT_TYPE' => 'application/xml', - 'CONTENT_LENGTH' => body.size.to_s } - ActionController::RackRequest.new(env).request_parameters - end -end - -class LegacyXmlParamsParsingTest < XmlParamsParsingTest - private - def parse_body(body) - env = { 'rack.input' => StringIO.new(body), - 'HTTP_X_POST_DATA_FORMAT' => 'xml', - 'CONTENT_LENGTH' => body.size.to_s } - ActionController::RackRequest.new(env).request_parameters - end -end - -class JsonParamsParsingTest < ActiveSupport::TestCase - def test_hash_params_for_application_json - person = parse_body({:person => {:name => "David"}}.to_json,'application/json')[:person] - assert_kind_of Hash, person - assert_equal 'David', person['name'] - end - - def test_hash_params_for_application_jsonrequest - person = parse_body({:person => {:name => "David"}}.to_json,'application/jsonrequest')[:person] - assert_kind_of Hash, person - assert_equal 'David', person['name'] + assert_equal expected, ActionController::RequestParser.parse_request_parameters(input) end - - private - def parse_body(body,content_type) - env = { 'rack.input' => StringIO.new(body), - 'CONTENT_TYPE' => content_type, - 'CONTENT_LENGTH' => body.size.to_s } - ActionController::RackRequest.new(env).request_parameters - end end diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 63f9827f4a..9f6b45f065 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -67,6 +67,11 @@ class RescueController < ActionController::Base render :text => 'no way' end + before_filter(:only => :before_filter_raises) { raise 'umm nice' } + + def before_filter_raises + end + def raises render :text => 'already rendered' raise "don't panic!" @@ -154,6 +159,16 @@ class RescueControllerTest < ActionController::TestCase end end + def test_rescue_exceptions_raised_by_filters + with_rails_root FIXTURE_PUBLIC do + with_all_requests_local false do + get :before_filter_raises + end + end + + assert_response :internal_server_error + end + def test_rescue_action_locally_if_all_requests_local @controller.expects(:local_request?).never @controller.expects(:rescue_action_locally).with(@exception) @@ -367,10 +382,21 @@ class RescueControllerTest < ActionController::TestCase end def test_rescue_dispatcher_exceptions - RescueController.process_with_exception(@request, @response, ActionController::RoutingError.new("Route not found")) + env = @request.env + env["action_controller.rescue.request"] = @request + env["action_controller.rescue.response"] = @response + + RescueController.call_with_exception(env, ActionController::RoutingError.new("Route not found")) assert_equal "no way", @response.body end + def test_rescue_dispatcher_exceptions_without_request_set + @request.env['REQUEST_URI'] = '/no_way' + response = RescueController.call_with_exception(@request.env, ActionController::RoutingError.new("Route not found")) + assert_kind_of ActionController::Response, response + assert_equal "no way", response.body + end + protected def with_all_requests_local(local = true) old_local, ActionController::Base.consider_all_requests_local = diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index d5b6bd6b2a..b981119e1e 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -706,7 +706,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do port_string = port == 80 ? '' : ":#{port}" protocol = options.delete(:protocol) || "http" - host = options.delete(:host) || "named.route.test" + host = options.delete(:host) || "test.host" anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) path = routes.generate(options) @@ -715,27 +715,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end def request - @request ||= MockRequest.new(:host => "named.route.test", :method => :get) - end - end - - class MockRequest - attr_accessor :path, :path_parameters, :host, :subdomains, :domain, :method - - def initialize(values={}) - values.each { |key, value| send("#{key}=", value) } - if values[:host] - subdomain, self.domain = values[:host].split(/\./, 2) - self.subdomains = [subdomain] - end - end - - def protocol - "http://" - end - - def host_with_port - (subdomains * '.') + '.' + domain + @request ||= ActionController::TestRequest.new end end @@ -900,7 +880,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def test_basic_named_route rs.add_named_route :home, '', :controller => 'content', :action => 'list' x = setup_for_named_route - assert_equal("http://named.route.test/", + assert_equal("http://test.host/", x.send(:home_url)) end @@ -908,7 +888,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do rs.add_named_route :home, '', :controller => 'content', :action => 'list' x = setup_for_named_route ActionController::Base.relative_url_root = "/foo" - assert_equal("http://named.route.test/foo/", + assert_equal("http://test.host/foo/", x.send(:home_url)) assert_equal "/foo/", x.send(:home_path) ActionController::Base.relative_url_root = nil @@ -917,14 +897,14 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def test_named_route_with_option rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page' x = setup_for_named_route - assert_equal("http://named.route.test/page/new%20stuff", + assert_equal("http://test.host/page/new%20stuff", x.send(:page_url, :title => 'new stuff')) end def test_named_route_with_default rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage' x = setup_for_named_route - assert_equal("http://named.route.test/page/AboutRails", + assert_equal("http://test.host/page/AboutRails", x.send(:page_url, :title => "AboutRails")) end @@ -932,21 +912,21 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def test_named_route_with_name_prefix rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_' x = setup_for_named_route - assert_equal("http://named.route.test/page", + assert_equal("http://test.host/page", x.send(:my_page_url)) end def test_named_route_with_path_prefix rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my' x = setup_for_named_route - assert_equal("http://named.route.test/my/page", + assert_equal("http://test.host/my/page", x.send(:page_url)) end def test_named_route_with_nested_controller rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index' x = setup_for_named_route - assert_equal("http://named.route.test/admin/user", + assert_equal("http://test.host/admin/user", x.send(:users_url)) end @@ -985,7 +965,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do map.root :controller => "hello" end x = setup_for_named_route - assert_equal("http://named.route.test/", x.send(:root_url)) + assert_equal("http://test.host/", x.send(:root_url)) assert_equal("/", x.send(:root_path)) end @@ -1001,7 +981,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do # x.send(:article_url, :title => 'hi') # ) assert_equal( - "http://named.route.test/page/2005/6/10/hi", + "http://test.host/page/2005/6/10/hi", x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6) ) end @@ -1202,7 +1182,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil) x = setup_for_named_route - assert_equal("http://named.route.test/test", + assert_equal("http://test.host/test", x.send(:blog_url)) end @@ -1249,7 +1229,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do assert_equal '/', rs.generate(:controller => 'content') x = setup_for_named_route - assert_equal("http://named.route.test/", + assert_equal("http://test.host/", x.send(:home_url)) end @@ -1591,7 +1571,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end def request - @request ||= MockRequest.new(:host => "named.routes.test", :method => :get) + @request ||= ActionController::TestRequest.new end def test_generate_extras @@ -1692,13 +1672,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def test_named_route_url_method controller = setup_named_route_test - assert_equal "http://named.route.test/people/5", controller.send(:show_url, :id => 5) + assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5) assert_equal "/people/5", controller.send(:show_path, :id => 5) - assert_equal "http://named.route.test/people", controller.send(:index_url) + assert_equal "http://test.host/people", controller.send(:index_url) assert_equal "/people", controller.send(:index_path) - assert_equal "http://named.route.test/admin/users", controller.send(:users_url) + assert_equal "http://test.host/admin/users", controller.send(:users_url) assert_equal '/admin/users', controller.send(:users_path) assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'}) end @@ -1706,28 +1686,28 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def test_named_route_url_method_with_anchor controller = setup_named_route_test - assert_equal "http://named.route.test/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location') + assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location') assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location') - assert_equal "http://named.route.test/people#location", controller.send(:index_url, :anchor => 'location') + assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location') assert_equal "/people#location", controller.send(:index_path, :anchor => 'location') - assert_equal "http://named.route.test/admin/users#location", controller.send(:users_url, :anchor => 'location') + assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location') assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location') - assert_equal "http://named.route.test/people/go/7/hello/joe/5#location", + assert_equal "http://test.host/people/go/7/hello/joe/5#location", controller.send(:multi_url, 7, "hello", 5, :anchor => 'location') - assert_equal "http://named.route.test/people/go/7/hello/joe/5?baz=bar#location", + assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location", controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location') - assert_equal "http://named.route.test/people?baz=bar#location", + assert_equal "http://test.host/people?baz=bar#location", controller.send(:index_url, :baz => "bar", :anchor => 'location') end def test_named_route_url_method_with_port controller = setup_named_route_test - assert_equal "http://named.route.test:8080/people/5", controller.send(:show_url, 5, :port=>8080) + assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080) end def test_named_route_url_method_with_host @@ -1737,30 +1717,30 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def test_named_route_url_method_with_protocol controller = setup_named_route_test - assert_equal "https://named.route.test/people/5", controller.send(:show_url, 5, :protocol => "https") + assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https") end def test_named_route_url_method_with_ordered_parameters controller = setup_named_route_test - assert_equal "http://named.route.test/people/go/7/hello/joe/5", + assert_equal "http://test.host/people/go/7/hello/joe/5", controller.send(:multi_url, 7, "hello", 5) end def test_named_route_url_method_with_ordered_parameters_and_hash controller = setup_named_route_test - assert_equal "http://named.route.test/people/go/7/hello/joe/5?baz=bar", + assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar", controller.send(:multi_url, 7, "hello", 5, :baz => "bar") end def test_named_route_url_method_with_ordered_parameters_and_empty_hash controller = setup_named_route_test - assert_equal "http://named.route.test/people/go/7/hello/joe/5", + assert_equal "http://test.host/people/go/7/hello/joe/5", controller.send(:multi_url, 7, "hello", 5, {}) end def test_named_route_url_method_with_no_positional_arguments controller = setup_named_route_test - assert_equal "http://named.route.test/people?baz=bar", + assert_equal "http://test.host/people?baz=bar", controller.send(:index_url, :baz => "bar") end @@ -1896,49 +1876,54 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/people" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("index", request.path_parameters[:action]) + request.recycle! - request.method = :post + request.env["REQUEST_METHOD"] = "POST" assert_nothing_raised { set.recognize(request) } assert_equal("create", request.path_parameters[:action]) + request.recycle! - request.method = :put + request.env["REQUEST_METHOD"] = "PUT" assert_nothing_raised { set.recognize(request) } assert_equal("update", request.path_parameters[:action]) + request.recycle! - begin - request.method = :bacon + assert_raises(ActionController::UnknownHttpMethod) { + request.env["REQUEST_METHOD"] = "BACON" set.recognize(request) - flunk 'Should have raised NotImplemented' - rescue ActionController::NotImplemented => e - assert_equal [:get, :post, :put, :delete], e.allowed_methods - end + } + request.recycle! request.path = "/people/5" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("show", request.path_parameters[:action]) assert_equal("5", request.path_parameters[:id]) + request.recycle! - request.method = :put + request.env["REQUEST_METHOD"] = "PUT" assert_nothing_raised { set.recognize(request) } assert_equal("update", request.path_parameters[:action]) assert_equal("5", request.path_parameters[:id]) + request.recycle! - request.method = :delete + request.env["REQUEST_METHOD"] = "DELETE" assert_nothing_raised { set.recognize(request) } assert_equal("destroy", request.path_parameters[:action]) assert_equal("5", request.path_parameters[:id]) + request.recycle! begin - request.method = :post + request.env["REQUEST_METHOD"] = "POST" set.recognize(request) flunk 'Should have raised MethodNotAllowed' rescue ActionController::MethodNotAllowed => e assert_equal [:get, :put, :delete], e.allowed_methods end + request.recycle! ensure Object.send(:remove_const, :PeopleController) @@ -1954,13 +1939,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/people" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("people", request.path_parameters[:controller]) assert_equal("index", request.path_parameters[:action]) request.path = "/" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("people", request.path_parameters[:controller]) assert_equal("index", request.path_parameters[:action]) @@ -1978,7 +1963,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/articles/2005/11/05/a-very-interesting-article" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("permalink", request.path_parameters[:action]) assert_equal("2005", request.path_parameters[:year]) @@ -2015,17 +2000,19 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/people/5" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("show", request.path_parameters[:action]) assert_equal("5", request.path_parameters[:id]) + request.recycle! - request.method = :put + request.env["REQUEST_METHOD"] = "PUT" assert_nothing_raised { set.recognize(request) } assert_equal("update", request.path_parameters[:action]) + request.recycle! request.path = "/people/5.png" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("show", request.path_parameters[:action]) assert_equal("5", request.path_parameters[:id]) @@ -2050,7 +2037,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do set.draw { |map| map.root :controller => "people" } request.path = "" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("people", request.path_parameters[:controller]) assert_equal("index", request.path_parameters[:action]) @@ -2070,7 +2057,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/api/inventory" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("api/products", request.path_parameters[:controller]) assert_equal("inventory", request.path_parameters[:action]) @@ -2090,7 +2077,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/api" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("api/products", request.path_parameters[:controller]) assert_equal("index", request.path_parameters[:action]) @@ -2110,7 +2097,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/prefix/inventory" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("api/products", request.path_parameters[:controller]) assert_equal("inventory", request.path_parameters[:action]) @@ -2246,7 +2233,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end request.path = "/projects/1/milestones" - request.method = :get + request.env["REQUEST_METHOD"] = "GET" assert_nothing_raised { set.recognize(request) } assert_equal("milestones", request.path_parameters[:controller]) assert_equal("index", request.path_parameters[:action]) diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index c003abf094..5fc79baa44 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -19,7 +19,8 @@ class SendFileController < ActionController::Base def rescue_action(e) raise end end -class SendFileTest < Test::Unit::TestCase +class SendFileTest < ActionController::TestCase + tests SendFileController include TestFileUtils Mime::Type.register "image/png", :png unless defined? Mime::PNG @@ -69,6 +70,7 @@ class SendFileTest < Test::Unit::TestCase assert_equal @controller.file_path, response.headers['X-Sendfile'] assert response.body.blank? + assert !response.etag? end def test_data @@ -118,17 +120,42 @@ class SendFileTest < Test::Unit::TestCase assert_equal 'private', h['Cache-Control'] end + def test_send_file_headers_with_mime_lookup_with_symbol + options = { + :length => 1, + :type => :png + } + + @controller.headers = {} + @controller.send(:send_file_headers!, options) + + headers = @controller.headers + + assert_equal 'image/png', headers['Content-Type'] + end + + + def test_send_file_headers_with_bad_symbol + options = { + :length => 1, + :type => :this_type_is_not_registered + } + + @controller.headers = {} + assert_raises(ArgumentError){ @controller.send(:send_file_headers!, options) } + end + %w(file data).each do |method| define_method "test_send_#{method}_status" do @controller.options = { :stream => false, :status => 500 } assert_nothing_raised { assert_not_nil process(method) } - assert_equal '500 Internal Server Error', @response.headers['Status'] + assert_equal '500 Internal Server Error', @response.status end define_method "test_default_send_#{method}_status" do @controller.options = { :stream => false } assert_nothing_raised { assert_not_nil process(method) } - assert_equal ActionController::Base::DEFAULT_RENDER_STATUS_CODE, @response.headers['Status'] + assert_equal ActionController::Base::DEFAULT_RENDER_STATUS_CODE, @response.status end end end diff --git a/actionpack/test/controller/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb index b5f14acc1f..d349c18d1d 100644 --- a/actionpack/test/controller/session/cookie_store_test.rb +++ b/actionpack/test/controller/session/cookie_store_test.rb @@ -1,298 +1,191 @@ require 'abstract_unit' require 'stringio' +class CookieStoreTest < ActionController::IntegrationTest + SessionKey = '_myapp_session' + SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33' -class CGI::Session::CookieStore - def ensure_secret_secure_with_test_hax(secret) - if secret == CookieStoreTest.default_session_options['secret'] - return true - else - ensure_secret_secure_without_test_hax(secret) - end - end - alias_method_chain :ensure_secret_secure, :test_hax -end + DispatcherApp = ActionController::Dispatcher.new + CookieStoreApp = ActionController::Session::CookieStore.new(DispatcherApp, + :key => SessionKey, :secret => SessionSecret) + Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1') -# Expose for tests. -class CGI - attr_reader :output_cookies, :output_hidden + SignedBar = "BAh7BjoIZm9vIghiYXI%3D--" + + "fef868465920f415f2c0652d6910d3af288a0367" - class Session - attr_reader :dbman + class TestController < ActionController::Base + def no_session_access + head :ok + end - class CookieStore - attr_reader :data, :original, :cookie_options + def persistent_session_id + render :text => session[:session_id] end - end -end -class CookieStoreTest < Test::Unit::TestCase - def self.default_session_options - { 'database_manager' => CGI::Session::CookieStore, - 'session_key' => '_myapp_session', - 'secret' => 'Keep it secret; keep it safe.', - 'no_cookies' => true, - 'no_hidden' => true, - 'session_http_only' => true - } - end + def set_session_value + session[:foo] = "bar" + render :text => Verifier.generate(session.to_hash) + end - def self.cookies - { :empty => ['BAgw--0686dcaccc01040f4bd4f35fe160afe9bc04c330', {}], - :a_one => ['BAh7BiIGYWkG--5689059497d7f122a7119f171aef81dcfd807fec', { 'a' => 1 }], - :typical => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7BiILbm90aWNlIgxIZXkgbm93--9d20154623b9eeea05c62ab819be0e2483238759', { 'user_id' => 123, 'flash' => { 'notice' => 'Hey now' }}], - :flashed => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA==--bf9785a666d3c4ac09f7fe3353496b437546cfbf', { 'user_id' => 123, 'flash' => {} }] - } + def get_session_value + render :text => "foo: #{session[:foo].inspect}" + end + def call_reset_session + reset_session + head :ok + end + + def raise_data_overflow + session[:foo] = 'bye!' * 1024 + head :ok + end + + def rescue_action(e) raise end end def setup - ENV.delete('HTTP_COOKIE') + @integration_session = open_session(CookieStoreApp) end def test_raises_argument_error_if_missing_session_key - [nil, ''].each do |blank| - assert_raise(ArgumentError, blank.inspect) { new_session 'session_key' => blank } - end + assert_raise(ArgumentError, nil.inspect) { + ActionController::Session::CookieStore.new(nil, + :key => nil, :secret => SessionSecret) + } + + assert_raise(ArgumentError, ''.inspect) { + ActionController::Session::CookieStore.new(nil, + :key => '', :secret => SessionSecret) + } end def test_raises_argument_error_if_missing_secret - [nil, ''].each do |blank| - assert_raise(ArgumentError, blank.inspect) { new_session 'secret' => blank } - end - end + assert_raise(ArgumentError, nil.inspect) { + ActionController::Session::CookieStore.new(nil, + :key => SessionKey, :secret => nil) + } - def test_raises_argument_error_if_secret_is_probably_insecure - ["password", "secret", "12345678901234567890123456789"].each do |blank| - assert_raise(ArgumentError, blank.inspect) { new_session 'secret' => blank } - end + assert_raise(ArgumentError, ''.inspect) { + ActionController::Session::CookieStore.new(nil, + :key => SessionKey, :secret => '') + } end - def test_reconfigures_session_to_omit_id_cookie_and_hidden_field - new_session do |session| - assert_equal true, @options['no_hidden'] - assert_equal true, @options['no_cookies'] - end - end + def test_raises_argument_error_if_secret_is_probably_insecure + assert_raise(ArgumentError, "password".inspect) { + ActionController::Session::CookieStore.new(nil, + :key => SessionKey, :secret => "password") + } - def test_restore_unmarshals_missing_cookie_as_empty_hash - new_session do |session| - assert_nil session.dbman.data - assert_nil session['test'] - assert_equal Hash.new, session.dbman.data - end - end + assert_raise(ArgumentError, "secret".inspect) { + ActionController::Session::CookieStore.new(nil, + :key => SessionKey, :secret => "secret") + } - def test_restore_unmarshals_good_cookies - cookies(:empty, :a_one, :typical).each do |value, expected| - set_cookie! value - new_session do |session| - assert_nil session['lazy loads the data hash'] - assert_equal expected, session.dbman.data - end - end + assert_raise(ArgumentError, "12345678901234567890123456789".inspect) { + ActionController::Session::CookieStore.new(nil, + :key => SessionKey, :secret => "12345678901234567890123456789") + } end - def test_restore_deletes_tampered_cookies - set_cookie! 'a--b' - new_session do |session| - assert_raise(CGI::Session::CookieStore::TamperedWithCookie) { session['fail'] } - assert_cookie_deleted session - end + def test_setting_session_value + with_test_route_set do + get '/set_session_value' + assert_response :success + assert_equal ["_myapp_session=#{response.body}; path=/"], + headers['Set-Cookie'] + end end - def test_close_doesnt_write_cookie_if_data_is_blank - new_session do |session| - assert_no_cookies session - session.close - assert_no_cookies session - end + def test_getting_session_value + with_test_route_set do + cookies[SessionKey] = SignedBar + get '/get_session_value' + assert_response :success + assert_equal 'foo: "bar"', response.body + end end - def test_close_doesnt_write_cookie_if_data_is_unchanged - set_cookie! cookie_value(:typical) - new_session do |session| - assert_no_cookies session - session['user_id'] = session['user_id'] - session.close - assert_no_cookies session + def test_disregards_tampered_sessions + with_test_route_set do + cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--123456780" + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body end end def test_close_raises_when_data_overflows - set_cookie! cookie_value(:empty) - new_session do |session| - session['overflow'] = 'bye!' * 1024 - assert_raise(CGI::Session::CookieStore::CookieOverflow) { session.close } - assert_no_cookies session - end - end - - def test_close_marshals_and_writes_cookie - set_cookie! cookie_value(:typical) - new_session do |session| - assert_no_cookies session - session['flash'] = {} - assert_no_cookies session - session.close - assert_equal 1, session.cgi.output_cookies.size - cookie = session.cgi.output_cookies.first - assert_cookie cookie, cookie_value(:flashed) - assert_http_only_cookie cookie - assert_secure_cookie cookie, false + with_test_route_set do + assert_raise(ActionController::Session::CookieStore::CookieOverflow) { + get '/raise_data_overflow' + } end end - def test_writes_non_secure_cookie_by_default - set_cookie! cookie_value(:typical) - new_session do |session| - session['flash'] = {} - session.close - cookie = session.cgi.output_cookies.first - assert_secure_cookie cookie,false + def test_doesnt_write_session_cookie_if_session_is_not_accessed + with_test_route_set do + get '/no_session_access' + assert_response :success + assert_equal [], headers['Set-Cookie'] end end - def test_writes_secure_cookie - set_cookie! cookie_value(:typical) - new_session('session_secure'=>true) do |session| - session['flash'] = {} - session.close - cookie = session.cgi.output_cookies.first - assert_secure_cookie cookie + def test_doesnt_write_session_cookie_if_session_is_unchanged + with_test_route_set do + cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--" + + "fef868465920f415f2c0652d6910d3af288a0367" + get '/no_session_access' + assert_response :success + assert_equal [], headers['Set-Cookie'] end end - def test_http_only_cookie_by_default - set_cookie! cookie_value(:typical) - new_session do |session| - session['flash'] = {} - session.close - cookie = session.cgi.output_cookies.first - assert_http_only_cookie cookie - end - end - - def test_overides_http_only_cookie - set_cookie! cookie_value(:typical) - new_session('session_http_only'=>false) do |session| - session['flash'] = {} - session.close - cookie = session.cgi.output_cookies.first - assert_http_only_cookie cookie, false - end - end + def test_setting_session_value_after_session_reset + with_test_route_set do + get '/set_session_value' + assert_response :success + session_payload = response.body + assert_equal ["_myapp_session=#{response.body}; path=/"], + headers['Set-Cookie'] - def test_delete_writes_expired_empty_cookie_and_sets_data_to_nil - set_cookie! cookie_value(:typical) - new_session do |session| - assert_no_cookies session - session.delete - assert_cookie_deleted session + get '/call_reset_session' + assert_response :success + assert_not_equal [], headers['Set-Cookie'] + assert_not_equal session_payload, cookies[SessionKey] - # @data is set to nil so #close doesn't send another cookie. - session.close - assert_cookie_deleted session + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body end end - def test_new_session_doesnt_reuse_deleted_cookie_data - set_cookie! cookie_value(:typical) - - new_session do |session| - assert_not_nil session['user_id'] - session.delete - - # Start a new session using the same CGI instance. - post_delete_session = CGI::Session.new(session.cgi, self.class.default_session_options) - assert_nil post_delete_session['user_id'] + def test_persistent_session_id + with_test_route_set do + cookies[SessionKey] = SignedBar + get '/persistent_session_id' + assert_response :success + assert_equal response.body.size, 32 + session_id = response.body + get '/persistent_session_id' + assert_equal session_id, response.body + reset! + get '/persistent_session_id' + assert_not_equal session_id, response.body end end private - def assert_no_cookies(session) - assert_nil session.cgi.output_cookies, session.cgi.output_cookies.inspect - end - - def assert_cookie_deleted(session, message = 'Expected session deletion cookie to be set') - assert_equal 1, session.cgi.output_cookies.size - cookie = session.cgi.output_cookies.first - assert_cookie cookie, nil, 1.year.ago.to_date, "#{message}: #{cookie.name} => #{cookie.value}" - end - - def assert_cookie(cookie, value = nil, expires = nil, message = nil) - assert_equal '_myapp_session', cookie.name, message - assert_equal [value].compact, cookie.value, message - assert_equal expires, cookie.expires ? cookie.expires.to_date : cookie.expires, message - end - - def assert_secure_cookie(cookie,value=true) - assert cookie.secure==value - end - - def assert_http_only_cookie(cookie,value=true) - assert cookie.http_only==value - end - - def cookies(*which) - self.class.cookies.values_at(*which) - end - - def cookie_value(which) - self.class.cookies[which].first - end - - def set_cookie!(value) - ENV['HTTP_COOKIE'] = "_myapp_session=#{value}" - end - - def new_session(options = {}) - with_cgi do |cgi| - assert_nil cgi.output_hidden, "Output hidden params should be empty: #{cgi.output_hidden.inspect}" - assert_nil cgi.output_cookies, "Output cookies should be empty: #{cgi.output_cookies.inspect}" - - @options = self.class.default_session_options.merge(options) - session = CGI::Session.new(cgi, @options) - ObjectSpace.undefine_finalizer(session) - - assert_nil cgi.output_hidden, "Output hidden params should be empty: #{cgi.output_hidden.inspect}" - assert_nil cgi.output_cookies, "Output cookies should be empty: #{cgi.output_cookies.inspect}" - - yield session if block_given? - session + def with_test_route_set + with_routing do |set| + set.draw do |map| + map.with_options :controller => "cookie_store_test/test" do |c| + c.connect "/:action" + end + end + yield end end - - def with_cgi - ENV['REQUEST_METHOD'] = 'GET' - ENV['HTTP_HOST'] = 'example.com' - ENV['QUERY_STRING'] = '' - - cgi = CGI.new('query', StringIO.new('')) - yield cgi if block_given? - cgi - end -end - - -class CookieStoreWithBlockAsSecretTest < CookieStoreTest - def self.default_session_options - CookieStoreTest.default_session_options.merge 'secret' => Proc.new { 'Keep it secret; keep it safe.' } - end -end - - -class CookieStoreWithMD5DigestTest < CookieStoreTest - def self.default_session_options - CookieStoreTest.default_session_options.merge 'digest' => 'MD5' - end - - def self.cookies - { :empty => ['BAgw--0415cc0be9579b14afc22ee2d341aa21', {}], - :a_one => ['BAh7BiIGYWkG--5a0ed962089cc6600ff44168a5d59bc8', { 'a' => 1 }], - :typical => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7BiILbm90aWNlIgxIZXkgbm93--f426763f6ef435b3738b493600db8d64', { 'user_id' => 123, 'flash' => { 'notice' => 'Hey now' }}], - :flashed => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA==--0af9156650dab044a53a91a4ddec2c51', { 'user_id' => 123, 'flash' => {} }], - :double_escaped => [CGI.escape('BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA%3D%3D--0af9156650dab044a53a91a4ddec2c51'), { 'user_id' => 123, 'flash' => {} }] } - end end diff --git a/actionpack/test/controller/session/mem_cache_store_test.rb b/actionpack/test/controller/session/mem_cache_store_test.rb index 9ab927a01f..eb896a344c 100644 --- a/actionpack/test/controller/session/mem_cache_store_test.rb +++ b/actionpack/test/controller/session/mem_cache_store_test.rb @@ -1,178 +1,102 @@ require 'abstract_unit' -class CGI::Session - def cache - dbman.instance_variable_get(:@cache) - end -end +# You need to start a memcached server inorder to run these tests +class MemCacheStoreTest < ActionController::IntegrationTest + class TestController < ActionController::Base + def no_session_access + head :ok + end + + def set_session_value + session[:foo] = "bar" + head :ok + end + def get_session_value + render :text => "foo: #{session[:foo].inspect}" + end -uses_mocha 'MemCacheStore tests' do -if defined? MemCache::MemCacheError - -class MemCacheStoreTest < Test::Unit::TestCase - SESSION_KEY_RE = /^session:[0-9a-z]+/ - CONN_TEST_KEY = 'connection_test' - MULTI_TEST_KEY = '0123456789' - TEST_DATA = 'Hello test' - - def self.get_mem_cache_if_available - begin - require 'memcache' - cache = MemCache.new('127.0.0.1') - # Test availability of the connection - cache.set(CONN_TEST_KEY, 1) - unless cache.get(CONN_TEST_KEY) == 1 - puts 'Warning: memcache server available but corrupted.' - return nil - end - rescue LoadError, MemCache::MemCacheError - return nil + def call_reset_session + reset_session + head :ok end - return cache + + def rescue_action(e) raise end end - CACHE = get_mem_cache_if_available + begin + DispatcherApp = ActionController::Dispatcher.new + MemCacheStoreApp = ActionController::Session::MemCacheStore.new( + DispatcherApp, :key => '_session_id') - def test_initialization - assert_raise(ArgumentError) { new_session('session_id' => '!invalid_id') } - new_session do |s| - assert_equal Hash.new, s.cache.get('session:' + s.session_id) + def setup + @integration_session = open_session(MemCacheStoreApp) end - end + def test_setting_and_getting_session_value + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] - def test_storage - d = rand(0xffff) - new_session do |s| - session_key = 'session:' + s.session_id - unless CACHE - s.cache.expects(:get).with(session_key) \ - .returns(:test => d) - s.cache.expects(:set).with(session_key, - has_entry(:test, d), - 0) - end - s[:test] = d - s.close - assert_equal d, s.cache.get(session_key)[:test] - assert_equal d, s[:test] - end - end - - def test_deletion - new_session do |s| - session_key = 'session:' + s.session_id - unless CACHE - s.cache.expects(:delete) - s.cache.expects(:get).with(session_key) \ - .returns(nil) + get '/get_session_value' + assert_response :success + assert_equal 'foo: "bar"', response.body end - s[:test] = rand(0xffff) - s.delete - assert_nil s.cache.get(session_key) end - end - - def test_other_session_retrieval - new_session do |sa| - unless CACHE - sa.cache.expects(:set).with('session:' + sa.session_id, - has_entry(:test, TEST_DATA), - 0) - end - sa[:test] = TEST_DATA - sa.close - new_session('session_id' => sa.session_id) do |sb| - unless CACHE - sb.cache.expects(:[]).with('session:' + sb.session_id) \ - .returns(:test => TEST_DATA) - end - assert_equal(TEST_DATA, sb[:test]) + def test_getting_nil_session_value + with_test_route_set do + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body end end - end + def test_prevents_session_fixation + with_test_route_set do + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + session_id = cookies['_session_id'] - def test_multiple_sessions - s_slots = Array.new(10) - operation = :write - last_data = nil - reads = writes = 0 - 50.times do - current = rand(10) - s_slots[current] ||= new_session('session_id' => MULTI_TEST_KEY, - 'new_session' => true) - s = s_slots[current] - case operation - when :write - last_data = rand(0xffff) - unless CACHE - s.cache.expects(:set).with('session:' + MULTI_TEST_KEY, - { :test => last_data }, - 0) - end - s[:test] = last_data - s.close - writes += 1 - when :read - # Make CGI::Session#[] think there was no data retrieval yet. - # Normally, the session caches the data during its lifetime. - s.instance_variable_set(:@data, nil) - unless CACHE - s.cache.expects(:[]).with('session:' + MULTI_TEST_KEY) \ - .returns(:test => last_data) - end - d = s[:test] - assert_equal(last_data, d, "OK reads: #{reads}, OK writes: #{writes}") - reads += 1 + reset! + + get '/set_session_value', :_session_id => session_id + assert_response :success + assert_equal nil, cookies['_session_id'] end - operation = rand(5) == 0 ? :write : :read end - end + def test_setting_session_value_after_session_reset + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + get '/call_reset_session' + assert_response :success + assert_not_equal [], headers['Set-Cookie'] - private - def obtain_session_options - options = { 'database_manager' => CGI::Session::MemCacheStore, - 'session_key' => '_test_app_session' - } - # if don't have running memcache server we use mock instead - unless CACHE - options['cache'] = c = mock - c.stubs(:[]).with(regexp_matches(SESSION_KEY_RE)) - c.stubs(:get).with(regexp_matches(SESSION_KEY_RE)) \ - .returns(Hash.new) - c.stubs(:add).with(regexp_matches(SESSION_KEY_RE), - instance_of(Hash), - 0) + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + end end - options + rescue LoadError, RuntimeError + $stderr.puts "Skipping MemCacheStoreTest tests. Start memcached and try again." end - - def new_session(options = {}) - with_cgi do |cgi| - @options = obtain_session_options.merge(options) - session = CGI::Session.new(cgi, @options) - yield session if block_given? - return session + private + def with_test_route_set + with_routing do |set| + set.draw do |map| + map.with_options :controller => "mem_cache_store_test/test" do |c| + c.connect "/:action" + end + end + yield + end end - end - - def with_cgi - ENV['REQUEST_METHOD'] = 'GET' - ENV['HTTP_HOST'] = 'example.com' - ENV['QUERY_STRING'] = '' - - cgi = CGI.new('query', StringIO.new('')) - yield cgi if block_given? - cgi - end end - -end # defined? MemCache -end # uses_mocha diff --git a/actionpack/test/controller/session_fixation_test.rb b/actionpack/test/controller/session_fixation_test.rb deleted file mode 100644 index e8dc8bd295..0000000000 --- a/actionpack/test/controller/session_fixation_test.rb +++ /dev/null @@ -1,84 +0,0 @@ -require 'abstract_unit' - -class SessionFixationTest < ActionController::IntegrationTest - class TestController < ActionController::Base - session :session_key => '_myapp_session_id', - :secret => CGI::Session.generate_unique_id, - :except => :default_session_key - - session :cookie_only => false, - :only => :allow_session_fixation - - def default_session_key - render :text => "default_session_key" - end - - def custom_session_key - render :text => "custom_session_key: #{params[:id]}" - end - - def allow_session_fixation - render :text => "allow_session_fixation" - end - - def rescue_action(e) raise end - end - - def setup - @controller = TestController.new - end - - def test_should_be_able_to_make_a_successful_request - with_test_route_set do - assert_nothing_raised do - get '/custom_session_key', :id => "1" - end - assert_equal 'custom_session_key: 1', @controller.response.body - assert_not_nil @controller.session - end - end - - def test_should_catch_session_fixation_attempt - with_test_route_set do - assert_raises(ActionController::RackRequest::SessionFixationAttempt) do - get '/custom_session_key', :_myapp_session_id => "42" - end - assert_nil @controller.session - end - end - - def test_should_not_catch_session_fixation_attempt_when_cookie_only_setting_is_disabled - with_test_route_set do - assert_nothing_raised do - get '/allow_session_fixation', :_myapp_session_id => "42" - end - assert !@controller.response.body.blank? - assert_not_nil @controller.session - end - end - - def test_should_catch_session_fixation_attempt_with_default_session_key - # using the default session_key is not possible with cookie store - ActionController::Base.session_store = :p_store - - with_test_route_set do - assert_raises ActionController::RackRequest::SessionFixationAttempt do - get '/default_session_key', :_session_id => "42" - end - assert_nil @controller.response - assert_nil @controller.session - end - end - - private - def with_test_route_set - with_routing do |set| - set.draw do |map| - map.with_options :controller => "session_fixation_test/test" do |c| - c.connect "/:action" - end - end - yield - end - end -end diff --git a/actionpack/test/controller/session_management_test.rb b/actionpack/test/controller/session_management_test.rb deleted file mode 100644 index 592b0b549d..0000000000 --- a/actionpack/test/controller/session_management_test.rb +++ /dev/null @@ -1,178 +0,0 @@ -require 'abstract_unit' - -class SessionManagementTest < Test::Unit::TestCase - class SessionOffController < ActionController::Base - session :off - - def show - render :text => "done" - end - - def tell - render :text => "done" - end - end - - class SessionOffOnController < ActionController::Base - session :off - session :on, :only => :tell - - def show - render :text => "done" - end - - def tell - render :text => "done" - end - end - - class TestController < ActionController::Base - session :off, :only => :show - session :session_secure => true, :except => :show - session :off, :only => :conditional, - :if => Proc.new { |r| r.parameters[:ws] } - - def show - render :text => "done" - end - - def tell - render :text => "done" - end - - def conditional - render :text => ">>>#{params[:ws]}<<<" - end - end - - class SpecializedController < SessionOffController - session :disabled => false, :only => :something - - def something - render :text => "done" - end - - def another - render :text => "done" - end - end - - class AssociationCachingTestController < ActionController::Base - class ObjectWithAssociationCache - def initialize - @cached_associations = false - end - - def fetch_associations - @cached_associations = true - end - - def clear_association_cache - @cached_associations = false - end - - def has_cached_associations? - @cached_associations - end - end - - def show - session[:object] = ObjectWithAssociationCache.new - session[:object].fetch_associations - if session[:object].has_cached_associations? - render :text => "has cached associations" - else - render :text => "does not have cached associations" - end - end - - def tell - if session[:object] - if session[:object].has_cached_associations? - render :text => "has cached associations" - else - render :text => "does not have cached associations" - end - else - render :text => "there is no object" - end - end - end - - - def setup - @request, @response = ActionController::TestRequest.new, - ActionController::TestResponse.new - end - - def test_session_off_globally - @controller = SessionOffController.new - get :show - assert_equal false, @request.session_options - get :tell - assert_equal false, @request.session_options - end - - def test_session_off_then_on_globally - @controller = SessionOffOnController.new - get :show - assert_equal false, @request.session_options - get :tell - assert_instance_of Hash, @request.session_options - assert_equal false, @request.session_options[:disabled] - end - - def test_session_off_conditionally - @controller = TestController.new - get :show - assert_equal false, @request.session_options - get :tell - assert_instance_of Hash, @request.session_options - assert @request.session_options[:session_secure] - end - - def test_controller_specialization_overrides_settings - @controller = SpecializedController.new - get :something - assert_instance_of Hash, @request.session_options - get :another - assert_equal false, @request.session_options - end - - def test_session_off_with_if - @controller = TestController.new - get :conditional - assert_instance_of Hash, @request.session_options - get :conditional, :ws => "ws" - assert_equal false, @request.session_options - end - - def test_session_store_setting - ActionController::Base.session_store = :drb_store - assert_equal CGI::Session::DRbStore, ActionController::Base.session_store - - if Object.const_defined?(:ActiveRecord) - ActionController::Base.session_store = :active_record_store - assert_equal CGI::Session::ActiveRecordStore, ActionController::Base.session_store - end - end - - def test_process_cleanup_with_session_management_support - @controller = AssociationCachingTestController.new - get :show - assert_equal "has cached associations", @response.body - get :tell - assert_equal "does not have cached associations", @response.body - end - - def test_session_is_enabled - @controller = TestController.new - get :show - assert_nothing_raised do - assert_equal false, @controller.session_enabled? - end - - get :tell - assert @controller.session_enabled? - end -end diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 4c44ea4205..e89d6bb960 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -2,8 +2,6 @@ require 'abstract_unit' class WebServiceTest < ActionController::IntegrationTest class TestController < ActionController::Base - session :off - def assign_parameters if params[:full] render :text => dump_params_keys |