aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/test
diff options
context:
space:
mode:
Diffstat (limited to 'actionpack/test')
-rw-r--r--actionpack/test/abstract_unit.rb26
-rw-r--r--actionpack/test/active_record_unit.rb6
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb1
-rw-r--r--actionpack/test/activerecord/render_partial_with_record_identification_test.rb22
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb36
-rw-r--r--actionpack/test/controller/assert_select_test.rb136
-rw-r--r--actionpack/test/controller/base_test.rb2
-rw-r--r--actionpack/test/controller/caching_test.rb22
-rw-r--r--actionpack/test/controller/cgi_test.rb4
-rw-r--r--actionpack/test/controller/components_test.rb156
-rw-r--r--actionpack/test/controller/deprecation/deprecated_base_methods_test.rb20
-rw-r--r--actionpack/test/controller/dispatcher_test.rb2
-rw-r--r--actionpack/test/controller/helper_test.rb16
-rw-r--r--actionpack/test/controller/html-scanner/sanitizer_test.rb6
-rw-r--r--actionpack/test/controller/integration_test.rb2
-rw-r--r--actionpack/test/controller/integration_upload_test.rb2
-rw-r--r--actionpack/test/controller/layout_test.rb47
-rw-r--r--actionpack/test/controller/logging_test.rb46
-rw-r--r--actionpack/test/controller/mime_responds_test.rb16
-rw-r--r--actionpack/test/controller/mime_type_test.rb12
-rw-r--r--actionpack/test/controller/polymorphic_routes_test.rb38
-rw-r--r--actionpack/test/controller/rack_test.rb1
-rw-r--r--actionpack/test/controller/redirect_test.rb16
-rw-r--r--actionpack/test/controller/render_test.rb77
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb181
-rw-r--r--actionpack/test/controller/request_test.rb50
-rw-r--r--actionpack/test/controller/rescue_test.rb18
-rw-r--r--actionpack/test/controller/resources_test.rb296
-rw-r--r--actionpack/test/controller/routing_test.rb42
-rw-r--r--actionpack/test/controller/session/cookie_store_test.rb17
-rw-r--r--actionpack/test/controller/session/mem_cache_store_test.rb3
-rw-r--r--actionpack/test/controller/test_test.rb26
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb41
-rw-r--r--actionpack/test/controller/verification_test.rb2
-rw-r--r--actionpack/test/controller/view_paths_test.rb2
-rw-r--r--actionpack/test/controller/webservice_test.rb9
-rw-r--r--actionpack/test/fixtures/alternate_helpers/foo_helper.rb3
-rw-r--r--actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb1
-rw-r--r--actionpack/test/fixtures/test/dont_pick_me1
-rw-r--r--actionpack/test/fixtures/test/hello.builder2
-rw-r--r--actionpack/test/template/active_record_helper_i18n_test.rb24
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb52
-rw-r--r--actionpack/test/template/atom_feed_helper_test.rb11
-rw-r--r--actionpack/test/template/compiled_templates_test.rb59
-rw-r--r--actionpack/test/template/date_helper_i18n_test.rb22
-rw-r--r--actionpack/test/template/date_helper_test.rb40
-rw-r--r--actionpack/test/template/form_options_helper_test.rb3
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb38
-rw-r--r--actionpack/test/template/number_helper_i18n_test.rb33
-rw-r--r--actionpack/test/template/render_test.rb64
-rw-r--r--actionpack/test/template/tag_helper_test.rb4
-rw-r--r--actionpack/test/template/text_helper_test.rb149
-rw-r--r--actionpack/test/template/translation_helper_test.rb6
53 files changed, 1150 insertions, 761 deletions
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 673efa6af0..51697fda2f 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -1,21 +1,29 @@
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers')
+$:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers')
+require 'rubygems'
require 'yaml'
require 'stringio'
require 'test/unit'
-require 'action_controller'
-require 'action_controller/cgi_ext'
-require 'action_controller/test_process'
-require 'action_view/test_case'
+
+gem 'mocha', '>= 0.9.3'
+require 'mocha'
begin
require 'ruby-debug'
+ Debugger.settings[:autoeval] = true
+ Debugger.start
rescue LoadError
# Debugging disabled. `gem install ruby-debug` to enable.
end
+require 'action_controller'
+require 'action_controller/cgi_ext'
+require 'action_controller/test_process'
+require 'action_view/test_case'
+
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
@@ -23,17 +31,9 @@ ActionController::Base.logger = nil
ActionController::Routing::Routes.reload rescue nil
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
-ActionView::PathSet::Path.eager_load_templates!
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
+ActionController::Base.view_paths.load
-# Wrap tests that use Mocha and skip if unavailable.
def uses_mocha(test_name)
- unless Object.const_defined?(:Mocha)
- require 'mocha'
- require 'stubba'
- end
yield
-rescue LoadError => load_error
- raise unless load_error.message =~ /mocha/i
- $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
end
diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/active_record_unit.rb
index a377ccad24..d8d2e00dc2 100644
--- a/actionpack/test/active_record_unit.rb
+++ b/actionpack/test/active_record_unit.rb
@@ -82,7 +82,9 @@ class ActiveRecordTestConnector
end
end
-class ActiveRecordTestCase < ActiveSupport::TestCase
+class ActiveRecordTestCase < ActionController::TestCase
+ include ActiveRecord::TestFixtures
+
# Set our fixture path
if ActiveRecordTestConnector.able_to_connect
self.fixture_path = [FIXTURE_LOAD_PATH]
@@ -96,8 +98,6 @@ class ActiveRecordTestCase < ActiveSupport::TestCase
def run(*args)
super if ActiveRecordTestConnector.connected
end
-
- def default_test; end
end
ActiveRecordTestConnector.setup
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index fd7da89aa7..677d434f9c 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -1,7 +1,6 @@
# These tests exercise CGI::Session::ActiveRecordStore, so you're going to
# need AR in a sibling directory to AP and have SQLite installed.
require 'active_record_unit'
-require 'action_controller/session/active_record_store'
module CommonActiveRecordStoreTests
def test_basics
diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
index d75cb2b53a..147b270808 100644
--- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
+++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
@@ -47,15 +47,9 @@ class RenderPartialWithRecordIdentificationController < ActionController::Base
end
class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase
+ tests RenderPartialWithRecordIdentificationController
fixtures :developers, :projects, :developers_projects, :topics, :replies, :companies, :mascots
- def setup
- @controller = RenderPartialWithRecordIdentificationController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- super
- end
-
def test_rendering_partial_with_has_many_and_belongs_to_association
get :render_with_has_many_and_belongs_to_association
assert_template 'projects/_project'
@@ -162,12 +156,7 @@ module Fun
end
class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveRecordTestCase
- def setup
- @controller = Fun::NestedController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- super
- end
+ tests Fun::NestedController
def test_render_with_record_in_nested_controller
get :render_with_record_in_nested_controller
@@ -183,12 +172,7 @@ class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveReco
end
class RenderPartialWithRecordIdentificationAndNestedDeeperControllersTest < ActiveRecordTestCase
- def setup
- @controller = Fun::Serious::NestedDeeperController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- super
- end
+ tests Fun::Serious::NestedDeeperController
def test_render_with_record_in_deeper_nested_controller
get :render_with_record_in_deeper_nested_controller
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...", "&lt;![CDATA[&lt;span>neverending...]]>"
end
+ def test_should_not_mangle_urls_with_ampersand
+ assert_sanitized %{<a href=\"http://www.domain.com?var1=1&amp;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)
diff --git a/actionpack/test/fixtures/alternate_helpers/foo_helper.rb b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
new file mode 100644
index 0000000000..a956fce6fa
--- /dev/null
+++ b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
@@ -0,0 +1,3 @@
+module FooHelper
+ def baz() end
+end
diff --git a/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb b/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
new file mode 100644
index 0000000000..00e6b6d6da
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
@@ -0,0 +1 @@
+partial with only html version \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/dont_pick_me b/actionpack/test/fixtures/test/dont_pick_me
new file mode 100644
index 0000000000..0157c9e503
--- /dev/null
+++ b/actionpack/test/fixtures/test/dont_pick_me
@@ -0,0 +1 @@
+non-template file \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello.builder b/actionpack/test/fixtures/test/hello.builder
index 86a8bb3d7b..a471553941 100644
--- a/actionpack/test/fixtures/test/hello.builder
+++ b/actionpack/test/fixtures/test/hello.builder
@@ -1,4 +1,4 @@
xml.html do
xml.p "Hello #{@name}"
- xml << render("test/greeting")
+ xml << render(:file => "test/greeting")
end \ No newline at end of file
diff --git a/actionpack/test/template/active_record_helper_i18n_test.rb b/actionpack/test/template/active_record_helper_i18n_test.rb
index 7ba9659814..7e6bf70706 100644
--- a/actionpack/test/template/active_record_helper_i18n_test.rb
+++ b/actionpack/test/template/active_record_helper_i18n_test.rb
@@ -10,37 +10,37 @@ class ActiveRecordHelperI18nTest < Test::Unit::TestCase
@object_name = 'book'
stubs(:content_tag).returns 'content_tag'
- I18n.stubs(:t).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
- I18n.stubs(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
+ I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
+ I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
end
def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message
- I18n.expects(:translate).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
- error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en-US')
+ I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
+ error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en')
end
def test_error_messages_for_given_no_header_option_it_translates_header_message
- I18n.expects(:t).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
+ I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :locale => 'en-US')
+ error_messages_for(:object => @object, :locale => 'en')
end
def test_error_messages_for_given_a_message_option_it_does_not_translate_message
- I18n.expects(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).never
+ I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :message => 'message', :locale => 'en-US')
+ error_messages_for(:object => @object, :message => 'message', :locale => 'en')
end
def test_error_messages_for_given_no_message_option_it_translates_message
- I18n.expects(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
+ I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :locale => 'en-US')
+ error_messages_for(:object => @object, :locale => 'en')
end
def test_error_messages_for_given_object_name_it_translates_object_name
- I18n.expects(:t).with(:header, :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
+ I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
I18n.expects(:t).with(@object_name, :default => @object_name, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name
- error_messages_for(:object => @object, :locale => 'en-US', :object_name => @object_name)
+ error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name)
end
end
end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index bade96fe17..7597927f6d 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -239,7 +239,11 @@ class AssetTagHelperTest < ActionView::TestCase
File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true)
assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png')
ensure
- ENV["RAILS_ASSET_ID"] = old_asset_id
+ if old_asset_id
+ ENV["RAILS_ASSET_ID"] = old_asset_id
+ else
+ ENV.delete("RAILS_ASSET_ID")
+ end
end
end
@@ -355,6 +359,46 @@ class AssetTagHelperTest < ActionView::TestCase
FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'secure.js'))
end
+ def test_caching_javascript_include_tag_when_caching_on_with_2_argument_object_asset_host
+ ENV['RAILS_ASSET_ID'] = ''
+ ActionController::Base.asset_host = Class.new do
+ def call(source, request)
+ if request.ssl?
+ "#{request.protocol}#{request.host_with_port}"
+ else
+ "#{request.protocol}assets#{source.length}.example.com"
+ end
+ end
+ end.new
+
+ ActionController::Base.perform_caching = true
+
+ assert_equal '/javascripts/vanilla.js'.length, 23
+ assert_dom_equal(
+ %(<script src="http://assets23.example.com/javascripts/vanilla.js" type="text/javascript"></script>),
+ javascript_include_tag(:all, :cache => 'vanilla')
+ )
+
+ assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'vanilla.js'))
+
+ class << @controller.request
+ def protocol() 'https://' end
+ def ssl?() true end
+ end
+
+ assert_equal '/javascripts/secure.js'.length, 22
+ assert_dom_equal(
+ %(<script src="https://localhost/javascripts/secure.js" type="text/javascript"></script>),
+ javascript_include_tag(:all, :cache => 'secure')
+ )
+
+ assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'secure.js'))
+
+ ensure
+ FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'vanilla.js'))
+ FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'secure.js'))
+ end
+
def test_caching_javascript_include_tag_when_caching_on_and_using_subdirectory
ENV["RAILS_ASSET_ID"] = ""
ActionController::Base.asset_host = 'http://a%d.example.com'
@@ -644,4 +688,10 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
ensure
ActionController::Base.asset_host = nil
end
+
+ def test_assert_css_and_js_of_the_same_name_return_correct_extension
+ assert_dom_equal(%(/collaboration/hieraki/javascripts/foo.js), javascript_path("foo"))
+ assert_dom_equal(%(/collaboration/hieraki/stylesheets/foo.css), stylesheet_path("foo"))
+
+ end
end
diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb
index 9247a42d33..8a00a397ca 100644
--- a/actionpack/test/template/atom_feed_helper_test.rb
+++ b/actionpack/test/template/atom_feed_helper_test.rb
@@ -166,12 +166,10 @@ class ScrollsController < ActionController::Base
end
end
-class AtomFeedTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = ScrollsController.new
+class AtomFeedTest < ActionController::TestCase
+ tests ScrollsController
+ def setup
@request.host = "www.nextangle.com"
end
@@ -255,7 +253,8 @@ class AtomFeedTest < Test::Unit::TestCase
def test_feed_xml_processing_instructions
with_restful_routing(:scrolls) do
get :index, :id => 'feed_with_xml_processing_instructions'
- assert_match %r{<\?xml-stylesheet type="text/css" href="t.css"\?>}, @response.body
+ assert_match %r{<\?xml-stylesheet [^\?]*type="text/css"}, @response.body
+ assert_match %r{<\?xml-stylesheet [^\?]*href="t.css"}, @response.body
end
end
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index e005aa0f03..a68b09bb45 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -12,36 +12,75 @@ uses_mocha 'TestTemplateRecompilation' do
def test_template_gets_compiled
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
assert_equal 1, @compiled_templates.instance_methods.size
end
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("test/hello_world.erb")
- assert_equal "Hello world!", render("test/hello_world.erb", {:foo => "bar"})
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
assert_equal 2, @compiled_templates.instance_methods.size
end
def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
ActionView::Template.any_instance.expects(:compile!).never
- assert_equal "Hello world!", render("test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
end
- def test_compiled_template_will_always_be_recompiled_when_eager_loaded_templates_is_off
- ActionView::PathSet::Path.expects(:eager_load_templates?).times(4).returns(false)
+ def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached
+ ActionView::Template.any_instance.expects(:loaded?).times(3).returns(false)
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
ActionView::Template.any_instance.expects(:compile!).times(3)
- 3.times { assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
+ 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
assert_equal 1, @compiled_templates.instance_methods.size
end
+ def test_template_changes_are_not_reflected_with_cached_templates
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
+
+ def test_template_changes_are_reflected_with_uncached_templates
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb")
+ end
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ end
+
private
def render(*args)
- ActionView::Base.new(ActionController::Base.view_paths, {}).render(*args)
+ render_with_cache(*args)
+ end
+
+ def render_with_cache(*args)
+ view_paths = ActionController::Base.view_paths
+ assert view_paths.first.loaded?
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
+
+ def render_without_cache(*args)
+ view_paths = ActionView::Base.process_view_paths(FIXTURE_LOAD_PATH)
+ assert !view_paths.first.loaded?
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
+
+ def modify_template(template, content)
+ filename = "#{FIXTURE_LOAD_PATH}/#{template}"
+ old_content = File.read(filename)
+ begin
+ File.open(filename, "wb+") { |f| f.write(content) }
+ yield
+ ensure
+ File.open(filename, "wb+") { |f| f.write(old_content) }
+ end
end
end
end
diff --git a/actionpack/test/template/date_helper_i18n_test.rb b/actionpack/test/template/date_helper_i18n_test.rb
index bf3b2588c8..dc9616db3b 100644
--- a/actionpack/test/template/date_helper_i18n_test.rb
+++ b/actionpack/test/template/date_helper_i18n_test.rb
@@ -41,11 +41,11 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase
key, count = *expected
to = @from + diff
- options = {:locale => 'en-US', :scope => :'datetime.distance_in_words'}
+ options = {:locale => 'en', :scope => :'datetime.distance_in_words'}
options[:count] = count if count
I18n.expects(:t).with(key, options)
- distance_of_time_in_words(@from, to, include_seconds, :locale => 'en-US')
+ distance_of_time_in_words(@from, to, include_seconds, :locale => 'en')
end
def test_distance_of_time_pluralizations
@@ -78,36 +78,36 @@ class DateHelperSelectTagsI18nTests < Test::Unit::TestCase
uses_mocha 'date_helper_select_tags_i18n_tests' do
def setup
- I18n.stubs(:translate).with(:'date.month_names', :locale => 'en-US').returns Date::MONTHNAMES
+ I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
end
# select_month
def test_select_month_given_use_month_names_option_does_not_translate_monthnames
I18n.expects(:translate).never
- select_month(8, :locale => 'en-US', :use_month_names => Date::MONTHNAMES)
+ select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
end
def test_select_month_translates_monthnames
- I18n.expects(:translate).with(:'date.month_names', :locale => 'en-US').returns Date::MONTHNAMES
- select_month(8, :locale => 'en-US')
+ I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
+ select_month(8, :locale => 'en')
end
def test_select_month_given_use_short_month_option_translates_abbr_monthnames
- I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en-US').returns Date::ABBR_MONTHNAMES
- select_month(8, :locale => 'en-US', :use_short_month => true)
+ I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
+ select_month(8, :locale => 'en', :use_short_month => true)
end
# date_or_time_select
def test_date_or_time_select_given_an_order_options_does_not_translate_order
I18n.expects(:translate).never
- datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en-US')
+ datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
end
def test_date_or_time_select_given_no_order_options_translates_order
- I18n.expects(:translate).with(:'date.order', :locale => 'en-US').returns [:year, :month, :day]
- datetime_select('post', 'updated_at', :locale => 'en-US')
+ I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
+ datetime_select('post', 'updated_at', :locale => 'en')
end
end
end \ No newline at end of file
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 1a645bccc6..49ba140c23 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1149,6 +1149,46 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, date_select("post", "written_on", :include_blank => true)
end
+
+ def test_date_select_with_nil_and_blank_and_order
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+
+ expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i"/>' + "\n"
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
+ end
+
+ def test_date_select_with_nil_and_blank_and_order
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+
+ expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i"/>' + "\n"
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
+ end
def test_date_select_cant_override_discard_hour
@post = Post.new
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index a33eb85b66..86a0bb6a79 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'tzinfo'
TZInfo::Timezone.cattr_reader :loaded_zones
@@ -682,4 +683,4 @@ uses_mocha "FormOptionsHelperTest" do
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 1849a61f2f..0c8af60aa4 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -12,12 +12,19 @@ class FormTagHelperTest < ActionView::TestCase
@controller = @controller.new
end
+ VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name
+
def test_check_box_tag
actual = check_box_tag "admin"
expected = %(<input id="admin" name="admin" type="checkbox" value="1" />)
assert_dom_equal expected, actual
end
+ def test_check_box_tag_id_sanitized
+ label_elem = root_elem(check_box_tag("project[2][admin]"))
+ assert_match VALID_HTML_ID, label_elem['id']
+ end
+
def test_form_tag
actual = form_tag
expected = %(<form action="http://www.example.com" method="post">)
@@ -64,6 +71,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_hidden_field_tag_id_sanitized
+ input_elem = root_elem(hidden_field_tag("item[][title]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
def test_file_field_tag
assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz")
end
@@ -118,6 +130,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_select_tag_id_sanitized
+ input_elem = root_elem(select_tag("project[1]people", "<option>david</option>"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
def test_text_area_tag_size_string
actual = text_area_tag "body", "hello world", "size" => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>)
@@ -184,6 +201,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_text_field_tag_id_sanitized
+ input_elem = root_elem(text_field_tag("item[][title]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
def test_label_tag_without_text
actual = label_tag "title"
expected = %(<label for="title">Title</label>)
@@ -208,11 +230,17 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
- def test_boolean_optios
+ def test_label_tag_id_sanitized
+ label_elem = root_elem(label_tag("item[title]"))
+ assert_match VALID_HTML_ID, label_elem['for']
+ end
+
+ def test_boolean_options
assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes")
assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil)
+ assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false)
assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => true)
- assert_dom_equal %(<select id="people[]" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
+ assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => nil)
end
@@ -283,4 +311,10 @@ class FormTagHelperTest < ActionView::TestCase
def protect_against_forgery?
false
end
+
+ private
+
+ def root_elem(rendered_content)
+ HTML::Document.new(rendered_content).root.children[0]
+ end
end
diff --git a/actionpack/test/template/number_helper_i18n_test.rb b/actionpack/test/template/number_helper_i18n_test.rb
index 2ee7f43a65..2528bead36 100644
--- a/actionpack/test/template/number_helper_i18n_test.rb
+++ b/actionpack/test/template/number_helper_i18n_test.rb
@@ -10,45 +10,48 @@ class NumberHelperI18nTests < Test::Unit::TestCase
@number_defaults = { :precision => 3, :delimiter => ',', :separator => '.' }
@currency_defaults = { :unit => '$', :format => '%u%n', :precision => 2 }
@human_defaults = { :precision => 1 }
+ @human_storage_units_defaults = %w(Bytes KB MB GB TB)
@percentage_defaults = { :delimiter => '' }
@precision_defaults = { :delimiter => '' }
- I18n.backend.store_translations 'en-US', :number => { :format => @number_defaults,
+ I18n.backend.store_translations 'en', :number => { :format => @number_defaults,
:currency => { :format => @currency_defaults }, :human => @human_defaults }
end
def test_number_to_currency_translates_currency_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.currency.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.currency.format', :locale => 'en',
:raise => true).returns(@currency_defaults)
- number_to_currency(1, :locale => 'en-US')
+ number_to_currency(1, :locale => 'en')
end
def test_number_with_precision_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.precision.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.precision.format', :locale => 'en',
:raise => true).returns(@precision_defaults)
- number_with_precision(1, :locale => 'en-US')
+ number_with_precision(1, :locale => 'en')
end
def test_number_with_delimiter_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- number_with_delimiter(1, :locale => 'en-US')
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ number_with_delimiter(1, :locale => 'en')
end
def test_number_to_percentage_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en',
:raise => true).returns(@percentage_defaults)
- number_to_percentage(1, :locale => 'en-US')
+ number_to_percentage(1, :locale => 'en')
end
def test_number_to_human_size_translates_human_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.human.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
:raise => true).returns(@human_defaults)
+ I18n.expects(:translate).with(:'number.human.storage_units', :locale => 'en',
+ :raise => true).returns(@human_storage_units_defaults)
# can't be called with 1 because this directly returns without calling I18n.translate
- number_to_human_size(1025, :locale => 'en-US')
+ number_to_human_size(1025, :locale => 'en')
end
end
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 476e651757..9e827abbca 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -1,14 +1,14 @@
require 'abstract_unit'
require 'controller/fake_models'
-class ViewRenderTest < Test::Unit::TestCase
- def setup
+module RenderTestCases
+ def setup_view(paths)
@assigns = { :secret => 'in the sauce' }
- @view = ActionView::Base.new(ActionController::Base.view_paths, @assigns)
+ @view = ActionView::Base.new(paths, @assigns)
end
def test_render_file
- assert_equal "Hello world!", @view.render("test/hello_world.erb")
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb")
end
def test_render_file_not_using_full_path
@@ -16,11 +16,11 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_file_without_specific_extension
- assert_equal "Hello world!", @view.render("test/hello_world")
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world")
end
def test_render_file_at_top_level
- assert_equal 'Elastica', @view.render('/shared')
+ assert_equal 'Elastica', @view.render(:file => '/shared')
end
def test_render_file_with_full_path
@@ -29,20 +29,20 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_file_with_instance_variables
- assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_ivar.erb")
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar.erb")
end
def test_render_file_with_locals
locals = { :secret => 'in the sauce' }
- assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_locals.erb", locals)
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals.erb", :locals => locals)
end
def test_render_file_not_using_full_path_with_dot_in_path
- assert_equal "The secret is in the sauce\n", @view.render("test/dot.directory/render_file_with_ivar")
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar")
end
def test_render_has_access_current_template
- assert_equal "test/template.erb", @view.render("test/template.erb")
+ assert_equal "test/template.erb", @view.render(:file => "test/template.erb")
end
def test_render_update
@@ -51,6 +51,10 @@ class ViewRenderTest < Test::Unit::TestCase
assert_equal 'alert("Hello, World!");', @view.render(:update) { |page| page.alert('Hello, World!') }
end
+ def test_render_partial_from_default
+ assert_equal "only partial", @view.render("test/partial_only")
+ end
+
def test_render_partial
assert_equal "only partial", @view.render(:partial => "test/partial_only")
end
@@ -73,6 +77,10 @@ class ViewRenderTest < Test::Unit::TestCase
assert_equal "5", @view.render(:partial => "test/counter", :locals => { :counter_counter => 5 })
end
+ def test_render_partial_with_locals_from_default
+ assert_equal "only partial", @view.render("test/partial_only", :counter_counter => 5)
+ end
+
def test_render_partial_with_errors
@view.render(:partial => "test/raise")
flunk "Render did not raise TemplateError"
@@ -149,7 +157,7 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_fallbacks_to_erb_for_unknown_types
- assert_equal "Hello, World!", @view.render(:inline => "Hello, World!", :type => :foo)
+ assert_equal "Hello, World!", @view.render(:inline => "Hello, World!", :type => :bar)
end
CustomHandler = lambda do |template|
@@ -167,6 +175,17 @@ class ViewRenderTest < Test::Unit::TestCase
assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
end
+ class LegacyHandler < ActionView::TemplateHandler
+ def render(template, local_assigns)
+ "source: #{template.source}; locals: #{local_assigns.inspect}"
+ end
+ end
+
+ def test_render_legacy_handler_with_custom_type
+ ActionView::Template.register_template_handler :foo, LegacyHandler
+ assert_equal 'source: Hello, <%= name %>!; locals: {:name=>"Josh"}', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
+ end
+
def test_render_with_layout
assert_equal %(<title></title>\nHello world!\n),
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield")
@@ -177,3 +196,26 @@ class ViewRenderTest < Test::Unit::TestCase
@view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield")
end
end
+
+class CachedViewRenderTest < Test::Unit::TestCase
+ include RenderTestCases
+
+ # Ensure view path cache is primed
+ def setup
+ view_paths = ActionController::Base.view_paths
+ assert view_paths.first.loaded?
+ setup_view(view_paths)
+ end
+end
+
+class LazyViewRenderTest < Test::Unit::TestCase
+ include RenderTestCases
+
+ # Test the same thing as above, but make sure the view path
+ # is not eager loaded
+ def setup
+ view_paths = ActionView::Base.process_view_paths(FIXTURE_LOAD_PATH)
+ assert !view_paths.first.loaded?
+ setup_view(view_paths)
+ end
+end
diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb
index fc49d340ef..ef88cae5b8 100644
--- a/actionpack/test/template/tag_helper_test.rb
+++ b/actionpack/test/template/tag_helper_test.rb
@@ -19,6 +19,10 @@ class TagHelperTest < ActionView::TestCase
assert_equal "<p />", tag("p", :ignored => nil)
end
+ def test_tag_options_accepts_false_option
+ assert_equal "<p value=\"false\" />", tag("p", :value => false)
+ end
+
def test_tag_options_accepts_blank_option
assert_equal "<p included=\"\" />", tag("p", :included => '')
end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index 5f9f715819..a6200fbdd7 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -205,55 +205,48 @@ class TextHelperTest < ActionView::TestCase
end
def test_auto_link_parsing
- urls = %w(http://www.rubyonrails.com
- http://www.rubyonrails.com:80
- http://www.rubyonrails.com/~minam
- https://www.rubyonrails.com/~minam
- http://www.rubyonrails.com/~minam/url%20with%20spaces
- http://www.rubyonrails.com/foo.cgi?something=here
- http://www.rubyonrails.com/foo.cgi?something=here&and=here
- http://www.rubyonrails.com/contact;new
- http://www.rubyonrails.com/contact;new%20with%20spaces
- http://www.rubyonrails.com/contact;new?with=query&string=params
- http://www.rubyonrails.com/~minam/contact;new?with=query&string=params
- http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007
- http://www.mail-archive.com/rails@lists.rubyonrails.org/
- http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1
- http://en.wikipedia.org/wiki/Sprite_(computer_graphics)
- http://en.wikipedia.org/wiki/Texas_hold'em
- )
+ urls = %w(
+ http://www.rubyonrails.com
+ http://www.rubyonrails.com:80
+ http://www.rubyonrails.com/~minam
+ https://www.rubyonrails.com/~minam
+ http://www.rubyonrails.com/~minam/url%20with%20spaces
+ http://www.rubyonrails.com/foo.cgi?something=here
+ http://www.rubyonrails.com/foo.cgi?something=here&and=here
+ http://www.rubyonrails.com/contact;new
+ http://www.rubyonrails.com/contact;new%20with%20spaces
+ http://www.rubyonrails.com/contact;new?with=query&string=params
+ http://www.rubyonrails.com/~minam/contact;new?with=query&string=params
+ http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007
+ http://www.mail-archive.com/rails@lists.rubyonrails.org/
+ http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1
+ http://en.wikipedia.org/wiki/Texas_hold'em
+ https://www.google.com/doku.php?id=gps:resource:scs:start
+ http://connect.oraclecorp.com/search?search[q]=green+france&search[type]=Group
+ http://of.openfoundry.org/projects/492/download#4th.Release.3
+ http://maps.google.co.uk/maps?f=q&q=the+london+eye&ie=UTF8&ll=51.503373,-0.11939&spn=0.007052,0.012767&z=16&iwloc=A
+ )
urls.each do |url|
- assert_equal %(<a href="#{url}">#{url}</a>), auto_link(url)
+ assert_equal generate_result(url), auto_link(url)
end
end
+ def generate_result(link_text, href = nil)
+ href ||= link_text
+ %{<a href="#{CGI::escapeHTML href}">#{CGI::escapeHTML link_text}</a>}
+ end
+
def test_auto_linking
email_raw = 'david@loudthinking.com'
email_result = %{<a href="mailto:#{email_raw}">#{email_raw}</a>}
- email2_raw = '+david@loudthinking.com'
- email2_result = %{<a href="mailto:#{email2_raw}">#{email2_raw}</a>}
link_raw = 'http://www.rubyonrails.com'
- link_result = %{<a href="#{link_raw}">#{link_raw}</a>}
- link_result_with_options = %{<a href="#{link_raw}" target="_blank">#{link_raw}</a>}
- link2_raw = 'www.rubyonrails.com'
- link2_result = %{<a href="http://#{link2_raw}">#{link2_raw}</a>}
- link3_raw = 'http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281'
- link3_result = %{<a href="#{link3_raw}">#{link3_raw}</a>}
- link4_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor123'
- link4_result = %{<a href="#{link4_raw}">#{link4_raw}</a>}
- link5_raw = 'http://foo.example.com:3000/controller/action'
- link5_result = %{<a href="#{link5_raw}">#{link5_raw}</a>}
- link6_raw = 'http://foo.example.com:3000/controller/action+pack'
- link6_result = %{<a href="#{link6_raw}">#{link6_raw}</a>}
- link7_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor-123'
- link7_result = %{<a href="#{link7_raw}">#{link7_raw}</a>}
- link8_raw = 'http://foo.example.com:3000/controller/action.html'
- link8_result = %{<a href="#{link8_raw}">#{link8_raw}</a>}
- link9_raw = 'http://business.timesonline.co.uk/article/0,,9065-2473189,00.html'
- link9_result = %{<a href="#{link9_raw}">#{link9_raw}</a>}
- link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/'
- link10_result = %{<a href="#{link10_raw}">#{link10_raw}</a>}
+ link_result = generate_result(link_raw)
+ link_result_with_options = %{<a href="#{link_raw}" target="_blank">#{link_raw}</a>}
+
+ assert_equal '', auto_link(nil)
+ assert_equal '', auto_link('')
+ assert_equal "#{link_result} #{link_result} #{link_result}", auto_link("#{link_raw} #{link_raw} #{link_raw}")
assert_equal %(hello #{email_result}), auto_link("hello #{email_raw}", :email_addresses)
assert_equal %(Go to #{link_result}), auto_link("Go to #{link_raw}", :urls)
@@ -264,41 +257,99 @@ class TextHelperTest < ActionView::TestCase
assert_equal %(<p>Link #{link_result_with_options}</p>), auto_link("<p>Link #{link_raw}</p>", :all, {:target => "_blank"})
assert_equal %(Go to #{link_result}.), auto_link(%(Go to #{link_raw}.))
assert_equal %(<p>Go to #{link_result}, then say hello to #{email_result}.</p>), auto_link(%(<p>Go to #{link_raw}, then say hello to #{email_raw}.</p>))
+
+ email2_raw = '+david@loudthinking.com'
+ email2_result = %{<a href="mailto:#{email2_raw}">#{email2_raw}</a>}
+ assert_equal email2_result, auto_link(email2_raw)
+
+ email3_raw = '+david@loudthinking.com'
+ email3_result = %{<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;+%64%61%76%69%64@%6c%6f%75%64%74%68%69%6e%6b%69%6e%67.%63%6f%6d">#{email3_raw}</a>}
+ assert_equal email3_result, auto_link(email3_raw, :all, :encode => :hex)
+ assert_equal email3_result, auto_link(email3_raw, :email_addresses, :encode => :hex)
+
+ link2_raw = 'www.rubyonrails.com'
+ link2_result = generate_result(link2_raw, "http://#{link2_raw}")
assert_equal %(Go to #{link2_result}), auto_link("Go to #{link2_raw}", :urls)
assert_equal %(Go to #{link2_raw}), auto_link("Go to #{link2_raw}", :email_addresses)
assert_equal %(<p>Link #{link2_result}</p>), auto_link("<p>Link #{link2_raw}</p>")
assert_equal %(<p>#{link2_result} Link</p>), auto_link("<p>#{link2_raw} Link</p>")
assert_equal %(Go to #{link2_result}.), auto_link(%(Go to #{link2_raw}.))
assert_equal %(<p>Say hello to #{email_result}, then go to #{link2_result}.</p>), auto_link(%(<p>Say hello to #{email_raw}, then go to #{link2_raw}.</p>))
+
+ link3_raw = 'http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281'
+ link3_result = generate_result(link3_raw)
assert_equal %(Go to #{link3_result}), auto_link("Go to #{link3_raw}", :urls)
assert_equal %(Go to #{link3_raw}), auto_link("Go to #{link3_raw}", :email_addresses)
assert_equal %(<p>Link #{link3_result}</p>), auto_link("<p>Link #{link3_raw}</p>")
assert_equal %(<p>#{link3_result} Link</p>), auto_link("<p>#{link3_raw} Link</p>")
assert_equal %(Go to #{link3_result}.), auto_link(%(Go to #{link3_raw}.))
- assert_equal %(<p>Go to #{link3_result}. seriously, #{link3_result}? i think I'll say hello to #{email_result}. instead.</p>), auto_link(%(<p>Go to #{link3_raw}. seriously, #{link3_raw}? i think I'll say hello to #{email_raw}. instead.</p>))
+ assert_equal %(<p>Go to #{link3_result}. Seriously, #{link3_result}? I think I'll say hello to #{email_result}. Instead.</p>),
+ auto_link(%(<p>Go to #{link3_raw}. Seriously, #{link3_raw}? I think I'll say hello to #{email_raw}. Instead.</p>))
+
+ link4_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor123'
+ link4_result = generate_result(link4_raw)
assert_equal %(<p>Link #{link4_result}</p>), auto_link("<p>Link #{link4_raw}</p>")
assert_equal %(<p>#{link4_result} Link</p>), auto_link("<p>#{link4_raw} Link</p>")
+
+ link5_raw = 'http://foo.example.com:3000/controller/action'
+ link5_result = generate_result(link5_raw)
assert_equal %(<p>#{link5_result} Link</p>), auto_link("<p>#{link5_raw} Link</p>")
+
+ link6_raw = 'http://foo.example.com:3000/controller/action+pack'
+ link6_result = generate_result(link6_raw)
assert_equal %(<p>#{link6_result} Link</p>), auto_link("<p>#{link6_raw} Link</p>")
+
+ link7_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor-123'
+ link7_result = generate_result(link7_raw)
assert_equal %(<p>#{link7_result} Link</p>), auto_link("<p>#{link7_raw} Link</p>")
+
+ link8_raw = 'http://foo.example.com:3000/controller/action.html'
+ link8_result = generate_result(link8_raw)
assert_equal %(Go to #{link8_result}), auto_link("Go to #{link8_raw}", :urls)
assert_equal %(Go to #{link8_raw}), auto_link("Go to #{link8_raw}", :email_addresses)
assert_equal %(<p>Link #{link8_result}</p>), auto_link("<p>Link #{link8_raw}</p>")
assert_equal %(<p>#{link8_result} Link</p>), auto_link("<p>#{link8_raw} Link</p>")
assert_equal %(Go to #{link8_result}.), auto_link(%(Go to #{link8_raw}.))
- assert_equal %(<p>Go to #{link8_result}. seriously, #{link8_result}? i think I'll say hello to #{email_result}. instead.</p>), auto_link(%(<p>Go to #{link8_raw}. seriously, #{link8_raw}? i think I'll say hello to #{email_raw}. instead.</p>))
+ assert_equal %(<p>Go to #{link8_result}. Seriously, #{link8_result}? I think I'll say hello to #{email_result}. Instead.</p>),
+ auto_link(%(<p>Go to #{link8_raw}. Seriously, #{link8_raw}? I think I'll say hello to #{email_raw}. Instead.</p>))
+
+ link9_raw = 'http://business.timesonline.co.uk/article/0,,9065-2473189,00.html'
+ link9_result = generate_result(link9_raw)
assert_equal %(Go to #{link9_result}), auto_link("Go to #{link9_raw}", :urls)
assert_equal %(Go to #{link9_raw}), auto_link("Go to #{link9_raw}", :email_addresses)
assert_equal %(<p>Link #{link9_result}</p>), auto_link("<p>Link #{link9_raw}</p>")
assert_equal %(<p>#{link9_result} Link</p>), auto_link("<p>#{link9_raw} Link</p>")
assert_equal %(Go to #{link9_result}.), auto_link(%(Go to #{link9_raw}.))
- assert_equal %(<p>Go to #{link9_result}. seriously, #{link9_result}? i think I'll say hello to #{email_result}. instead.</p>), auto_link(%(<p>Go to #{link9_raw}. seriously, #{link9_raw}? i think I'll say hello to #{email_raw}. instead.</p>))
+ assert_equal %(<p>Go to #{link9_result}. Seriously, #{link9_result}? I think I'll say hello to #{email_result}. Instead.</p>),
+ auto_link(%(<p>Go to #{link9_raw}. Seriously, #{link9_raw}? I think I'll say hello to #{email_raw}. Instead.</p>))
+
+ link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/'
+ link10_result = generate_result(link10_raw)
assert_equal %(<p>#{link10_result} Link</p>), auto_link("<p>#{link10_raw} Link</p>")
- assert_equal email2_result, auto_link(email2_raw)
- assert_equal '', auto_link(nil)
- assert_equal '', auto_link('')
- assert_equal "#{link_result} #{link_result} #{link_result}", auto_link("#{link_raw} #{link_raw} #{link_raw}")
- assert_equal '<a href="http://www.rubyonrails.com">Ruby On Rails</a>', auto_link('<a href="http://www.rubyonrails.com">Ruby On Rails</a>')
+ end
+
+ def test_auto_link_already_linked
+ linked1 = generate_result('Ruby On Rails', 'http://www.rubyonrails.com')
+ linked2 = generate_result('www.rubyonrails.com', 'http://www.rubyonrails.com')
+ assert_equal linked1, auto_link(linked1)
+ assert_equal linked2, auto_link(linked2)
+ end
+
+ def test_auto_link_with_brackets
+ link1_raw = 'http://en.wikipedia.org/wiki/Sprite_(computer_graphics)'
+ link1_result = generate_result(link1_raw)
+ assert_equal link1_result, auto_link(link1_raw)
+ assert_equal "(link: #{link1_result})", auto_link("(link: #{link1_raw})")
+
+ link2_raw = 'http://en.wikipedia.org/wiki/Sprite_[computer_graphics]'
+ link2_result = generate_result(link2_raw)
+ assert_equal link2_result, auto_link(link2_raw)
+ assert_equal "[link: #{link2_result}]", auto_link("[link: #{link2_raw}]")
+
+ link3_raw = 'http://en.wikipedia.org/wiki/Sprite_{computer_graphics}'
+ link3_result = generate_result(link3_raw)
+ assert_equal link3_result, auto_link(link3_raw)
+ assert_equal "{link: #{link3_result}}", auto_link("{link: #{link3_raw}}")
end
def test_auto_link_at_eol
@@ -316,7 +367,7 @@ class TextHelperTest < ActionView::TestCase
end
def test_auto_link_with_options_hash
- assert_equal 'Welcome to my new blog at <a href="http://www.myblog.com/" class="menu" target="_blank">http://www.myblog.com/</a>. Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.',
+ assert_dom_equal 'Welcome to my new blog at <a href="http://www.myblog.com/" class="menu" target="_blank">http://www.myblog.com/</a>. Please e-mail me at <a href="mailto:me@email.com" class="menu" target="_blank">me@email.com</a>.',
auto_link("Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com.",
:link => :all, :html => { :class => "menu", :target => "_blank" })
end
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index 1b28a59288..d0d65cb450 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -10,12 +10,12 @@ class TranslationHelperTest < Test::Unit::TestCase
end
def test_delegates_to_i18n_setting_the_raise_option
- I18n.expects(:translate).with(:foo, :locale => 'en-US', :raise => true)
- translate :foo, :locale => 'en-US'
+ I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true)
+ translate :foo, :locale => 'en'
end
def test_returns_missing_translation_message_wrapped_into_span
- expected = '<span class="translation_missing">en-US, foo</span>'
+ expected = '<span class="translation_missing">en, foo</span>'
assert_equal expected, translate(:foo)
end