diff options
Diffstat (limited to 'actionpack/test/controller')
32 files changed, 741 insertions, 603 deletions
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index 56ba36cee5..ea56048f37 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -165,13 +165,11 @@ module Admin end # a test case to exercise the new capabilities TestRequest & TestResponse -class ActionPackAssertionsControllerTest < Test::Unit::TestCase +class ActionPackAssertionsControllerTest < ActionController::TestCase # let's get this party started def setup ActionController::Routing::Routes.reload ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module user content admin/user)) - @controller = ActionPackAssertionsController.new - @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new end def teardown @@ -235,13 +233,13 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase map.connect ':controller/:action/:id' end process :redirect_to_named_route - assert_raise(Test::Unit::AssertionFailedError) do + assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to 'http://test.host/route_two' end - assert_raise(Test::Unit::AssertionFailedError) do + assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two' end - assert_raise(Test::Unit::AssertionFailedError) do + assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to route_two_url end end @@ -368,6 +366,12 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase assert @response.missing? end + # check client errors + def test_client_error_response_code + process :response404 + assert @response.client_error? + end + # check to see if our redirection matches a pattern def test_redirect_url_match process :redirect_external @@ -410,7 +414,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase def test_assert_redirection_fails_with_incorrect_controller process :redirect_to_controller - assert_raise(Test::Unit::AssertionFailedError) do + assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to :controller => "action_pack_assertions", :action => "flash_me" end end @@ -457,16 +461,16 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase def test_assert_valid get :get_valid_record - assert_valid assigns('record') + assert_deprecated { assert_valid assigns('record') } end def test_assert_valid_failing get :get_invalid_record begin - assert_valid assigns('record') + assert_deprecated { assert_valid assigns('record') } assert false - rescue Test::Unit::AssertionFailedError => e + rescue ActiveSupport::TestCase::Assertion => e end end @@ -475,7 +479,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase get :index assert_response :success flunk 'Expected non-success response' - rescue Test::Unit::AssertionFailedError => e + rescue ActiveSupport::TestCase::Assertion => e assert e.message.include?('FAIL') end @@ -484,17 +488,15 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase get :show assert_response :success flunk 'Expected non-success response' - rescue Test::Unit::AssertionFailedError + rescue ActiveSupport::TestCase::Assertion + # success rescue flunk "assert_response failed to handle failure response with missing, but optional, exception." end end -class ActionPackHeaderTest < Test::Unit::TestCase - def setup - @controller = ActionPackAssertionsController.new - @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new - end +class ActionPackHeaderTest < ActionController::TestCase + tests ActionPackAssertionsController def test_rendering_xml_sets_content_type process :hello_xml_world diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 08cbcbf302..ed8c4427c9 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -9,9 +9,10 @@ require 'controller/fake_controllers' unless defined?(ActionMailer) begin - $:.unshift(File.dirname(__FILE__) + "/../../../actionmailer/lib") + $:.unshift("#{File.dirname(__FILE__)}/../../../actionmailer/lib") require 'action_mailer' - rescue LoadError + rescue LoadError => e + raise unless e.message =~ /action_mailer/ require 'rubygems' gem 'actionmailer' end @@ -19,7 +20,18 @@ end ActionMailer::Base.template_root = FIXTURE_LOAD_PATH -class AssertSelectTest < Test::Unit::TestCase +class AssertSelectTest < ActionController::TestCase + Assertion = ActiveSupport::TestCase::Assertion + + class AssertSelectMailer < ActionMailer::Base + def test(html) + recipients "test <test@test.host>" + from "test@test.host" + subject "Test e-mail" + part :content_type=>"text/html", :body=>html + end + end + class AssertSelectController < ActionController::Base def response_with=(content) @content = content @@ -51,21 +63,9 @@ class AssertSelectTest < Test::Unit::TestCase end end - class AssertSelectMailer < ActionMailer::Base - def test(html) - recipients "test <test@test.host>" - from "test@test.host" - subject "Test e-mail" - part :content_type=>"text/html", :body=>html - end - end - - AssertionFailedError = Test::Unit::AssertionFailedError + tests AssertSelectController def setup - @controller = AssertSelectController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] @@ -76,7 +76,7 @@ class AssertSelectTest < Test::Unit::TestCase end def assert_failure(message, &block) - e = assert_raises(AssertionFailedError, &block) + e = assert_raises(Assertion, &block) assert_match(message, e.message) if Regexp === message assert_equal(message, e.message) if String === message end @@ -94,43 +94,43 @@ class AssertSelectTest < Test::Unit::TestCase def test_equality_true_false render_html %Q{<div id="1"></div><div id="2"></div>} - assert_nothing_raised { assert_select "div" } - assert_raises(AssertionFailedError) { assert_select "p" } - assert_nothing_raised { assert_select "div", true } - assert_raises(AssertionFailedError) { assert_select "p", true } - assert_raises(AssertionFailedError) { assert_select "div", false } - assert_nothing_raised { assert_select "p", false } + assert_nothing_raised { assert_select "div" } + assert_raises(Assertion) { assert_select "p" } + assert_nothing_raised { assert_select "div", true } + assert_raises(Assertion) { assert_select "p", true } + assert_raises(Assertion) { assert_select "div", false } + assert_nothing_raised { assert_select "p", false } end def test_equality_string_and_regexp render_html %Q{<div id="1">foo</div><div id="2">foo</div>} - assert_nothing_raised { assert_select "div", "foo" } - assert_raises(AssertionFailedError) { assert_select "div", "bar" } - assert_nothing_raised { assert_select "div", :text=>"foo" } - assert_raises(AssertionFailedError) { assert_select "div", :text=>"bar" } - assert_nothing_raised { assert_select "div", /(foo|bar)/ } - assert_raises(AssertionFailedError) { assert_select "div", /foobar/ } - assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ } - assert_raises(AssertionFailedError) { assert_select "div", :text=>/foobar/ } - assert_raises(AssertionFailedError) { assert_select "p", :text=>/foobar/ } + assert_nothing_raised { assert_select "div", "foo" } + assert_raises(Assertion) { assert_select "div", "bar" } + assert_nothing_raised { assert_select "div", :text=>"foo" } + assert_raises(Assertion) { assert_select "div", :text=>"bar" } + assert_nothing_raised { assert_select "div", /(foo|bar)/ } + assert_raises(Assertion) { assert_select "div", /foobar/ } + assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ } + assert_raises(Assertion) { assert_select "div", :text=>/foobar/ } + assert_raises(Assertion) { assert_select "p", :text=>/foobar/ } end def test_equality_of_html render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>} text = "\"This is not a big problem,\" he said." html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said." - assert_nothing_raised { assert_select "p", text } - assert_raises(AssertionFailedError) { assert_select "p", html } - assert_nothing_raised { assert_select "p", :html=>html } - assert_raises(AssertionFailedError) { assert_select "p", :html=>text } + assert_nothing_raised { assert_select "p", text } + assert_raises(Assertion) { assert_select "p", html } + assert_nothing_raised { assert_select "p", :html=>html } + assert_raises(Assertion) { assert_select "p", :html=>text } # No stripping for pre. render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>} text = "\n\"This is not a big problem,\" he said.\n" html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n" - assert_nothing_raised { assert_select "pre", text } - assert_raises(AssertionFailedError) { assert_select "pre", html } - assert_nothing_raised { assert_select "pre", :html=>html } - assert_raises(AssertionFailedError) { assert_select "pre", :html=>text } + assert_nothing_raised { assert_select "pre", text } + assert_raises(Assertion) { assert_select "pre", html } + assert_nothing_raised { assert_select "pre", :html=>html } + assert_raises(Assertion) { assert_select "pre", :html=>text } end def test_counts @@ -206,16 +206,16 @@ class AssertSelectTest < Test::Unit::TestCase def test_assert_select_text_match render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>} assert_select "div" do - assert_nothing_raised { assert_select "div", "foo" } - assert_nothing_raised { assert_select "div", "bar" } - assert_nothing_raised { assert_select "div", /\w*/ } - assert_nothing_raised { assert_select "div", /\w*/, :count=>2 } - assert_raises(AssertionFailedError) { assert_select "div", :text=>"foo", :count=>2 } - assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } - assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } - assert_nothing_raised { assert_select "div", :html=>/\w*/ } - assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 } - assert_raises(AssertionFailedError) { assert_select "div", :html=>"<span>foo</span>", :count=>2 } + assert_nothing_raised { assert_select "div", "foo" } + assert_nothing_raised { assert_select "div", "bar" } + assert_nothing_raised { assert_select "div", /\w*/ } + assert_nothing_raised { assert_select "div", /\w*/, :count=>2 } + assert_raises(Assertion) { assert_select "div", :text=>"foo", :count=>2 } + assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } + assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } + assert_nothing_raised { assert_select "div", :html=>/\w*/ } + assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 } + assert_raises(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 } end end @@ -323,7 +323,7 @@ class AssertSelectTest < Test::Unit::TestCase # Test that we fail if there is nothing to pick. def test_assert_select_rjs_fails_if_nothing_to_pick render_rjs { } - assert_raises(AssertionFailedError) { assert_select_rjs } + assert_raises(Assertion) { assert_select_rjs } end def test_assert_select_rjs_with_unicode @@ -338,10 +338,10 @@ class AssertSelectTest < Test::Unit::TestCase if str.respond_to?(:force_encoding) str.force_encoding(Encoding::UTF_8) assert_select str, /\343\203\201..\343\203\210/u - assert_raises(AssertionFailedError) { assert_select str, /\343\203\201.\343\203\210/u } + assert_raises(Assertion) { assert_select str, /\343\203\201.\343\203\210/u } else assert_select str, Regexp.new("\343\203\201..\343\203\210",0,'U') - assert_raises(AssertionFailedError) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') } + assert_raises(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') } end end end @@ -365,7 +365,7 @@ class AssertSelectTest < Test::Unit::TestCase assert_select "div", 1 assert_select "#3" end - assert_raises(AssertionFailedError) { assert_select_rjs "test4" } + assert_raises(Assertion) { assert_select_rjs "test4" } end def test_assert_select_rjs_for_replace @@ -383,7 +383,7 @@ class AssertSelectTest < Test::Unit::TestCase assert_select "div", 1 assert_select "#1" end - assert_raises(AssertionFailedError) { assert_select_rjs :replace, "test2" } + assert_raises(Assertion) { assert_select_rjs :replace, "test2" } # Replace HTML. assert_select_rjs :replace_html do assert_select "div", 1 @@ -393,7 +393,7 @@ class AssertSelectTest < Test::Unit::TestCase assert_select "div", 1 assert_select "#2" end - assert_raises(AssertionFailedError) { assert_select_rjs :replace_html, "test1" } + assert_raises(Assertion) { assert_select_rjs :replace_html, "test1" } end def test_assert_select_rjs_for_chained_replace @@ -411,7 +411,7 @@ class AssertSelectTest < Test::Unit::TestCase assert_select "div", 1 assert_select "#1" end - assert_raises(AssertionFailedError) { assert_select_rjs :chained_replace, "test2" } + assert_raises(Assertion) { assert_select_rjs :chained_replace, "test2" } # Replace HTML. assert_select_rjs :chained_replace_html do assert_select "div", 1 @@ -421,7 +421,7 @@ class AssertSelectTest < Test::Unit::TestCase assert_select "div", 1 assert_select "#2" end - assert_raises(AssertionFailedError) { assert_select_rjs :replace_html, "test1" } + assert_raises(Assertion) { assert_select_rjs :replace_html, "test1" } end # Simple remove @@ -440,8 +440,8 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :remove, "test1" - rescue Test::Unit::AssertionFailedError - assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message + rescue Assertion + assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_remove_ignores_block @@ -472,8 +472,8 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :show, "test1" - rescue Test::Unit::AssertionFailedError - assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message + rescue Assertion + assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_show_ignores_block @@ -504,8 +504,8 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :hide, "test1" - rescue Test::Unit::AssertionFailedError - assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message + rescue Assertion + assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_hide_ignores_block @@ -536,8 +536,8 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :toggle, "test1" - rescue Test::Unit::AssertionFailedError - assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message + rescue Assertion + assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message end def test_assert_select_rjs_for_toggle_ignores_block @@ -567,7 +567,7 @@ class AssertSelectTest < Test::Unit::TestCase assert_select "div", 1 assert_select "#3" end - assert_raises(AssertionFailedError) { assert_select_rjs :insert_html, "test1" } + assert_raises(Assertion) { assert_select_rjs :insert_html, "test1" } end # Positioned insert. @@ -693,7 +693,7 @@ EOF # def test_assert_select_email - assert_raises(AssertionFailedError) { assert_select_email {} } + assert_raises(Assertion) { assert_select_email {} } AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>" assert_select_email do assert_select "div:root" do diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 738c016c6e..18d185b264 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -105,7 +105,7 @@ class ControllerInstanceTests < Test::Unit::TestCase end -class PerformActionTest < Test::Unit::TestCase +class PerformActionTest < ActionController::TestCase class MockLogger attr_reader :logged diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index b6cdd116e5..10c65acd9a 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -42,7 +42,7 @@ class PageCachingTestController < ActionController::Base end end -class PageCachingTest < Test::Unit::TestCase +class PageCachingTest < ActionController::TestCase def setup ActionController::Base.perform_caching = true @@ -222,7 +222,7 @@ class ActionCachingMockController end end -class ActionCacheTest < Test::Unit::TestCase +class ActionCacheTest < ActionController::TestCase def setup reset! FileUtils.mkdir_p(FILE_STORE_PATH) @@ -291,11 +291,13 @@ class ActionCacheTest < Test::Unit::TestCase ActionController::Base.use_accept_header = old_use_accept_header end - def test_action_cache_with_store_options - MockTime.expects(:now).returns(12345).once - @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once - @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once - get :index + uses_mocha 'test action cache' do + def test_action_cache_with_store_options + MockTime.expects(:now).returns(12345).once + @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once + @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once + get :index + end end def test_action_cache_with_custom_cache_path @@ -469,7 +471,7 @@ class FragmentCachingTestController < ActionController::Base def some_action; end; end -class FragmentCachingTest < Test::Unit::TestCase +class FragmentCachingTest < ActionController::TestCase def setup ActionController::Base.perform_caching = true @store = ActiveSupport::Cache::MemoryStore.new @@ -525,7 +527,7 @@ class FragmentCachingTest < Test::Unit::TestCase def test_write_fragment_with_caching_disabled assert_nil @store.read('views/name') ActionController::Base.perform_caching = false - assert_equal nil, @controller.write_fragment('name', 'value') + assert_equal 'value', @controller.write_fragment('name', 'value') assert_nil @store.read('views/name') end @@ -601,7 +603,7 @@ class FunctionalCachingController < ActionController::Base end end -class FunctionalFragmentCachingTest < Test::Unit::TestCase +class FunctionalFragmentCachingTest < ActionController::TestCase def setup ActionController::Base.perform_caching = true @store = ActiveSupport::Cache::MemoryStore.new diff --git a/actionpack/test/controller/cgi_test.rb b/actionpack/test/controller/cgi_test.rb index 813171857a..ac1c8abc59 100644 --- a/actionpack/test/controller/cgi_test.rb +++ b/actionpack/test/controller/cgi_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'action_controller/cgi_process' class BaseCgiTest < Test::Unit::TestCase def setup @@ -48,7 +47,8 @@ class BaseCgiTest < Test::Unit::TestCase # some developers have grown accustomed to using comma in cookie values. @alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"} @cgi = CGI.new - @cgi.stubs(:env_table).returns(@request_hash) + class << @cgi; attr_accessor :env_table end + @cgi.env_table = @request_hash @request = ActionController::CgiRequest.new(@cgi) end diff --git a/actionpack/test/controller/components_test.rb b/actionpack/test/controller/components_test.rb deleted file mode 100644 index 4d36fc411d..0000000000 --- a/actionpack/test/controller/components_test.rb +++ /dev/null @@ -1,156 +0,0 @@ -require 'abstract_unit' - -class CallerController < ActionController::Base - def calling_from_controller - render_component(:controller => "callee", :action => "being_called") - end - - def calling_from_controller_with_params - render_component(:controller => "callee", :action => "being_called", :params => { "name" => "David" }) - end - - def calling_from_controller_with_different_status_code - render_component(:controller => "callee", :action => "blowing_up") - end - - def calling_from_template - render :inline => "Ring, ring: <%= render_component(:controller => 'callee', :action => 'being_called') %>" - end - - def internal_caller - render :inline => "Are you there? <%= render_component(:action => 'internal_callee') %>" - end - - def internal_callee - render :text => "Yes, ma'am" - end - - def set_flash - render_component(:controller => "callee", :action => "set_flash") - end - - def use_flash - render_component(:controller => "callee", :action => "use_flash") - end - - def calling_redirected - render_component(:controller => "callee", :action => "redirected") - end - - def calling_redirected_as_string - render :inline => "<%= render_component(:controller => 'callee', :action => 'redirected') %>" - end - - def rescue_action(e) raise end -end - -class CalleeController < ActionController::Base - def being_called - render :text => "#{params[:name] || "Lady"} of the House, speaking" - end - - def blowing_up - render :text => "It's game over, man, just game over, man!", :status => 500 - end - - def set_flash - flash[:notice] = 'My stoney baby' - render :text => 'flash is set' - end - - def use_flash - render :text => flash[:notice] || 'no flash' - end - - def redirected - redirect_to :controller => "callee", :action => "being_called" - end - - def rescue_action(e) raise end -end - -class ComponentsTest < Test::Unit::TestCase - def setup - @controller = CallerController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - - def test_calling_from_controller - assert_deprecated do - get :calling_from_controller - assert_equal "Lady of the House, speaking", @response.body - end - end - - def test_calling_from_controller_with_params - assert_deprecated do - get :calling_from_controller_with_params - assert_equal "David of the House, speaking", @response.body - end - end - - def test_calling_from_controller_with_different_status_code - assert_deprecated do - get :calling_from_controller_with_different_status_code - assert_equal 500, @response.response_code - end - end - - def test_calling_from_template - assert_deprecated do - get :calling_from_template - assert_equal "Ring, ring: Lady of the House, speaking", @response.body - end - end - - def test_etag_is_set_for_parent_template_when_calling_from_template - assert_deprecated do - get :calling_from_template - expected_etag = etag_for("Ring, ring: Lady of the House, speaking") - assert_equal expected_etag, @response.headers['ETag'] - end - end - - def test_internal_calling - assert_deprecated do - get :internal_caller - assert_equal "Are you there? Yes, ma'am", @response.body - end - end - - def test_flash - assert_deprecated do - get :set_flash - assert_equal 'My stoney baby', flash[:notice] - get :use_flash - assert_equal 'My stoney baby', @response.body - get :use_flash - assert_equal 'no flash', @response.body - end - end - - def test_component_redirect_redirects - assert_deprecated do - get :calling_redirected - assert_redirected_to :controller=>"callee", :action => "being_called" - end - end - - def test_component_multiple_redirect_redirects - test_component_redirect_redirects - test_internal_calling - end - - def test_component_as_string_redirect_renders_redirected_action - assert_deprecated do - get :calling_redirected_as_string - assert_equal "Lady of the House, speaking", @response.body - end - end - - protected - def etag_for(text) - %("#{Digest::MD5.hexdigest(text)}") - end -end diff --git a/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb b/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb index 86555a77df..dd69a63020 100644 --- a/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb +++ b/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class DeprecatedBaseMethodsTest < Test::Unit::TestCase +class DeprecatedBaseMethodsTest < ActionController::TestCase class Target < ActionController::Base def home_url(greeting) "http://example.com/#{greeting}" @@ -13,11 +13,7 @@ class DeprecatedBaseMethodsTest < Test::Unit::TestCase def rescue_action(e) raise e end end - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = Target.new - end + tests Target def test_log_error_silences_deprecation_warnings get :raises_name_error @@ -25,10 +21,12 @@ class DeprecatedBaseMethodsTest < Test::Unit::TestCase assert_not_deprecated { @controller.send :log_error, e } end - def test_assertion_failed_error_silences_deprecation_warnings - get :raises_name_error - rescue => e - error = Test::Unit::Error.new('testing ur doodz', e) - assert_not_deprecated { error.message } + if defined? Test::Unit::Error + def test_assertion_failed_error_silences_deprecation_warnings + get :raises_name_error + rescue => e + error = Test::Unit::Error.new('testing ur doodz', e) + assert_not_deprecated { error.message } + end end end diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb index 3ee78a6156..61bfb2b6e9 100644 --- a/actionpack/test/controller/dispatcher_test.rb +++ b/actionpack/test/controller/dispatcher_test.rb @@ -2,8 +2,6 @@ require 'abstract_unit' uses_mocha 'dispatcher tests' do -require 'action_controller/dispatcher' - class DispatcherTest < Test::Unit::TestCase Dispatcher = ActionController::Dispatcher diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 83e3b085e7..5f36461b89 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -ActionController::Helpers::HELPERS_DIR.replace File.dirname(__FILE__) + '/../fixtures/helpers' +ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers' class TestController < ActionController::Base attr_accessor :delegate_attr @@ -130,6 +130,20 @@ class HelperTest < Test::Unit::TestCase assert methods.include?('foobar') end + def test_all_helpers_with_alternate_helper_dir + @controller_class.helpers_dir = File.dirname(__FILE__) + '/../fixtures/alternate_helpers' + + # Reload helpers + @controller_class.master_helper_module = Module.new + @controller_class.helper :all + + # helpers/abc_helper.rb should not be included + assert !master_helper_methods.include?('bare_a') + + # alternate_helpers/foo_helper.rb + assert master_helper_methods.include?('baz') + end + def test_helper_proxy methods = ApplicationController.helpers.methods.map(&:to_s) diff --git a/actionpack/test/controller/html-scanner/sanitizer_test.rb b/actionpack/test/controller/html-scanner/sanitizer_test.rb index a9e8447e32..e85a5c7abf 100644 --- a/actionpack/test/controller/html-scanner/sanitizer_test.rb +++ b/actionpack/test/controller/html-scanner/sanitizer_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class SanitizerTest < Test::Unit::TestCase +class SanitizerTest < ActionController::TestCase def setup @sanitizer = nil # used by assert_sanitizer end @@ -253,6 +253,10 @@ class SanitizerTest < Test::Unit::TestCase assert_sanitized "<![CDATA[<span>neverending...", "<![CDATA[<span>neverending...]]>" end + def test_should_not_mangle_urls_with_ampersand + assert_sanitized %{<a href=\"http://www.domain.com?var1=1&var2=2\">my link</a>} + end + protected def assert_sanitized(input, expected = nil) @sanitizer ||= HTML::WhiteListSanitizer.new diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 7e4c3e171a..b39d35930d 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -1,6 +1,4 @@ require 'abstract_unit' -require 'action_controller/integration' -require 'action_controller/routing' uses_mocha 'integration' do diff --git a/actionpack/test/controller/integration_upload_test.rb b/actionpack/test/controller/integration_upload_test.rb index 4af9b7e697..b1dd6a6341 100644 --- a/actionpack/test/controller/integration_upload_test.rb +++ b/actionpack/test/controller/integration_upload_test.rb @@ -1,6 +1,4 @@ require 'abstract_unit' -require 'action_controller/integration' -require 'action_controller/routing' unless defined? ApplicationController class ApplicationController < ActionController::Base diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 1120fdbff5..18c01f755c 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -3,6 +3,10 @@ require 'abstract_unit' # The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited # method has access to the view_paths array when looking for a layout to automatically assign. old_load_paths = ActionController::Base.view_paths + +ActionView::Template::register_template_handler :mab, + lambda { |template| template.source.inspect } + ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ] class LayoutTest < ActionController::Base @@ -31,14 +35,8 @@ end class MultipleExtensions < LayoutTest end -ActionView::Template::register_template_handler :mab, - lambda { |template| template.source.inspect } - -class LayoutAutoDiscoveryTest < Test::Unit::TestCase +class LayoutAutoDiscoveryTest < ActionController::TestCase def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @request.host = "www.nextangle.com" end @@ -55,10 +53,9 @@ class LayoutAutoDiscoveryTest < Test::Unit::TestCase end def test_third_party_template_library_auto_discovers_layout - ThirdPartyTemplateLibraryController.view_paths.reload! @controller = ThirdPartyTemplateLibraryController.new get :hello - assert_equal 'layouts/third_party_template_library', @controller.active_layout + assert_equal 'layouts/third_party_template_library.mab', @controller.active_layout.to_s assert_equal 'layouts/third_party_template_library', @response.layout assert_response :success assert_equal 'Mab', @response.body @@ -67,14 +64,14 @@ class LayoutAutoDiscoveryTest < Test::Unit::TestCase def test_namespaced_controllers_auto_detect_layouts @controller = ControllerNameSpace::NestedController.new get :hello - assert_equal 'layouts/controller_name_space/nested', @controller.active_layout + assert_equal 'layouts/controller_name_space/nested', @controller.active_layout.to_s assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body end def test_namespaced_controllers_auto_detect_layouts @controller = MultipleExtensions.new get :hello - assert_equal 'layouts/multiple_extensions', @controller.active_layout + assert_equal 'layouts/multiple_extensions.html.erb', @controller.active_layout.to_s assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip end end @@ -98,12 +95,7 @@ class RendersNoLayoutController < LayoutTest end end -class LayoutSetInResponseTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - +class LayoutSetInResponseTest < ActionController::TestCase def test_layout_set_when_using_default_layout @controller = DefaultLayoutController.new get :hello @@ -150,12 +142,7 @@ class SetsNonExistentLayoutFile < LayoutTest layout "nofile.rhtml" end -class LayoutExceptionRaised < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - +class LayoutExceptionRaised < ActionController::TestCase def test_exception_raised_when_layout_file_not_found @controller = SetsNonExistentLayoutFile.new get :hello @@ -170,12 +157,7 @@ class LayoutStatusIsRendered < LayoutTest end end -class LayoutStatusIsRenderedTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - +class LayoutStatusIsRenderedTest < ActionController::TestCase def test_layout_status_is_rendered @controller = LayoutStatusIsRendered.new get :hello @@ -187,12 +169,7 @@ class LayoutSymlinkedTest < LayoutTest layout "symlinked/symlinked_layout" end -class LayoutSymlinkedIsRenderedTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - +class LayoutSymlinkedIsRenderedTest < ActionController::TestCase def test_symlinked_layout_is_rendered @controller = LayoutSymlinkedTest.new get :hello diff --git a/actionpack/test/controller/logging_test.rb b/actionpack/test/controller/logging_test.rb new file mode 100644 index 0000000000..3c936854dd --- /dev/null +++ b/actionpack/test/controller/logging_test.rb @@ -0,0 +1,46 @@ +require 'abstract_unit' + +class LoggingController < ActionController::Base + def show + render :nothing => true + end +end + +class LoggingTest < ActionController::TestCase + tests LoggingController + + class MockLogger + attr_reader :logged + + def method_missing(method, *args) + @logged ||= [] + @logged << args.first + end + end + + setup :set_logger + + def test_logging_without_parameters + get :show + assert_equal 2, logs.size + assert_nil logs.detect {|l| l =~ /Parameters/ } + end + + def test_logging_with_parameters + get :show, :id => 10 + assert_equal 3, logs.size + + params = logs.detect {|l| l =~ /Parameters/ } + assert_equal 'Parameters: {"id"=>"10"}', params + end + + private + + def set_logger + @controller.logger = MockLogger.new + end + + def logs + @logs ||= @controller.logger.logged.compact.map {|l| l.strip} + end +end diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index 0d508eb8df..dc59180a68 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -162,13 +162,11 @@ class RespondToController < ActionController::Base end end -class MimeControllerTest < Test::Unit::TestCase +class MimeControllerTest < ActionController::TestCase + tests RespondToController + def setup ActionController::Base.use_accept_header = true - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - - @controller = RespondToController.new @request.host = "www.example.com" end @@ -509,12 +507,10 @@ class SuperPostController < PostController end end -class MimeControllerLayoutsTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new +class MimeControllerLayoutsTest < ActionController::TestCase + tests PostController - @controller = PostController.new + def setup @request.host = "www.example.com" end diff --git a/actionpack/test/controller/mime_type_test.rb b/actionpack/test/controller/mime_type_test.rb index f16a3c68b4..21ae0419f1 100644 --- a/actionpack/test/controller/mime_type_test.rb +++ b/actionpack/test/controller/mime_type_test.rb @@ -61,7 +61,9 @@ class MimeTypeTest < Test::Unit::TestCase types.each do |type| mime = Mime.const_get(type.to_s.upcase) assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?" - (types - [type]).each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } + invalid_types = types - [type] + invalid_types.delete(:html) if Mime::Type.html_types.include?(type) + invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } end end @@ -71,14 +73,12 @@ class MimeTypeTest < Test::Unit::TestCase end def test_verifiable_mime_types - unverified_types = Mime::Type.unverifiable_types all_types = Mime::SET.to_a.map(&:to_sym) all_types.uniq! # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } - - unverified, verified = all_types.partition { |type| Mime::Type.unverifiable_types.include? type } - assert verified.all? { |type| Mime.const_get(type.to_s.upcase).verify_request? }, "Not all Mime Types are verified: #{verified.inspect}" - assert unverified.all? { |type| !Mime.const_get(type.to_s.upcase).verify_request? }, "Some Mime Types are verified: #{unverified.inspect}" + verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type } + 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 end diff --git a/actionpack/test/controller/polymorphic_routes_test.rb b/actionpack/test/controller/polymorphic_routes_test.rb index 6ddf2826cd..09c7f74617 100644 --- a/actionpack/test/controller/polymorphic_routes_test.rb +++ b/actionpack/test/controller/polymorphic_routes_test.rb @@ -22,8 +22,7 @@ end class Response::Nested < Response; end uses_mocha 'polymorphic URL helpers' do - class PolymorphicRoutesTest < Test::Unit::TestCase - + class PolymorphicRoutesTest < ActiveSupport::TestCase include ActionController::PolymorphicRoutes def setup @@ -72,20 +71,22 @@ uses_mocha 'polymorphic URL helpers' do polymorphic_url(@article, :param1 => '10') end - def test_formatted_url_helper - expects(:formatted_article_url).with(@article, :pdf) - formatted_polymorphic_url([@article, :pdf]) + def test_formatted_url_helper_is_deprecated + expects(:articles_url).with(:format => :pdf) + assert_deprecated do + formatted_polymorphic_url([@article, :pdf]) + end end def test_format_option @article.save - expects(:formatted_article_url).with(@article, :pdf) + expects(:article_url).with(@article, :format => :pdf) polymorphic_url(@article, :format => :pdf) end def test_format_option_with_url_options @article.save - expects(:formatted_article_url).with(@article, :pdf, :param1 => '10') + expects(:article_url).with(@article, :format => :pdf, :param1 => '10') polymorphic_url(@article, :format => :pdf, :param1 => '10') end @@ -158,17 +159,34 @@ uses_mocha 'polymorphic URL helpers' do def test_nesting_with_array_containing_singleton_resource_and_format @tag = Tag.new @tag.save - expects(:formatted_article_response_tag_url).with(@article, @tag, :pdf) - formatted_polymorphic_url([@article, :response, @tag, :pdf]) + expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) + polymorphic_url([@article, :response, @tag], :format => :pdf) end def test_nesting_with_array_containing_singleton_resource_and_format_option @tag = Tag.new @tag.save - expects(:formatted_article_response_tag_url).with(@article, @tag, :pdf) + expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) polymorphic_url([@article, :response, @tag], :format => :pdf) end + def test_nesting_with_array_containing_nil + expects(:article_response_url).with(@article) + polymorphic_url([@article, nil, :response]) + end + + def test_with_array_containing_single_object + @article.save + expects(:article_url).with(@article) + polymorphic_url([nil, @article]) + end + + def test_with_array_containing_single_name + @article.save + expects(:articles_url) + polymorphic_url([:articles]) + end + # TODO: Needs to be updated to correctly know about whether the object is in a hash or not def xtest_with_hash expects(:article_url).with(@article) diff --git a/actionpack/test/controller/rack_test.rb b/actionpack/test/controller/rack_test.rb index d5e56b9584..7e8b0f9bf2 100644 --- a/actionpack/test/controller/rack_test.rb +++ b/actionpack/test/controller/rack_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'action_controller/rack_process' class BaseRackTest < Test::Unit::TestCase def setup diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index c55307d645..27cedc91d2 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -103,12 +103,8 @@ class RedirectController < ActionController::Base end end -class RedirectTest < Test::Unit::TestCase - def setup - @controller = RedirectController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end +class RedirectTest < ActionController::TestCase + tests RedirectController def test_simple_redirect get :simple_redirect @@ -256,12 +252,8 @@ module ModuleTest end end - class ModuleRedirectTest < Test::Unit::TestCase - def setup - @controller = ModuleRedirectController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end + class ModuleRedirectTest < ActionController::TestCase + tests ModuleRedirectController def test_simple_redirect get :simple_redirect diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index df9376727f..972e425e35 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -39,7 +39,7 @@ class TestController < ActionController::Base render :action => 'hello_world' end before_filter :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs - + def handle_last_modified_and_etags fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ]) end @@ -246,6 +246,15 @@ class TestController < ActionController::Base :locals => { :local_name => name } end + def helper_method_to_render_to_string(*args) + render_to_string(*args) + end + helper_method :helper_method_to_render_to_string + + def render_html_only_partial_within_inline + render :inline => "Hello world <%= helper_method_to_render_to_string :partial => 'test/partial_with_only_html_version' %>" + end + def formatted_html_erb end @@ -337,6 +346,11 @@ class TestController < ActionController::Base render :text => "Hi web users! #{@stuff}" end + def render_to_string_with_inline_and_render + render_to_string :inline => "<%= 'dlrow olleh'.reverse %>" + render :template => "test/hello_world" + end + def rendering_with_conflicting_local_vars @name = "David" def @template.name() nil end @@ -641,12 +655,10 @@ class TestController < ActionController::Base end end -class RenderTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = TestController.new +class RenderTest < ActionController::TestCase + tests TestController + 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) @@ -871,12 +883,13 @@ class RenderTest < Test::Unit::TestCase end def test_enum_rjs_test + ActiveSupport::SecureRandom.stubs(:base64).returns("asdf") get :enum_rjs_test body = %{ $$(".product").each(function(value, index) { new Effect.Highlight(element,{}); new Effect.Highlight(value,{}); - Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}}); + Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value) + '&authenticity_token=' + encodeURIComponent('asdf')})}}); new Draggable(value, {}); }); }.gsub(/^ /, '').strip @@ -908,6 +921,11 @@ class RenderTest < Test::Unit::TestCase assert_equal "The value of foo is: ::this is a test::\n", @response.body end + def test_render_to_string_inline + get :render_to_string_with_inline_and_render + assert_template "test/hello_world" + end + def test_nested_rendering @controller = Fun::GamesController.new get :hello_world @@ -924,6 +942,11 @@ class RenderTest < Test::Unit::TestCase assert_equal "Goodbye, Local David", @response.body end + def test_rendering_html_only_partial_within_inline_with_js + get :render_html_only_partial_within_inline, :format => :js + assert_equal "Hello world partial with only html version", @response.body + end + def test_should_render_formatted_template get :formatted_html_erb assert_equal 'formatted html erb', @response.body @@ -1333,12 +1356,10 @@ class RenderTest < Test::Unit::TestCase end end -class EtagRenderTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = TestController.new +class EtagRenderTest < ActionController::TestCase + tests TestController + def setup @request.host = "www.nextangle.com" @expected_bang_etag = etag_for(expand_key([:foo, 123])) end @@ -1368,7 +1389,7 @@ class EtagRenderTest < Test::Unit::TestCase assert_equal "200 OK", @response.status assert !@response.body.empty? end - + def test_render_should_not_set_etag_when_last_modified_has_been_specified get :render_hello_world_with_last_modified_set assert_equal "200 OK", @response.status @@ -1382,7 +1403,7 @@ class EtagRenderTest < Test::Unit::TestCase expected_etag = etag_for('hello david') assert_equal expected_etag, @response.headers['ETag'] @response = ActionController::TestResponse.new - + @request.if_none_match = expected_etag get :render_hello_world_from_variable assert_equal "304 Not Modified", @response.status @@ -1407,35 +1428,33 @@ class EtagRenderTest < Test::Unit::TestCase assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body assert_equal etag_for("<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n"), @response.headers['ETag'] end - + def test_etag_with_bang_should_set_etag get :conditional_hello_with_bangs assert_equal @expected_bang_etag, @response.headers["ETag"] assert_response :success end - + def test_etag_with_bang_should_obey_if_none_match @request.if_none_match = @expected_bang_etag get :conditional_hello_with_bangs assert_response :not_modified end - + protected def etag_for(text) %("#{Digest::MD5.hexdigest(text)}") end - + def expand_key(args) ActiveSupport::Cache.expand_cache_key(args) end end -class LastModifiedRenderTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = TestController.new +class LastModifiedRenderTest < ActionController::TestCase + tests TestController + def setup @request.host = "www.nextangle.com" @last_modified = Time.now.utc.beginning_of_day.httpdate end @@ -1467,13 +1486,13 @@ class LastModifiedRenderTest < Test::Unit::TestCase assert !@response.body.blank? assert_equal @last_modified, @response.headers['Last-Modified'] end - + def test_request_with_bang_gets_last_modified get :conditional_hello_with_bangs assert_equal @last_modified, @response.headers['Last-Modified'] assert_response :success end - + def test_request_with_bang_obeys_last_modified @request.if_modified_since = @last_modified get :conditional_hello_with_bangs @@ -1487,12 +1506,10 @@ class LastModifiedRenderTest < Test::Unit::TestCase end end -class RenderingLoggingTest < Test::Unit::TestCase - def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller = TestController.new +class RenderingLoggingTest < ActionController::TestCase + tests TestController + def setup @request.host = "www.nextangle.com" end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index f7adaa7d4e..ef0bf5fd08 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -5,13 +5,6 @@ ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end -# simulates cookie session store -class FakeSessionDbMan - def self.generate_digest(data) - Digest::SHA1.hexdigest("secure") - end -end - # common controller actions module RequestForgeryProtectionActions def index @@ -36,29 +29,10 @@ end # sample controllers class RequestForgeryProtectionController < ActionController::Base include RequestForgeryProtectionActions - protect_from_forgery :only => :index, :secret => 'abc' -end - -class RequestForgeryProtectionWithoutSecretController < ActionController::Base - include RequestForgeryProtectionActions - protect_from_forgery -end - -# no token is given, assume the cookie store is used -class CsrfCookieMonsterController < ActionController::Base - include RequestForgeryProtectionActions protect_from_forgery :only => :index end -# sessions are turned off -class SessionOffController < ActionController::Base - protect_from_forgery :secret => 'foobar' - session :off - def rescue_action(e) raise e end - include RequestForgeryProtectionActions -end - -class FreeCookieController < CsrfCookieMonsterController +class FreeCookieController < RequestForgeryProtectionController self.allow_forgery_protection = false def index @@ -77,57 +51,61 @@ module RequestForgeryProtectionTests ActionController::Base.request_forgery_protection_token = nil end + def test_should_render_form_with_token_tag - get :index - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token - end - - def test_should_render_button_to_with_token_tag - get :show_button - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token - end + get :index + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token + end - def test_should_render_remote_form_with_only_one_token_parameter - get :remote_form - assert_equal 1, @response.body.scan(@token).size - end + def test_should_render_button_to_with_token_tag + get :show_button + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token + end - def test_should_allow_get - get :index - assert_response :success - end - - def test_should_allow_post_without_token_on_unsafe_action - post :unsafe - assert_response :success - end + def test_should_render_remote_form_with_only_one_token_parameter + get :remote_form + assert_equal 1, @response.body.scan(@token).size + end - def test_should_not_allow_post_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { post :index } - end + def test_should_allow_get + get :index + assert_response :success + end - def test_should_not_allow_put_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { put :index } - end + def test_should_allow_post_without_token_on_unsafe_action + post :unsafe + assert_response :success + end - def test_should_not_allow_delete_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { delete :index } + def test_should_not_allow_html_post_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raises(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } + end + + def test_should_not_allow_html_put_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raises(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } + end + + def test_should_not_allow_html_delete_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raises(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } end - def test_should_not_allow_api_formatted_post_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + def test_should_allow_api_formatted_post_without_token + assert_nothing_raised do post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_nothing_raised do put :index, :format => 'xml' end end - def test_should_not_allow_api_formatted_delete_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + def test_should_allow_api_formatted_delete_without_token + assert_nothing_raised do delete :index, :format => 'xml' end end @@ -174,16 +152,20 @@ module RequestForgeryProtectionTests end end - def test_should_not_allow_xhr_post_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { xhr :post, :index } + def test_should_allow_xhr_post_without_token + assert_nothing_raised { xhr :post, :index } + end + def test_should_not_allow_xhr_post_with_html_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raise(ActionController::InvalidAuthenticityToken) { xhr :post, :index } end - def test_should_not_allow_xhr_put_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { xhr :put, :index } + def test_should_allow_xhr_put_without_token + assert_nothing_raised { xhr :put, :index } end - def test_should_not_allow_xhr_delete_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { xhr :delete, :index } + def test_should_allow_xhr_delete_without_token + assert_nothing_raised { xhr :delete, :index } end def test_should_allow_post_with_token @@ -222,61 +204,28 @@ end # OK let's get our test on -class RequestForgeryProtectionControllerTest < Test::Unit::TestCase +class RequestForgeryProtectionControllerTest < ActionController::TestCase include RequestForgeryProtectionTests def setup @controller = RequestForgeryProtectionController.new @request = ActionController::TestRequest.new + @request.format = :html @response = ActionController::TestResponse.new - class << @request.session - def session_id() '123' end - end - @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123') - ActionController::Base.request_forgery_protection_token = :authenticity_token - end -end + @token = "cf50faa3fe97702ca1ae" -class RequestForgeryProtectionWithoutSecretControllerTest < Test::Unit::TestCase - def setup - @controller = RequestForgeryProtectionWithoutSecretController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - class << @request.session - def session_id() '123' end - end - @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123') + ActiveSupport::SecureRandom.stubs(:base64).returns(@token) ActionController::Base.request_forgery_protection_token = :authenticity_token end - - def test_should_raise_error_without_secret - assert_raises ActionController::InvalidAuthenticityToken do - get :index - end - end end -class CsrfCookieMonsterControllerTest < Test::Unit::TestCase - include RequestForgeryProtectionTests - def setup - @controller = CsrfCookieMonsterController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - class << @request.session - attr_accessor :dbman - end - # simulate a cookie session store - @request.session.dbman = FakeSessionDbMan - @token = Digest::SHA1.hexdigest("secure") - ActionController::Base.request_forgery_protection_token = :authenticity_token - end -end - -class FreeCookieControllerTest < Test::Unit::TestCase +class FreeCookieControllerTest < ActionController::TestCase def setup @controller = FreeCookieController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new - @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123') + @token = "cf50faa3fe97702ca1ae" + + ActiveSupport::SecureRandom.stubs(:base64).returns(@token) end def test_should_not_render_form_with_token_tag @@ -295,19 +244,3 @@ class FreeCookieControllerTest < Test::Unit::TestCase end end end - -class SessionOffControllerTest < Test::Unit::TestCase - def setup - @controller = SessionOffController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123') - end - - def test_should_raise_correct_exception - @request.session = {} # session(:off) doesn't appear to work with controller tests - assert_raises(ActionController::InvalidAuthenticityToken) do - post :index, :authenticity_token => @token - end - end -end diff --git a/actionpack/test/controller/request_test.rb b/actionpack/test/controller/request_test.rb index e79a0ea76b..ba4a6da39b 100644 --- a/actionpack/test/controller/request_test.rb +++ b/actionpack/test/controller/request_test.rb @@ -1,7 +1,6 @@ require 'abstract_unit' -require 'action_controller/integration' -class RequestTest < Test::Unit::TestCase +class RequestTest < ActiveSupport::TestCase def setup ActionController::Base.relative_url_root = nil @request = ActionController::TestRequest.new @@ -67,6 +66,15 @@ class RequestTest < Test::Unit::TestCase assert_match /HTTP_X_FORWARDED_FOR="9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4"/, e.message assert_match /HTTP_CLIENT_IP="8.8.8.8"/, e.message + # turn IP Spoofing detection off. + # This is useful for sites that are aimed at non-IP clients. The typical + # example is WAP. Since the cellular network is not IP based, it's a + # leap of faith to assume that their proxies are ever going to set the + # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly. + ActionController::Base.ip_spoofing_check = false + assert_equal('8.8.8.8', @request.remote_ip(true)) + ActionController::Base.ip_spoofing_check = true + @request.env['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 9.9.9.9' assert_equal '8.8.8.8', @request.remote_ip(true) @@ -400,7 +408,7 @@ class RequestTest < Test::Unit::TestCase end end -class UrlEncodedRequestParameterParsingTest < Test::Unit::TestCase +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=" @@ -704,20 +712,20 @@ class UrlEncodedRequestParameterParsingTest < Test::Unit::TestCase end end -class MultipartRequestParameterParsingTest < Test::Unit::TestCase +class MultipartRequestParameterParsingTest < ActiveSupport::TestCase FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart' def test_single_parameter - params = process('single_parameter') + params = parse_multipart('single_parameter') assert_equal({ 'foo' => 'bar' }, params) end def test_bracketed_param - assert_equal({ 'foo' => { 'baz' => 'bar'}}, process('bracketed_param')) + assert_equal({ 'foo' => { 'baz' => 'bar'}}, parse_multipart('bracketed_param')) end def test_text_file - params = process('text_file') + params = parse_multipart('text_file') assert_equal %w(file foo), params.keys.sort assert_equal 'bar', params['foo'] @@ -729,17 +737,13 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase end def test_boundary_problem_file - params = process('boundary_problem_file') + params = parse_multipart('boundary_problem_file') assert_equal %w(file foo), params.keys.sort file = params['file'] foo = params['foo'] - if RUBY_VERSION > '1.9' - assert_kind_of File, file - else - assert_kind_of Tempfile, file - end + assert_kind_of Tempfile, file assert_equal 'file.txt', file.original_filename assert_equal "text/plain", file.content_type @@ -748,16 +752,14 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase end def test_large_text_file - params = process('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'] - if RUBY_VERSION > '1.9' - assert_kind_of File, file - else - assert_kind_of Tempfile, file - end + + assert_kind_of Tempfile, file + assert_equal 'file.txt', file.original_filename assert_equal "text/plain", file.content_type assert ('a' * 20480) == file.read @@ -774,7 +776,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase end def test_binary_file - params = process('binary_file') + params = parse_multipart('binary_file') assert_equal %w(file flowers foo), params.keys.sort assert_equal 'bar', params['foo'] @@ -793,7 +795,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase end def test_mixed_files - params = process('mixed_files') + params = parse_multipart('mixed_files') assert_equal %w(files foo), params.keys.sort assert_equal 'bar', params['foo'] @@ -805,7 +807,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase end private - def process(name) + 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 @@ -814,7 +816,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase end end -class XmlParamsParsingTest < Test::Unit::TestCase +class XmlParamsParsingTest < ActiveSupport::TestCase def test_hash_params person = parse_body("<person><name>David</name></person>")[:person] assert_kind_of Hash, person @@ -868,7 +870,7 @@ class LegacyXmlParamsParsingTest < XmlParamsParsingTest end end -class JsonParamsParsingTest < Test::Unit::TestCase +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 diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 32c6c013f1..63f9827f4a 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -291,24 +291,6 @@ class RescueControllerTest < ActionController::TestCase assert_equal 'template_error', templates[ActionView::TemplateError.name] end - def test_clean_backtrace - with_rails_root nil do - # No action if RAILS_ROOT isn't set. - cleaned = @controller.send(:clean_backtrace, @exception) - assert_equal @exception.backtrace, cleaned - end - - with_rails_root Dir.pwd do - # RAILS_ROOT is removed from backtrace. - cleaned = @controller.send(:clean_backtrace, @exception) - expected = @exception.backtrace.map { |line| line.sub(RAILS_ROOT, '') } - assert_equal expected, cleaned - - # No action if backtrace is nil. - assert_nil @controller.send(:clean_backtrace, Exception.new) - end - end - def test_not_implemented with_all_requests_local false do with_rails_public_path(".") do diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 1fea82e564..8dedeb23f6 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -14,6 +14,8 @@ class LogosController < ResourcesController; end class AccountsController < ResourcesController; end class AdminController < ResourcesController; end +class ProductsController < ResourcesController; end +class ImagesController < ResourcesController; end module Backoffice class ProductsController < ResourcesController; end @@ -27,7 +29,7 @@ module Backoffice end end -class ResourcesTest < Test::Unit::TestCase +class ResourcesTest < ActionController::TestCase # The assertions in these tests are incompatible with the hash method # optimisation. This could indicate user level problems def setup @@ -185,7 +187,7 @@ class ResourcesTest < Test::Unit::TestCase assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.keys.each do |action| - assert_named_route "/threads/1/messages/#{action}.xml", "formatted_#{action}_thread_messages_path", :action => action, :format => 'xml' + assert_named_route "/threads/1/messages/#{action}.xml", "#{action}_thread_messages_path", :action => action, :format => 'xml' end end end @@ -314,7 +316,7 @@ class ResourcesTest < Test::Unit::TestCase end assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| - assert_named_route preview_path, :formatted_preview_new_thread_message_path, preview_options + assert_named_route preview_path, :preview_new_thread_message_path, preview_options end end end @@ -776,6 +778,235 @@ class ResourcesTest < Test::Unit::TestCase end end + def test_resource_has_only_show_action + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :show + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy]) + end + end + + def test_singleton_resource_has_only_show_action + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :show + end + + assert_singleton_resource_allowed_routes('accounts', {}, :show, [:index, :new, :create, :edit, :update, :destroy]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :show, [:index, :new, :create, :edit, :update, :destroy]) + end + end + + def test_resource_does_not_have_destroy_action + with_routing do |set| + set.draw do |map| + map.resources :products, :except => :destroy + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy) + end + end + + def test_singleton_resource_does_not_have_destroy_action + with_routing do |set| + set.draw do |map| + map.resource :account, :except => :destroy + end + + assert_singleton_resource_allowed_routes('accounts', {}, [:new, :create, :show, :edit, :update], :destroy) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [:new, :create, :show, :edit, :update], :destroy) + end + end + + def test_resource_has_only_create_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :create + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy]) + + assert_not_nil set.named_routes[:products] + end + end + + def test_resource_has_only_update_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :update + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy]) + + assert_not_nil set.named_routes[:product] + end + end + + def test_resource_has_only_destroy_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :destroy + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update]) + + assert_not_nil set.named_routes[:product] + end + end + + def test_singleton_resource_has_only_create_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :create + end + + assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :create, [:new, :show, :edit, :update, :destroy]) + + assert_not_nil set.named_routes[:account] + end + end + + def test_singleton_resource_has_only_update_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :update + end + + assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :update, [:new, :create, :show, :edit, :destroy]) + + assert_not_nil set.named_routes[:account] + end + end + + def test_singleton_resource_has_only_destroy_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :destroy + end + + assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :destroy, [:new, :create, :show, :edit, :update]) + + assert_not_nil set.named_routes[:account] + end + end + + def test_resource_has_only_collection_action + with_routing do |set| + set.draw do |map| + map.resources :products, :except => :all, :collection => { :sale => :get } + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy]) + + assert_recognizes({ :controller => 'products', :action => 'sale' }, :path => 'products/sale', :method => :get) + assert_recognizes({ :controller => 'products', :action => 'sale', :format => 'xml' }, :path => 'products/sale.xml', :method => :get) + end + end + + def test_resource_has_only_member_action + with_routing do |set| + set.draw do |map| + map.resources :products, :except => :all, :member => { :preview => :get } + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy]) + + assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1' }, :path => 'products/1/preview', :method => :get) + assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1', :format => 'xml' }, :path => 'products/1/preview.xml', :method => :get) + end + end + + def test_singleton_resource_has_only_member_action + with_routing do |set| + set.draw do |map| + map.resource :account, :except => :all, :member => { :signup => :get } + end + + assert_singleton_resource_allowed_routes('accounts', {}, [], [:new, :create, :show, :edit, :update, :destroy]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [], [:new, :create, :show, :edit, :update, :destroy]) + + assert_recognizes({ :controller => 'accounts', :action => 'signup' }, :path => 'account/signup', :method => :get) + assert_recognizes({ :controller => 'accounts', :action => 'signup', :format => 'xml' }, :path => 'account/signup.xml', :method => :get) + end + end + + def test_nested_resource_inherits_only_show_action + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :show do |product| + product.resources :images + end + end + + assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images') + assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images') + end + end + + def test_nested_resource_has_only_show_and_member_action + with_routing do |set| + set.draw do |map| + map.resources :products, :only => [:index, :show] do |product| + product.resources :images, :member => { :thumbnail => :get }, :only => :show + end + end + + assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images') + assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images') + + assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2' }, :path => 'products/1/images/2/thumbnail', :method => :get) + assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2', :format => 'jpg' }, :path => 'products/1/images/2/thumbnail.jpg', :method => :get) + end + end + + def test_nested_resource_ignores_only_option + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :show do |product| + product.resources :images, :except => :destroy + end + end + + assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images') + assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images') + end + end + + def test_nested_resource_ignores_except_option + with_routing do |set| + set.draw do |map| + map.resources :products, :except => :show do |product| + product.resources :images, :only => :destroy + end + end + + assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images') + assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images') + end + end + + def test_default_singleton_restful_route_uses_get + with_routing do |set| + set.draw do |map| + map.resource :product + end + + assert_equal :get, set.named_routes.routes[:product].conditions[:method] + end + end + protected def with_restful_routing(*args) with_routing do |set| @@ -899,14 +1130,14 @@ class ResourcesTest < Test::Unit::TestCase end assert_named_route "#{full_path}", "#{name_prefix}#{controller_name}_path", options[:options] - assert_named_route "#{full_path}.xml", "formatted_#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{full_path}.xml", "#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml') assert_named_route "#{shallow_path}/1", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1') - assert_named_route "#{shallow_path}/1.xml", "formatted_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml') + assert_named_route "#{shallow_path}/1.xml", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml') assert_named_route "#{full_path}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options] - assert_named_route "#{full_path}/#{new_action}.xml", "formatted_new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{full_path}/#{new_action}.xml", "new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml') assert_named_route "#{shallow_path}/1/#{edit_action}", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1') - assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "formatted_edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml') + assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml') yield options[:options] if block_given? end @@ -958,12 +1189,12 @@ class ResourcesTest < Test::Unit::TestCase name_prefix = options[:name_prefix] assert_named_route "#{full_path}", "#{name_prefix}#{singleton_name}_path", options[:options] - assert_named_route "#{full_path}.xml", "formatted_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{full_path}.xml", "#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml') assert_named_route "#{full_path}/new", "new_#{name_prefix}#{singleton_name}_path", options[:options] - assert_named_route "#{full_path}/new.xml", "formatted_new_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{full_path}/new.xml", "new_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml') assert_named_route "#{full_path}/edit", "edit_#{name_prefix}#{singleton_name}_path", options[:options] - assert_named_route "#{full_path}/edit.xml", "formatted_edit_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{full_path}/edit.xml", "edit_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml') end def assert_named_route(expected, route, options) @@ -979,6 +1210,51 @@ class ResourcesTest < Test::Unit::TestCase end end + def assert_resource_allowed_routes(controller, options, shallow_options, allowed, not_allowed, path = controller) + shallow_path = "#{path}/#{shallow_options[:id]}" + format = options[:format] && ".#{options[:format]}" + options.merge!(:controller => controller) + shallow_options.merge!(options) + + assert_whether_allowed(allowed, not_allowed, options, 'index', "#{path}#{format}", :get) + assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get) + assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post) + assert_whether_allowed(allowed, not_allowed, shallow_options, 'show', "#{shallow_path}#{format}", :get) + assert_whether_allowed(allowed, not_allowed, shallow_options, 'edit', "#{shallow_path}/edit#{format}", :get) + assert_whether_allowed(allowed, not_allowed, shallow_options, 'update', "#{shallow_path}#{format}", :put) + assert_whether_allowed(allowed, not_allowed, shallow_options, 'destroy', "#{shallow_path}#{format}", :delete) + end + + def assert_singleton_resource_allowed_routes(controller, options, allowed, not_allowed, path = controller.singularize) + format = options[:format] && ".#{options[:format]}" + options.merge!(:controller => controller) + + assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get) + assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post) + assert_whether_allowed(allowed, not_allowed, options, 'show', "#{path}#{format}", :get) + assert_whether_allowed(allowed, not_allowed, options, 'edit', "#{path}/edit#{format}", :get) + assert_whether_allowed(allowed, not_allowed, options, 'update', "#{path}#{format}", :put) + assert_whether_allowed(allowed, not_allowed, options, 'destroy', "#{path}#{format}", :delete) + end + + def assert_whether_allowed(allowed, not_allowed, options, action, path, method) + action = action.to_sym + options = options.merge(:action => action.to_s) + path_options = { :path => path, :method => method } + + if Array(allowed).include?(action) + assert_recognizes options, path_options + elsif Array(not_allowed).include?(action) + assert_not_recognizes options, path_options + end + end + + def assert_not_recognizes(expected_options, path) + assert_raise ActionController::RoutingError, ActionController::MethodNotAllowed, Assertion do + assert_recognizes(expected_options, path) + end + end + def distinct_routes? (r1, r2) if r1.conditions == r2.conditions and r1.requirements == r2.requirements then if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 9699a04abb..d5b6bd6b2a 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1,6 +1,5 @@ require 'abstract_unit' require 'controller/fake_controllers' -require 'action_controller/routing' class MilestonesController < ActionController::Base def index() head :ok end @@ -706,12 +705,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do port = options.delete(:port) || 80 port_string = port == 80 ? '' : ":#{port}" - host = options.delete(:host) || "named.route.test" - anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) + protocol = options.delete(:protocol) || "http" + host = options.delete(:host) || "named.route.test" + anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) path = routes.generate(options) - only_path ? "#{path}#{anchor}" : "http://#{host}#{port_string}#{path}#{anchor}" + only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}" end def request @@ -747,12 +747,16 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do ActionController::Base.optimise_named_routes = true @rs = ::ActionController::Routing::RouteSet.new - @rs.draw {|m| m.connect ':controller/:action/:id' } ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed) end + + def teardown + @rs.clear! + end def test_default_setup + @rs.draw {|m| m.connect ':controller/:action/:id' } assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content")) assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list")) assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10")) @@ -769,6 +773,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end def test_ignores_leading_slash + @rs.clear! @rs.draw {|m| m.connect '/:controller/:action/:id'} test_default_setup end @@ -1002,6 +1007,8 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end def test_changing_controller + @rs.draw {|m| m.connect ':controller/:action/:id' } + assert_equal '/admin/stuff/show/10', rs.generate( {:controller => 'stuff', :action => 'show', :id => 10}, {:controller => 'admin/user', :action => 'index'} @@ -1155,10 +1162,12 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end def test_action_expiry + @rs.draw {|m| m.connect ':controller/:action/:id' } assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'}) end def test_recognition_with_uppercase_controller_name + @rs.draw {|m| m.connect ':controller/:action/:id' } assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content")) assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list")) assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10")) @@ -1726,6 +1735,11 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com") end + 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") + 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", @@ -2394,13 +2408,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do def setup routes.instance_variable_set '@routes_last_modified', nil silence_warnings { Object.const_set :RAILS_ROOT, '.' } - ActionController::Routing::Routes.configuration_file = File.join(RAILS_ROOT, 'config', 'routes.rb') + routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb')) @stat = stub_everything end def teardown - ActionController::Routing::Routes.configuration_file = nil + ActionController::Routing::Routes.configuration_files.clear Object.send :remove_const, :RAILS_ROOT end @@ -2443,12 +2457,24 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end def test_load_with_configuration - routes.configuration_file = "foobarbaz" + routes.configuration_files.clear + routes.add_configuration_file("foobarbaz") File.expects(:stat).returns(@stat) routes.expects(:load).with("foobarbaz") routes.reload end + + def test_load_multiple_configurations + routes.add_configuration_file("engines.rb") + + File.expects(:stat).at_least_once.returns(@stat) + + routes.expects(:load).with('./config/routes.rb') + routes.expects(:load).with('engines.rb') + + routes.reload + end private def routes diff --git a/actionpack/test/controller/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb index 010c00fa14..b5f14acc1f 100644 --- a/actionpack/test/controller/session/cookie_store_test.rb +++ b/actionpack/test/controller/session/cookie_store_test.rb @@ -1,7 +1,4 @@ require 'abstract_unit' -require 'action_controller/cgi_process' -require 'action_controller/cgi_ext' - require 'stringio' @@ -45,8 +42,8 @@ class CookieStoreTest < Test::Unit::TestCase { :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' => {} }], - :double_escaped => [CGI.escape('BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA%3D%3D--bf9785a666d3c4ac09f7fe3353496b437546cfbf'), { 'user_id' => 123, 'flash' => {} }] } + :flashed => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA==--bf9785a666d3c4ac09f7fe3353496b437546cfbf', { 'user_id' => 123, 'flash' => {} }] + } end @@ -105,15 +102,6 @@ class CookieStoreTest < Test::Unit::TestCase end end - def test_restores_double_encoded_cookies - set_cookie! cookie_value(:double_escaped) - new_session do |session| - session.dbman.restore - assert_equal session["user_id"], 123 - assert_equal session["flash"], {} - end - end - def test_close_doesnt_write_cookie_if_data_is_blank new_session do |session| assert_no_cookies session @@ -266,6 +254,7 @@ class CookieStoreTest < Test::Unit::TestCase @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}" diff --git a/actionpack/test/controller/session/mem_cache_store_test.rb b/actionpack/test/controller/session/mem_cache_store_test.rb index a7d48431f8..9ab927a01f 100644 --- a/actionpack/test/controller/session/mem_cache_store_test.rb +++ b/actionpack/test/controller/session/mem_cache_store_test.rb @@ -1,7 +1,4 @@ require 'abstract_unit' -require 'action_controller/cgi_process' -require 'action_controller/cgi_ext' - class CGI::Session def cache diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index a23428804a..ee7b8ade8c 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' require 'controller/fake_controllers' -class TestTest < Test::Unit::TestCase +class TestTest < ActionController::TestCase class TestController < ActionController::Base def no_op render :text => 'dummy' @@ -24,7 +24,7 @@ class TestTest < Test::Unit::TestCase end def render_raw_post - raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank? + raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank? render :text => request.raw_post end @@ -580,7 +580,7 @@ XML assert_equal @response.redirect_url, redirect_to_url # Must be a :redirect response. - assert_raise(Test::Unit::AssertionFailedError) do + assert_raise(ActiveSupport::TestCase::Assertion) do assert_redirected_to 'created resource' end end @@ -602,21 +602,21 @@ XML end end -class CleanBacktraceTest < Test::Unit::TestCase +class CleanBacktraceTest < ActionController::TestCase def test_should_reraise_the_same_object - exception = Test::Unit::AssertionFailedError.new('message') + exception = ActiveSupport::TestCase::Assertion.new('message') clean_backtrace { raise exception } - rescue => caught + rescue Exception => caught assert_equal exception.object_id, caught.object_id assert_equal exception.message, caught.message end def test_should_clean_assertion_lines_from_backtrace path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller") - exception = Test::Unit::AssertionFailedError.new('message') + exception = ActiveSupport::TestCase::Assertion.new('message') exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"] clean_backtrace { raise exception } - rescue => caught + rescue Exception => caught assert_equal ["#{path}/abc"], caught.backtrace end @@ -629,21 +629,17 @@ class CleanBacktraceTest < Test::Unit::TestCase end end -class InferringClassNameTest < Test::Unit::TestCase +class InferringClassNameTest < ActionController::TestCase def test_determine_controller_class assert_equal ContentController, determine_class("ContentControllerTest") end def test_determine_controller_class_with_nonsense_name - assert_raises ActionController::NonInferrableControllerError do - determine_class("HelloGoodBye") - end + assert_nil determine_class("HelloGoodBye") end def test_determine_controller_class_with_sensible_name_where_no_controller_exists - assert_raises ActionController::NonInferrableControllerError do - determine_class("NoControllerWithThisNameTest") - end + assert_nil determine_class("NoControllerWithThisNameTest") end private diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index 64e9a085ca..e9d372544e 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -2,7 +2,7 @@ require 'abstract_unit' ActionController::UrlRewriter -class UrlRewriterTests < Test::Unit::TestCase +class UrlRewriterTests < ActionController::TestCase def setup @request = ActionController::TestRequest.new @params = {} @@ -85,8 +85,7 @@ class UrlRewriterTests < Test::Unit::TestCase end end -class UrlWriterTests < Test::Unit::TestCase - +class UrlWriterTests < ActionController::TestCase class W include ActionController::UrlWriter end @@ -302,6 +301,42 @@ class UrlWriterTests < Test::Unit::TestCase assert_generates("/image", :controller=> :image) end + def test_named_routes_with_nil_keys + ActionController::Routing::Routes.clear! + add_host! + ActionController::Routing::Routes.draw do |map| + map.main '', :controller => 'posts' + map.resources :posts + map.connect ':controller/:action/:id' + end + # We need to create a new class in order to install the new named route. + kls = Class.new { include ActionController::UrlWriter } + controller = kls.new + params = {:action => :index, :controller => :posts, :format => :xml} + assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params)) + params[:format] = nil + assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params)) + ensure + ActionController::Routing::Routes.load! + end + + def test_formatted_url_methods_are_deprecated + ActionController::Routing::Routes.draw do |map| + map.resources :posts + end + # We need to create a new class in order to install the new named route. + kls = Class.new { include ActionController::UrlWriter } + controller = kls.new + params = {:id => 1, :format => :xml} + assert_deprecated do + assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params)) + end + assert_deprecated do + assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml)) + end + ensure + ActionController::Routing::Routes.load! + end private def extract_params(url) url.split('?', 2).last.split('&') diff --git a/actionpack/test/controller/verification_test.rb b/actionpack/test/controller/verification_test.rb index b289443129..418a81baa8 100644 --- a/actionpack/test/controller/verification_test.rb +++ b/actionpack/test/controller/verification_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class VerificationTest < Test::Unit::TestCase +class VerificationTest < ActionController::TestCase class TestController < ActionController::Base verify :only => :guarded_one, :params => "one", :add_flash => { :error => 'unguarded' }, diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb index b859a92cbd..04e14d8eac 100644 --- a/actionpack/test/controller/view_paths_test.rb +++ b/actionpack/test/controller/view_paths_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class ViewLoadPathsTest < Test::Unit::TestCase +class ViewLoadPathsTest < ActionController::TestCase class TestController < ActionController::Base def self.controller_path() "test" end def rescue_action(e) raise end diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 32f67ddd6c..6d2b3e4f23 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -101,14 +101,13 @@ class WebServiceTest < Test::Unit::TestCase end def test_post_xml_using_an_attributted_node_named_type - ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) } + ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } process('POST', 'application/xml', '<request><type type="string">Arial,12</type><z>3</z></request>') assert_equal 'type, z', @controller.response.body assert @controller.params.has_key?(:type) - assert_equal 'string', @controller.params['type']['type'] - assert_equal 'Arial,12', @controller.params['type']['content'] - assert_equal '3', @controller.params['z'] + assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect + assert_equal '3', @controller.params['z'], @controller.params.inspect end def test_register_and_use_yaml @@ -128,7 +127,7 @@ class WebServiceTest < Test::Unit::TestCase end def test_register_and_use_xml_simple - ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) } + ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } process('POST', 'application/xml', '<request><summary>content...</summary><title>SimpleXml</title></request>' ) assert_equal 'summary, title', @controller.response.body assert @controller.params.has_key?(:summary) |