diff options
author | Olli Jokinen <olli.jokinen@enemy.fi> | 2011-12-01 15:32:59 +0200 |
---|---|---|
committer | Olli Jokinen <olli.jokinen@enemy.fi> | 2011-12-01 15:32:59 +0200 |
commit | b4e1903d23a760028d58bc3bb20a1d491bfd4a4b (patch) | |
tree | a40bdce1bd4800124ab6eaed2a6be017bf9cfd3d /actionpack/test | |
parent | fae9ad9c712decef70b379f5aa1faa0149902831 (diff) | |
parent | 1e51cd957e3c90f4be35f1f0c4c380d8f7d40d66 (diff) | |
download | rails-b4e1903d23a760028d58bc3bb20a1d491bfd4a4b.tar.gz rails-b4e1903d23a760028d58bc3bb20a1d491bfd4a4b.tar.bz2 rails-b4e1903d23a760028d58bc3bb20a1d491bfd4a4b.zip |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'actionpack/test')
74 files changed, 1708 insertions, 429 deletions
diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb index 5823e64637..bf068aedcd 100644 --- a/actionpack/test/abstract/abstract_controller_test.rb +++ b/actionpack/test/abstract/abstract_controller_test.rb @@ -50,7 +50,7 @@ module AbstractController end def index_to_string - self.response_body = render_to_string "index.erb" + self.response_body = render_to_string "index" end def action_with_ivars @@ -63,11 +63,11 @@ module AbstractController end def rendering_to_body - self.response_body = render_to_body :template => "naked_render.erb" + self.response_body = render_to_body :template => "naked_render" end def rendering_to_string - self.response_body = render_to_string :template => "naked_render.erb" + self.response_body = render_to_string :template => "naked_render" end end diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 24d071df39..d191a203dd 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -73,7 +73,17 @@ module RackTestUtils end module RenderERBUtils + def view + @view ||= begin + path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH) + view_paths = ActionView::PathSet.new([path]) + ActionView::Base.new(view_paths) + end + end + def render_erb(string) + @virtual_path = nil + template = ActionView::Template.new( string.strip, "test template", @@ -333,11 +343,16 @@ module ActionDispatch "#{FIXTURE_LOAD_PATH}/public" end - remove_method :logger + remove_method :stderr_logger # Silence logger - def logger + def stderr_logger nil end end end +module RoutingTestHelpers + def url_for(set, options, recall = nil) + set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall)) + end +end diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb index 20d11377f6..90e7f4ae59 100644 --- a/actionpack/test/activerecord/polymorphic_routes_test.rb +++ b/actionpack/test/activerecord/polymorphic_routes_test.rb @@ -2,42 +2,40 @@ require 'active_record_unit' require 'fixtures/project' class Task < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end class Step < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end class Bid < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end class Tax < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end class Fax < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end class Series < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end module Blog class Post < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end class Blog < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' end - def self._railtie - o = Object.new - def o.railtie_name; "blog" end - o + def self.use_relative_model_naming? + true end end diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 878484eb57..5eef8a32d7 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -20,6 +20,15 @@ class AssertSelectTest < ActionController::TestCase end end + class AssertMultipartSelectMailer < ActionMailer::Base + def test(options) + mail :subject => "Test e-mail", :from => "test@test.host", :to => "test <test@test.host>" do |format| + format.text { render :text => options[:text] } + format.html { render :text => options[:html] } + end + end + end + class AssertSelectController < ActionController::Base def response_with=(content) @content = content @@ -313,6 +322,16 @@ EOF end end + def test_assert_select_email_multipart + AssertMultipartSelectMailer.test(:html => "<div><p>foo</p><p>bar</p></div>", :text => 'foo bar').deliver + assert_select_email do + assert_select "div:root" do + assert_select "p:first-child", "foo" + assert_select "p:last-child", "bar" + end + end + end + protected def render_html(html) @controller.response_with = html diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index da3314fe6d..2364bbf3a3 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -194,10 +194,11 @@ class ActionCachingTestController < CachingController caches_action :show, :cache_path => 'http://test.host/custom/show' caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" } caches_action :with_layout + caches_action :with_format_and_http_param, :cache_path => Proc.new { |c| { :key => 'value' } } caches_action :layout_false, :layout => false caches_action :record_not_found, :four_oh_four, :simple_runtime_error - layout 'talk_from_action.erb' + layout 'talk_from_action' def index @cache_this = MockTime.now.to_f.to_s @@ -219,6 +220,11 @@ class ActionCachingTestController < CachingController render :text => @cache_this, :layout => true end + def with_format_and_http_param + @cache_this = MockTime.now.to_f.to_s + render :text => @cache_this + end + def record_not_found raise ActiveRecord::RecordNotFound, "oops!" end @@ -359,6 +365,13 @@ class ActionCacheTest < ActionController::TestCase assert !fragment_exist?('hostname.com/action_caching_test') end + def test_action_cache_with_format_and_http_param + get :with_format_and_http_param, :format => 'json' + assert_response :success + assert !fragment_exist?('hostname.com/action_caching_test/with_format_and_http_param.json?key=value.json') + assert fragment_exist?('hostname.com/action_caching_test/with_format_and_http_param.json?key=value') + 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 @@ -745,6 +758,7 @@ class FunctionalFragmentCachingTest < ActionController::TestCase expected_body = <<-CACHED Hello This bit's fragment cached +Ciao CACHED assert_equal expected_body, @response.body @@ -786,3 +800,51 @@ CACHED assert_equal " <p>Builder</p>\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached') end end + +class CacheHelperOutputBufferTest < ActionController::TestCase + + class MockController + def read_fragment(name, options) + return false + end + + def write_fragment(name, fragment, options) + fragment + end + end + + def setup + super + end + + def test_output_buffer + output_buffer = ActionView::OutputBuffer.new + controller = MockController.new + cache_helper = Object.new + cache_helper.extend(ActionView::Helpers::CacheHelper) + cache_helper.expects(:controller).returns(controller).at_least(0) + cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0) + # if the output_buffer is changed, the new one should be html_safe and of the same type + cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0) + + assert_nothing_raised do + cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil } + end + end + + def test_safe_buffer + output_buffer = ActiveSupport::SafeBuffer.new + controller = MockController.new + cache_helper = Object.new + cache_helper.extend(ActionView::Helpers::CacheHelper) + cache_helper.expects(:controller).returns(controller).at_least(0) + cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0) + # if the output_buffer is changed, the new one should be html_safe and of the same type + cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0) + + assert_nothing_raised do + cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil } + end + end + +end diff --git a/actionpack/test/controller/default_url_options_with_filter_test.rb b/actionpack/test/controller/default_url_options_with_filter_test.rb new file mode 100644 index 0000000000..3bbb981040 --- /dev/null +++ b/actionpack/test/controller/default_url_options_with_filter_test.rb @@ -0,0 +1,29 @@ +require 'abstract_unit' + + +class ControllerWithBeforeFilterAndDefaultUrlOptions < ActionController::Base + + before_filter { I18n.locale = params[:locale] } + after_filter { I18n.locale = "en" } + + def target + render :text => "final response" + end + + def redirect + redirect_to :action => "target" + end + + def default_url_options + {:locale => "de"} + end +end + +class ControllerWithBeforeFilterAndDefaultUrlOptionsTest < ActionController::TestCase + + # This test has it´s roots in issue #1872 + test "should redirect with correct locale :de" do + get :redirect, :locale => "de" + assert_redirected_to "/controller_with_before_filter_and_default_url_options/target?locale=de" + end +end diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb index 3e723e20d9..43b20fdead 100644 --- a/actionpack/test/controller/force_ssl_test.rb +++ b/actionpack/test/controller/force_ssl_test.rb @@ -14,6 +14,10 @@ class ForceSSLControllerLevel < ForceSSLController force_ssl end +class ForceSSLCustomDomain < ForceSSLController + force_ssl :host => "secure.test.host" +end + class ForceSSLOnlyAction < ForceSSLController force_ssl :only => :cheeseburger end @@ -38,6 +42,22 @@ class ForceSSLControllerLevelTest < ActionController::TestCase end end +class ForceSSLCustomDomainTest < ActionController::TestCase + tests ForceSSLCustomDomain + + def test_banana_redirects_to_https_with_custom_host + get :banana + assert_response 301 + assert_equal "https://secure.test.host/force_ssl_custom_domain/banana", redirect_to_url + end + + def test_cheeseburger_redirects_to_https_with_custom_host + get :cheeseburger + assert_response 301 + assert_equal "https://secure.test.host/force_ssl_custom_domain/cheeseburger", redirect_to_url + end +end + class ForceSSLOnlyActionTest < ActionController::TestCase tests ForceSSLOnlyAction @@ -80,4 +100,4 @@ class ForceSSLExcludeDevelopmentTest < ActionController::TestCase get :banana assert_response 200 end -end
\ No newline at end of file +end diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 584d73668a..35a87c1aae 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'active_support/core_ext/kernel/reporting' ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__) diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb index bd3e13e6fa..364e96d4f6 100644 --- a/actionpack/test/controller/http_basic_authentication_test.rb +++ b/actionpack/test/controller/http_basic_authentication_test.rb @@ -85,6 +85,14 @@ class HttpBasicAuthenticationTest < ActionController::TestCase end end + def test_encode_credentials_has_no_newline + username = 'laskjdfhalksdjfhalkjdsfhalksdjfhklsdjhalksdjfhalksdjfhlakdsjfh' + password = 'kjfhueyt9485osdfasdkljfh4lkjhakldjfhalkdsjf' + result = ActionController::HttpAuthentication::Basic.encode_credentials( + username, password) + assert_no_match(/\n/, result) + end + test "authentication request without credential" do get :display diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 23709e44e2..2ad95f5c29 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -493,7 +493,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest routes.draw do match '', :to => 'application_integration_test/test#index', :as => :empty_string - + match 'foo', :to => 'application_integration_test/test#index', :as => :foo match 'bar', :to => 'application_integration_test/test#index', :as => :bar end @@ -511,7 +511,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest test "route helpers after controller access" do get '/' assert_equal '/', empty_string_path - + get '/foo' assert_equal '/foo', foo_path @@ -528,11 +528,10 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest assert_raise(NameError) { missing_path } end - test "process reuse the env we pass as argument" do + test "process do not modify the env passed as argument" do env = { :SERVER_NAME => 'server', 'action_dispatch.custom' => 'custom' } + old_env = env.dup get '/foo', nil, env - assert_equal :get, env[:method] - assert_equal 'server', env[:SERVER_NAME] - assert_equal 'custom', env['action_dispatch.custom'] + assert_equal old_env, env end end diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index cafe2b9320..25299eb8b8 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -79,7 +79,7 @@ class DefaultLayoutController < LayoutTest end class AbsolutePathLayoutController < LayoutTest - layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.erb') + layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test') end class HasOwnLayoutController < LayoutTest @@ -184,7 +184,7 @@ class RenderWithTemplateOptionController < LayoutTest end class SetsNonExistentLayoutFile < LayoutTest - layout "nofile.erb" + layout "nofile" end class LayoutExceptionRaised < ActionController::TestCase diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index ccdfcb0b2c..700fd788fa 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -13,6 +13,11 @@ module Another head :status => 406 end + before_filter :redirector, :only => :never_executed + + def never_executed + end + def show render :nothing => true end @@ -49,7 +54,6 @@ module Another def with_rescued_exception raise SpecialException end - end end @@ -86,6 +90,13 @@ class ACLogSubscriberTest < ActionController::TestCase assert_equal "Processing by Another::LogSubscribersController#show as HTML", logs.first end + def test_halted_callback + get :never_executed + wait + assert_equal 4, logs.size + assert_equal "Filter chain halted as :redirector rendered or redirected", logs.third + end + def test_process_action get :show wait diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index afb2d39955..76a8c89e60 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -509,7 +509,7 @@ end class RespondWithController < ActionController::Base respond_to :html, :json respond_to :xml, :except => :using_resource_with_block - respond_to :js, :only => [ :using_resource_with_block, :using_resource, :using_hash_resource ] + respond_to :js, :only => [ :using_resource_with_block, :using_resource, 'using_hash_resource' ] def using_resource respond_with(resource) @@ -656,7 +656,9 @@ class RespondWithControllerTest < ActionController::TestCase @request.accept = "application/json" get :using_hash_resource assert_equal "application/json", @response.content_type - assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body + assert @response.body.include?("result") + assert @response.body.include?('"name":"david"') + assert @response.body.include?('"id":13') end def test_using_hash_resource_with_post @@ -745,6 +747,20 @@ class RespondWithControllerTest < ActionController::TestCase end end + def test_using_resource_for_post_with_json_yields_unprocessable_entity_on_failure + with_test_route_set do + @request.accept = "application/json" + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + post :using_resource + assert_equal "application/json", @response.content_type + assert_equal 422, @response.status + errors = {:errors => errors} + assert_equal errors.to_json, @response.body + assert_nil @response.location + end + end + def test_using_resource_for_put_with_html_redirects_on_success with_test_route_set do put :using_resource @@ -780,21 +796,21 @@ class RespondWithControllerTest < ActionController::TestCase end end - def test_using_resource_for_put_with_xml_yields_ok_on_success + def test_using_resource_for_put_with_xml_yields_no_content_on_success @request.accept = "application/xml" put :using_resource assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status + assert_equal 204, @response.status assert_equal " ", @response.body end - def test_using_resource_for_put_with_json_yields_ok_on_success + def test_using_resource_for_put_with_json_yields_no_content_on_success Customer.any_instance.stubs(:to_json).returns('{"name": "David"}') @request.accept = "application/json" put :using_resource assert_equal "application/json", @response.content_type - assert_equal 200, @response.status - assert_equal "{}", @response.body + assert_equal 204, @response.status + assert_equal " ", @response.body end def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure @@ -808,6 +824,18 @@ class RespondWithControllerTest < ActionController::TestCase assert_nil @response.location end + def test_using_resource_for_put_with_json_yields_unprocessable_entity_on_failure + @request.accept = "application/json" + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + put :using_resource + assert_equal "application/json", @response.content_type + assert_equal 422, @response.status + errors = {:errors => errors} + assert_equal errors.to_json, @response.body + assert_nil @response.location + end + def test_using_resource_for_delete_with_html_redirects_on_success with_test_route_set do Customer.any_instance.stubs(:destroyed?).returns(true) @@ -818,23 +846,23 @@ class RespondWithControllerTest < ActionController::TestCase end end - def test_using_resource_for_delete_with_xml_yields_ok_on_success + def test_using_resource_for_delete_with_xml_yields_no_content_on_success Customer.any_instance.stubs(:destroyed?).returns(true) @request.accept = "application/xml" delete :using_resource assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status + assert_equal 204, @response.status assert_equal " ", @response.body end - def test_using_resource_for_delete_with_json_yields_ok_on_success + def test_using_resource_for_delete_with_json_yields_no_content_on_success Customer.any_instance.stubs(:to_json).returns('{"name": "David"}') Customer.any_instance.stubs(:destroyed?).returns(true) @request.accept = "application/json" delete :using_resource assert_equal "application/json", @response.content_type - assert_equal 200, @response.status - assert_equal "{}", @response.body + assert_equal 204, @response.status + assert_equal " ", @response.body end def test_using_resource_for_delete_with_html_redirects_on_failure diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb index 3ca29f1bcf..c424dcbd8d 100644 --- a/actionpack/test/controller/new_base/bare_metal_test.rb +++ b/actionpack/test/controller/new_base/bare_metal_test.rb @@ -23,6 +23,12 @@ module BareMetalTest assert_equal "Hello world", string end + + test "response_body value is wrapped in an array when the value is a String" do + controller = BareController.new + controller.index + assert_equal ["Hello world"], controller.response_body + end end class HeadController < ActionController::Metal diff --git a/actionpack/test/controller/new_base/render_file_test.rb b/actionpack/test/controller/new_base/render_file_test.rb index 8b2fdf8f96..a961cbf849 100644 --- a/actionpack/test/controller/new_base/render_file_test.rb +++ b/actionpack/test/controller/new_base/render_file_test.rb @@ -10,7 +10,7 @@ module RenderFile def with_instance_variables @secret = 'in the sauce' - render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb') + render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar') end def without_file_key @@ -19,7 +19,7 @@ module RenderFile def without_file_key_with_instance_variable @secret = 'in the sauce' - render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb') + render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar') end def relative_path @@ -34,16 +34,16 @@ module RenderFile def pathname @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar.erb]) + render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar]) end def with_locals - path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals.erb') + path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals') render :file => path, :locals => {:secret => 'in the sauce'} end def without_file_key_with_locals - path = FIXTURES.join('test/render_file_with_locals.erb').to_s + path = FIXTURES.join('test/render_file_with_locals').to_s render path, :locals => {:secret => 'in the sauce'} end end diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb index 83b0d039ad..b4a25c49c9 100644 --- a/actionpack/test/controller/new_base/render_partial_test.rb +++ b/actionpack/test/controller/new_base/render_partial_test.rb @@ -7,12 +7,12 @@ module RenderPartial self.view_paths = [ActionView::FixtureResolver.new( "render_partial/basic/_basic.html.erb" => "BasicPartial!", "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>", - "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>", - "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>", + "render_partial/basic/with_json.html.erb" => "<%= render :partial => 'with_json', :formats => [:json] %>", + "render_partial/basic/_with_json.json.erb" => "<%= render :partial => 'final', :formats => [:json] %>", "render_partial/basic/_final.json.erb" => "{ final: json }", - "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", - "render_partial/basic/_overriden.html.erb" => "ParentPartial!", - "render_partial/child/_overriden.html.erb" => "OverridenPartial!" + "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", + "render_partial/basic/_overriden.html.erb" => "ParentPartial!", + "render_partial/child/_overriden.html.erb" => "OverridenPartial!" )] def html_with_json_inside_json diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb index 584f2d772c..ba804421da 100644 --- a/actionpack/test/controller/new_base/render_template_test.rb +++ b/actionpack/test/controller/new_base/render_template_test.rb @@ -10,8 +10,8 @@ module RenderTemplate "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend", "with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>", "with_implicit_raw.html.erb" => "Hello <%== '<strong>this is also raw</strong>' %>", - "test/with_json.html.erb" => "<%= render :template => 'test/with_json.json' %>", - "test/with_json.json.erb" => "<%= render :template => 'test/final' %>", + "test/with_json.html.erb" => "<%= render :template => 'test/with_json', :formats => [:json] %>", + "test/with_json.json.erb" => "<%= render :template => 'test/final', :formats => [:json] %>", "test/final.json.erb" => "{ final: json }", "test/with_error.html.erb" => "<%= idontexist %>" )] @@ -117,7 +117,7 @@ module RenderTemplate assert_response "{ final: json }" end - test "rendering a template with error properly exceprts the code" do + test "rendering a template with error properly excerts the code" do get :with_error assert_status 500 assert_match "undefined local variable or method `idontexist'", response.body diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 92d4a6d98b..79041055bd 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -4,6 +4,11 @@ class WorkshopsController < ActionController::Base end class RedirectController < ActionController::Base + # empty method not used anywhere to ensure methods like + # `status` and `location` aren't called on `redirect_to` calls + def status; render :text => 'called status'; end + def location; render :text => 'called location'; end + def simple_redirect redirect_to :action => "hello_world" end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index ce4b407c7d..aea603b014 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -163,14 +163,14 @@ class TestController < ActionController::Base # :ported: def render_file_with_instance_variables @secret = 'in the sauce' - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') + path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar') render :file => path end # :ported: def render_file_as_string_with_instance_variables @secret = 'in the sauce' - path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) + path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar')) render path end @@ -187,21 +187,21 @@ class TestController < ActionController::Base def render_file_using_pathname @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar.erb') + render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar') end def render_file_from_template @secret = 'in the sauce' - @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) + @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar')) end def render_file_with_locals - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') + path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals') render :file => path, :locals => {:secret => 'in the sauce'} end def render_file_as_string_with_locals - path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')) + path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals')) render path, :locals => {:secret => 'in the sauce'} end @@ -405,6 +405,14 @@ class TestController < ActionController::Base render :template => "test/hello_world" end + def render_with_explicit_unescaped_template + render :template => "test/h*llo_world" + end + + def render_with_explicit_escaped_template + render :template => "test/hello,world" + end + def render_with_explicit_string_template render "test/hello_world" end @@ -445,17 +453,13 @@ class TestController < ActionController::Base render :action => "potential_conflicts" end - # :deprecated: - # Tests being able to pick a .builder template over a .erb - # For instance, being able to have hello.xml.builder and hello.xml.erb - # and select one via "hello.builder" or "hello.erb" def hello_world_from_rxml_using_action - render :action => "hello_world_from_rxml.builder" + render :action => "hello_world_from_rxml", :handlers => [:builder] end # :deprecated: def hello_world_from_rxml_using_template - render :template => "test/hello_world_from_rxml.builder" + render :template => "test/hello_world_from_rxml", :handlers => [:builder] end def action_talk_to_layout @@ -517,8 +521,8 @@ class TestController < ActionController::Base render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" end - def partial_dot_html - render :partial => 'partial.html.erb' + def partial_formats_html + render :partial => 'partial', :formats => [:html] end def partial @@ -789,7 +793,9 @@ class RenderTest < ActionController::TestCase end def test_render_file - get :hello_world_file + assert_deprecated do + get :hello_world_file + end assert_equal "Hello world!", @response.body end @@ -1057,6 +1063,12 @@ class RenderTest < ActionController::TestCase assert_response :success end + def test_render_with_explicit_unescaped_template + assert_raise(ActionView::MissingTemplate) { get :render_with_explicit_unescaped_template } + get :render_with_explicit_escaped_template + assert_equal "Hello w*rld!", @response.body + end + def test_render_with_explicit_string_template get :render_with_explicit_string_template assert_equal "<html>Hello world!</html>", @response.body @@ -1219,8 +1231,8 @@ class RenderTest < ActionController::TestCase assert_equal 'partial html', @response.body end - def test_should_render_html_partial_with_dot - get :partial_dot_html + def test_should_render_html_partial_with_formats + get :partial_formats_html assert_equal 'partial html', @response.body end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index d94db7f5fb..fd5a41a0bb 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' require 'digest/sha1' require 'active_support/core_ext/string/strip' +require "active_support/log_subscriber/test_helper" # common controller actions module RequestForgeryProtectionActions @@ -157,6 +158,21 @@ module RequestForgeryProtectionTests assert_not_blocked { put :index } end + def test_should_warn_on_missing_csrf_token + old_logger = ActionController::Base.logger + logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new + ActionController::Base.logger = logger + + begin + assert_blocked { post :index } + + assert_equal 1, logger.logged(:warn).size + assert_match(/CSRF token authenticity/, logger.logged(:warn).last) + ensure + ActionController::Base.logger = old_logger + end + end + def assert_blocked session[:something_like_user_id] = 1 yield diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 6ea492cf8b..6b8a8f6161 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -91,6 +91,15 @@ class ResourcesTest < ActionController::TestCase end end + def test_multiple_resources_with_options + expected_options = {:controller => 'threads', :action => 'index'} + + with_restful_routing :messages, :comments, expected_options.slice(:controller) do + assert_recognizes(expected_options, :path => 'comments') + assert_recognizes(expected_options, :path => 'messages') + end + end + def test_with_custom_conditions with_restful_routing :messages, :conditions => { :subdomain => 'app' } do assert @routes.recognize_path("/messages", :method => :get, :subdomain => 'app') @@ -523,7 +532,7 @@ class ResourcesTest < ActionController::TestCase routes.each do |route| routes.each do |r| next if route === r # skip the comparison instance - assert distinct_routes?(route, r), "Duplicate Route: #{route}" + assert_not_equal [route.conditions, route.path.spec.to_s], [r.conditions, r.path.spec.to_s] end end end @@ -1342,13 +1351,4 @@ class ResourcesTest < ActionController::TestCase assert_recognizes(expected_options, path) end end - - def distinct_routes? (r1, r2) - if r1.conditions == r2.conditions and r1.constraints == r2.constraints then - if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then - return false - end - end - true - end end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index aa9d193436..4a67380f59 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1,7 +1,6 @@ # encoding: utf-8 require 'abstract_unit' require 'controller/fake_controllers' -require 'active_support/dependencies' require 'active_support/core_ext/object/with_options' class MilestonesController < ActionController::Base @@ -12,12 +11,6 @@ end ROUTING = ActionDispatch::Routing -module RoutingTestHelpers - def url_for(set, options, recall = nil) - set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall)) - end -end - # See RFC 3986, section 3.3 for allowed path characters. class UriReservedCharactersRoutingTest < Test::Unit::TestCase include RoutingTestHelpers @@ -1665,114 +1658,6 @@ class RackMountIntegrationTests < ActiveSupport::TestCase assert_raise(ActionController::RoutingError) { @routes.recognize_path('/none', :method => :get) } end - def test_generate - assert_equal '/admin/users', url_for(@routes, { :use_route => 'admin_users' }) - assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users' }) - assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users', :action => 'index' }) - assert_equal '/admin/users', url_for(@routes, { :action => 'index' }, { :controller => 'admin/users' }) - assert_equal '/admin/users', url_for(@routes, { :controller => 'users', :action => 'index' }, { :controller => 'admin/accounts' }) - assert_equal '/people', url_for(@routes, { :controller => '/people', :action => 'index' }, { :controller => 'admin/accounts' }) - - assert_equal '/admin/posts', url_for(@routes, { :controller => 'admin/posts' }) - assert_equal '/admin/posts/new', url_for(@routes, { :controller => 'admin/posts', :action => 'new' }) - - assert_equal '/blog/2009', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009 }) - assert_equal '/blog/2009/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1 }) - assert_equal '/blog/2009/1/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1 }) - - assert_equal '/archive/2010', url_for(@routes, { :controller => 'archive', :action => 'index', :year => '2010' }) - assert_equal '/archive', url_for(@routes, { :controller => 'archive', :action => 'index' }) - assert_equal '/archive?year=january', url_for(@routes, { :controller => 'archive', :action => 'index', :year => 'january' }) - - assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }) - assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people' }) - assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people', url_for(@routes, {}, { :controller => 'people', :action => 'index' }) - assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people/new', url_for(@routes, { :use_route => 'new_person' }) - assert_equal '/people/new', url_for(@routes, { :controller => 'people', :action => 'new' }) - assert_equal '/people/1', url_for(@routes, { :use_route => 'person', :id => '1' }) - assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people/1.xml', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :format => 'xml' }) - assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => 1 }) - assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => Model.new('1') }) - assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => '1' }, { :controller => 'people', :action => 'index' }) - assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => 1 }, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people/1', url_for(@routes, {}, { :controller => 'people', :action => 'show', :id => '1' }) - assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'index', :id => '1' }) - assert_equal '/people/1/edit', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1' }) - assert_equal '/people/1/edit.xml', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1', :format => 'xml' }) - assert_equal '/people/1/edit', url_for(@routes, { :use_route => 'edit_person', :id => '1' }) - assert_equal '/people/1?legacy=true', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :legacy => 'true' }) - assert_equal '/people?legacy=true', url_for(@routes, { :controller => 'people', :action => 'index', :legacy => 'true' }) - - assert_equal '/id_default/2', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '2' }) - assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '1' }) - assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => 1 }) - assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default' }) - assert_equal '/optional/bar', url_for(@routes, { :controller => 'posts', :action => 'index', :optional => 'bar' }) - assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' }) - - assert_equal '/project', url_for(@routes, { :controller => 'project', :action => 'index' }) - assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index', :project_id => '1' }) - assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index'}, {:project_id => '1' }) - assert_raise(ActionController::RoutingError) { url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }) } - assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1' }) - assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }, { :project_id => '1' }) - - assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' }) - assert_equal '/clients?project_id=1', url_for(@routes, { :controller => 'projects', :action => 'index', :project_id => '1' }) - assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' }, { :project_id => '1' }) - assert_equal '/clients', url_for(@routes, { :action => 'index' }, { :controller => 'projects', :action => 'index', :project_id => '1' }) - - assert_equal '/comment/20', url_for(@routes, { :id => 20 }, { :controller => 'comments', :action => 'show' }) - assert_equal '/comment/20', url_for(@routes, { :controller => 'comments', :id => 20, :action => 'show' }) - assert_equal '/comments/boo', url_for(@routes, { :controller => 'comments', :action => 'boo' }) - - assert_equal '/ws/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1', :ws => true }) - assert_equal '/ws/posts', url_for(@routes, { :controller => 'posts', :action => 'index', :ws => true }) - - assert_equal '/account', url_for(@routes, { :controller => 'account', :action => 'subscription' }) - assert_equal '/account/billing', url_for(@routes, { :controller => 'account', :action => 'billing' }) - - assert_equal '/pages/1/notes/show/1', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'show', :id => '1' }) - assert_equal '/pages/1/notes/list', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'list' }) - assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'index' }) - assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes' }) - assert_equal '/notes', url_for(@routes, { :page_id => nil, :controller => 'notes' }) - assert_equal '/notes', url_for(@routes, { :controller => 'notes' }) - assert_equal '/notes/print', url_for(@routes, { :controller => 'notes', :action => 'print' }) - assert_equal '/notes/print', url_for(@routes, {}, { :controller => 'notes', :action => 'print' }) - - assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' }) - assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1', :foo => 'bar' }) - assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' }) - assert_equal '/notes/index/1', url_for(@routes, { :action => 'index' }, { :controller => 'notes', :id => '1' }) - assert_equal '/notes/index/1', url_for(@routes, {}, { :controller => 'notes', :id => '1' }) - assert_equal '/notes/show/1', url_for(@routes, {}, { :controller => 'notes', :action => 'show', :id => '1' }) - assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes', :id => '1' }, { :foo => 'bar' }) - assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'notes', :action => 'show', :id => '1' }) - assert_equal '/notes/list', url_for(@routes, { :action => 'list' }, { :controller => 'notes', :action => 'show', :id => '1' }) - - assert_equal '/posts/ping', url_for(@routes, { :controller => 'posts', :action => 'ping' }) - assert_equal '/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1' }) - assert_equal '/posts', url_for(@routes, { :controller => 'posts' }) - assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' }) - assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'posts', :action => 'index' }) - assert_equal '/posts/create', url_for(@routes, { :action => 'create' }, { :controller => 'posts' }) - assert_equal '/posts?foo=bar', url_for(@routes, { :controller => 'posts', :foo => 'bar' }) - assert_equal '/posts?foo%5B%5D=bar&foo%5B%5D=baz', url_for(@routes, { :controller => 'posts', :foo => ['bar', 'baz'] }) - assert_equal '/posts?page=2', url_for(@routes, { :controller => 'posts', :page => 2 }) - assert_equal '/posts?q%5Bfoo%5D%5Ba%5D=b', url_for(@routes, { :controller => 'posts', :q => { :foo => { :a => 'b'}} }) - - assert_equal '/news.rss', url_for(@routes, { :controller => 'news', :action => 'index', :format => 'rss' }) - - - assert_raise(ActionController::RoutingError) { url_for(@routes, { :action => 'index' }) } - end - def test_generate_extras assert_equal ['/people', []], @routes.generate_extras(:controller => 'people') assert_equal ['/people', [:foo]], @routes.generate_extras(:controller => 'people', :foo => 'bar') diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb new file mode 100644 index 0000000000..74067cb895 --- /dev/null +++ b/actionpack/test/controller/show_exceptions_test.rb @@ -0,0 +1,59 @@ +require 'abstract_unit' + +module ShowExceptions + class ShowExceptionsController < ActionController::Base + use ActionDispatch::ShowExceptions + + def boom + raise 'boom!' + end + end + + class ShowExceptionsTest < ActionDispatch::IntegrationTest + test 'show error page from a remote ip' do + @app = ShowExceptionsController.action(:boom) + self.remote_addr = '208.77.188.166' + get '/' + assert_equal "500 error fixture\n", body + end + + test 'show diagnostics from a local ip' do + @app = ShowExceptionsController.action(:boom) + ['127.0.0.1', '127.0.0.127', '::1', '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1%0'].each do |ip_address| + self.remote_addr = ip_address + get '/' + assert_match(/boom/, body) + end + end + + test 'show diagnostics from a remote ip when consider_all_requests_local is true' do + ShowExceptionsController.any_instance.stubs(:consider_all_requests_local).returns(true) + @app = ShowExceptionsController.action(:boom) + self.remote_addr = '208.77.188.166' + get '/' + assert_match(/boom/, body) + end + end + + class ShowExceptionsOverridenController < ShowExceptionsController + private + + def show_detailed_exceptions? + params['detailed'] == '1' + end + end + + class ShowExceptionsOverridenTest < ActionDispatch::IntegrationTest + test 'show error page' do + @app = ShowExceptionsOverridenController.action(:boom) + get '/', {'detailed' => '0'} + assert_equal "500 error fixture\n", body + end + + test 'show diagnostics message' do + @app = ShowExceptionsOverridenController.action(:boom) + get '/', {'detailed' => '1'} + assert_match(/boom/, body) + end + end +end diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 043d44500a..b64e275363 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -50,6 +50,10 @@ class TestTest < ActionController::TestCase render :text => request.query_string end + def test_protocol + render :text => request.protocol + end + def test_html_output render :text => <<HTML <html> @@ -142,6 +146,17 @@ XML end end + class ViewAssignsController < ActionController::Base + def test_assigns + @foo = "foo" + render :nothing => true + end + + def view_assigns + { "bar" => "bar" } + end + end + def test_raw_post_handling params = ActiveSupport::OrderedHash[:page, {:name => 'page name'}, 'some key', 123] post :render_raw_post, params.dup @@ -252,6 +267,15 @@ XML assert_equal "foo", assigns["foo"] end + def test_view_assigns + @controller = ViewAssignsController.new + process :test_assigns + assert_equal nil, assigns(:foo) + assert_equal nil, assigns[:foo] + assert_equal "bar", assigns(:bar) + assert_equal "bar", assigns[:bar] + end + def test_assert_tag_tag process :test_html_output @@ -515,6 +539,12 @@ XML ) end + def test_params_passing_doesnt_modify_in_place + page = {:name => "Page name", :month => 4, :year => 2004, :day => 6} + get :test_params, :page => page + assert_equal 2004, page[:year] + end + def test_id_converted_to_string get :test_params, :id => 20, :foo => Object.new assert_kind_of String, @request.path_parameters['id'] @@ -592,6 +622,19 @@ XML assert_nil @request.symbolized_path_parameters[:id] end + def test_request_protocol_is_reset_after_request + get :test_protocol + assert_equal "http://", @response.body + + @request.env["HTTPS"] = "on" + get :test_protocol + assert_equal "https://", @response.body + + @request.env.delete("HTTPS") + get :test_protocol + assert_equal "http://", @response.body + end + def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set cookies['foo'] = 'bar' get :no_op @@ -731,6 +774,22 @@ class CrazyNameTest < ActionController::TestCase end end +class CrazySymbolNameTest < ActionController::TestCase + tests :content + + def test_set_controller_class_using_symbol + assert_equal ContentController, self.class.controller_class + end +end + +class CrazyStringNameTest < ActionController::TestCase + tests 'content' + + def test_set_controller_class_using_string + assert_equal ContentController, self.class.controller_class + end +end + class NamedRoutesControllerTest < ActionController::TestCase tests ContentController diff --git a/actionpack/test/controller/url_for_integration_test.rb b/actionpack/test/controller/url_for_integration_test.rb new file mode 100644 index 0000000000..451ea6027d --- /dev/null +++ b/actionpack/test/controller/url_for_integration_test.rb @@ -0,0 +1,177 @@ +# encoding: utf-8 +require 'abstract_unit' +require 'controller/fake_controllers' +require 'active_support/core_ext/object/with_options' + +module ActionPack + class URLForIntegrationTest < ActiveSupport::TestCase + include RoutingTestHelpers + + Model = Struct.new(:to_param) + + Mapping = lambda { + namespace :admin do + resources :users, :posts + end + + namespace 'api' do + root :to => 'users#index' + end + + match '/blog(/:year(/:month(/:day)))' => 'posts#show_date', + :constraints => { + :year => /(19|20)\d\d/, + :month => /[01]?\d/, + :day => /[0-3]?\d/ + }, + :day => nil, + :month => nil + + match 'archive/:year', :controller => 'archive', :action => 'index', + :defaults => { :year => nil }, + :constraints => { :year => /\d{4}/ }, + :as => "blog" + + resources :people + #match 'legacy/people' => "people#index", :legacy => "true" + + match 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol + match 'id_default(/:id)' => "foo#id_default", :id => 1 + match 'get_or_post' => "foo#get_or_post", :via => [:get, :post] + match 'optional/:optional' => "posts#index" + match 'projects/:project_id' => "project#index", :as => "project" + match 'clients' => "projects#index" + + match 'ignorecase/geocode/:postalcode' => 'geocode#show', :postalcode => /hx\d\d-\d[a-z]{2}/i + match 'extended/geocode/:postalcode' => 'geocode#show',:constraints => { + :postalcode => /# Postcode format + \d{5} #Prefix + (-\d{4})? #Suffix + /x + }, :as => "geocode" + + match 'news(.:format)' => "news#index" + + match 'comment/:id(/:action)' => "comments#show" + match 'ws/:controller(/:action(/:id))', :ws => true + match 'account(/:action)' => "account#subscription" + match 'pages/:page_id/:controller(/:action(/:id))' + match ':controller/ping', :action => 'ping' + match ':controller(/:action(/:id))(.:format)' + root :to => "news#index" + } + + def setup + @routes = ActionDispatch::Routing::RouteSet.new + @routes.draw(&Mapping) + end + + [ + ['/admin/users',[ { :use_route => 'admin_users' }]], + ['/admin/users',[ { :controller => 'admin/users' }]], + ['/admin/users',[ { :controller => 'admin/users', :action => 'index' }]], + ['/admin/users',[ { :action => 'index' }, { :controller => 'admin/users' }]], + ['/admin/users',[ { :controller => 'users', :action => 'index' }, { :controller => 'admin/accounts' }]], + ['/people',[ { :controller => '/people', :action => 'index' }, { :controller => 'admin/accounts' }]], + + ['/admin/posts',[ { :controller => 'admin/posts' }]], + ['/admin/posts/new',[ { :controller => 'admin/posts', :action => 'new' }]], + + ['/blog/2009',[ { :controller => 'posts', :action => 'show_date', :year => 2009 }]], + ['/blog/2009/1',[ { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1 }]], + ['/blog/2009/1/1',[ { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1 }]], + + ['/archive/2010',[ { :controller => 'archive', :action => 'index', :year => '2010' }]], + ['/archive',[ { :controller => 'archive', :action => 'index' }]], + ['/archive?year=january',[ { :controller => 'archive', :action => 'index', :year => 'january' }]], + + ['/people',[ { :controller => 'people', :action => 'index' }]], + ['/people',[ { :action => 'index' }, { :controller => 'people' }]], + ['/people',[ { :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people',[ { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people',[ {}, { :controller => 'people', :action => 'index' }]], + ['/people/1',[ { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people/new',[ { :use_route => 'new_person' }]], + ['/people/new',[ { :controller => 'people', :action => 'new' }]], + ['/people/1',[ { :use_route => 'person', :id => '1' }]], + ['/people/1',[ { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people/1.xml',[ { :controller => 'people', :action => 'show', :id => '1', :format => 'xml' }]], + ['/people/1',[ { :controller => 'people', :action => 'show', :id => 1 }]], + ['/people/1',[ { :controller => 'people', :action => 'show', :id => Model.new('1') }]], + ['/people/1',[ { :action => 'show', :id => '1' }, { :controller => 'people', :action => 'index' }]], + ['/people/1',[ { :action => 'show', :id => 1 }, { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people',[ { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people/1',[ {}, { :controller => 'people', :action => 'show', :id => '1' }]], + ['/people/1',[ { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'index', :id => '1' }]], + ['/people/1/edit',[ { :controller => 'people', :action => 'edit', :id => '1' }]], + ['/people/1/edit.xml',[ { :controller => 'people', :action => 'edit', :id => '1', :format => 'xml' }]], + ['/people/1/edit',[ { :use_route => 'edit_person', :id => '1' }]], + ['/people/1?legacy=true',[ { :controller => 'people', :action => 'show', :id => '1', :legacy => 'true' }]], + ['/people?legacy=true',[ { :controller => 'people', :action => 'index', :legacy => 'true' }]], + + ['/id_default/2',[ { :controller => 'foo', :action => 'id_default', :id => '2' }]], + ['/id_default',[ { :controller => 'foo', :action => 'id_default', :id => '1' }]], + ['/id_default',[ { :controller => 'foo', :action => 'id_default', :id => 1 }]], + ['/id_default',[ { :controller => 'foo', :action => 'id_default' }]], + ['/optional/bar',[ { :controller => 'posts', :action => 'index', :optional => 'bar' }]], + ['/posts',[ { :controller => 'posts', :action => 'index' }]], + + ['/project',[ { :controller => 'project', :action => 'index' }]], + ['/projects/1',[ { :controller => 'project', :action => 'index', :project_id => '1' }]], + ['/projects/1',[ { :controller => 'project', :action => 'index'}, {:project_id => '1' }]], + ['/projects/1',[ { :use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1' }]], + ['/projects/1',[ { :use_route => 'project', :controller => 'project', :action => 'index' }, { :project_id => '1' }]], + + ['/clients',[ { :controller => 'projects', :action => 'index' }]], + ['/clients?project_id=1',[ { :controller => 'projects', :action => 'index', :project_id => '1' }]], + ['/clients',[ { :controller => 'projects', :action => 'index' }, { :project_id => '1' }]], + ['/clients',[ { :action => 'index' }, { :controller => 'projects', :action => 'index', :project_id => '1' }]], + + ['/comment/20',[ { :id => 20 }, { :controller => 'comments', :action => 'show' }]], + ['/comment/20',[ { :controller => 'comments', :id => 20, :action => 'show' }]], + ['/comments/boo',[ { :controller => 'comments', :action => 'boo' }]], + + ['/ws/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1', :ws => true }]], + ['/ws/posts',[ { :controller => 'posts', :action => 'index', :ws => true }]], + + ['/account',[ { :controller => 'account', :action => 'subscription' }]], + ['/account/billing',[ { :controller => 'account', :action => 'billing' }]], + + ['/pages/1/notes/show/1',[ { :page_id => '1', :controller => 'notes', :action => 'show', :id => '1' }]], + ['/pages/1/notes/list',[ { :page_id => '1', :controller => 'notes', :action => 'list' }]], + ['/pages/1/notes',[ { :page_id => '1', :controller => 'notes', :action => 'index' }]], + ['/pages/1/notes',[ { :page_id => '1', :controller => 'notes' }]], + ['/notes',[ { :page_id => nil, :controller => 'notes' }]], + ['/notes',[ { :controller => 'notes' }]], + ['/notes/print',[ { :controller => 'notes', :action => 'print' }]], + ['/notes/print',[ {}, { :controller => 'notes', :action => 'print' }]], + + ['/notes/index/1',[ { :controller => 'notes' }, { :controller => 'notes', :id => '1' }]], + ['/notes/index/1',[ { :controller => 'notes' }, { :controller => 'notes', :id => '1', :foo => 'bar' }]], + ['/notes/index/1',[ { :controller => 'notes' }, { :controller => 'notes', :id => '1' }]], + ['/notes/index/1',[ { :action => 'index' }, { :controller => 'notes', :id => '1' }]], + ['/notes/index/1',[ {}, { :controller => 'notes', :id => '1' }]], + ['/notes/show/1',[ {}, { :controller => 'notes', :action => 'show', :id => '1' }]], + ['/notes/index/1',[ { :controller => 'notes', :id => '1' }, { :foo => 'bar' }]], + ['/posts',[ { :controller => 'posts' }, { :controller => 'notes', :action => 'show', :id => '1' }]], + ['/notes/list',[ { :action => 'list' }, { :controller => 'notes', :action => 'show', :id => '1' }]], + + ['/posts/ping',[ { :controller => 'posts', :action => 'ping' }]], + ['/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1' }]], + ['/posts',[ { :controller => 'posts' }]], + ['/posts',[ { :controller => 'posts', :action => 'index' }]], + ['/posts',[ { :controller => 'posts' }, { :controller => 'posts', :action => 'index' }]], + ['/posts/create',[ { :action => 'create' }, { :controller => 'posts' }]], + ['/posts?foo=bar',[ { :controller => 'posts', :foo => 'bar' }]], + ['/posts?foo%5B%5D=bar&foo%5B%5D=baz', [{ :controller => 'posts', :foo => ['bar', 'baz'] }]], + ['/posts?page=2', [{ :controller => 'posts', :page => 2 }]], + ['/posts?q%5Bfoo%5D%5Ba%5D=b', [{ :controller => 'posts', :q => { :foo => { :a => 'b'}} }]], + + ['/news.rss', [{ :controller => 'news', :action => 'index', :format => 'rss' }]], + ].each_with_index do |(url, params), i| + define_method("test_#{url.gsub(/\W/, '_')}_#{i}") do + assert_equal url, url_for(@routes, *params), params.inspect + end + end + end +end diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 484e996f31..dc07e07cb9 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -16,6 +16,10 @@ module AbstractController W.default_url_options[:host] = 'www.basecamphq.com' end + def add_numeric_host! + W.default_url_options[:host] = '127.0.0.1' + end + def test_exception_is_thrown_without_host assert_raise ArgumentError do W.new.url_for :controller => 'c', :action => 'a', :id => 'i' @@ -67,6 +71,27 @@ module AbstractController ) end + def test_subdomain_may_be_removed + add_host! + assert_equal('http://basecamphq.com/c/a/i', + W.new.url_for(:subdomain => false, :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_multiple_subdomains_may_be_removed + W.default_url_options[:host] = 'mobile.www.api.basecamphq.com' + assert_equal('http://basecamphq.com/c/a/i', + W.new.url_for(:subdomain => false, :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_subdomain_may_be_accepted_with_numeric_host + add_numeric_host! + assert_equal('http://127.0.0.1/c/a/i', + W.new.url_for(:subdomain => 'api', :controller => 'c', :action => 'a', :id => 'i') + ) + end + def test_domain_may_be_changed add_host! assert_equal('http://www.37signals.com/c/a/i', diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index 89de4c1da4..f88903b10e 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -70,9 +70,9 @@ class UrlRewriterTests < ActionController::TestCase ) end - def test_anchor_should_be_cgi_escaped + def test_anchor_should_be_uri_escaped assert_equal( - 'http://test.host/c/a/i#anc%2Fhor', + 'http://test.host/c/a/i#anc/hor', @rewriter.rewrite(@routes, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) ) end diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index fb67ecb07d..3765b7eb44 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -148,6 +148,22 @@ class CookiesTest < ActionController::TestCase @request.host = "www.nextangle.com" end + def test_each + request.cookie_jar['foo'] = :bar + list = [] + request.cookie_jar.each do |k,v| + list << [k, v] + end + + assert_equal [['foo', :bar]], list + end + + def test_enumerable + request.cookie_jar['foo'] = :bar + actual = request.cookie_jar.map { |k,v| [k.to_s, v.to_s] } + assert_equal [['foo', 'bar']], actual + end + def test_key_methods assert !request.cookie_jar.key?(:foo) assert !request.cookie_jar.has_key?("foo") @@ -194,8 +210,8 @@ class CookiesTest < ActionController::TestCase assert_equal({"user_name" => "david"}, @response.cookies) end - def test_setting_cookie_with_secure_in_development - Rails.env.stubs(:development?).returns(true) + def test_setting_cookie_with_secure_when_always_write_cookie_is_true + ActionDispatch::Cookies::CookieJar.any_instance.stubs(:always_write_cookie).returns(true) get :authenticate_with_secure assert_cookie_header "user_name=david; path=/; secure" assert_equal({"user_name" => "david"}, @response.cookies) diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb index 3316dd03aa..d3465589c1 100644 --- a/actionpack/test/dispatch/mapper_test.rb +++ b/actionpack/test/dispatch/mapper_test.rb @@ -5,6 +5,7 @@ module ActionDispatch class MapperTest < ActiveSupport::TestCase class FakeSet attr_reader :routes + alias :set :routes def initialize @routes = [] diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb index 851fb59d51..08fe2127b9 100644 --- a/actionpack/test/dispatch/mime_type_test.rb +++ b/actionpack/test/dispatch/mime_type_test.rb @@ -107,8 +107,10 @@ class MimeTypeTest < ActiveSupport::TestCase # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } + types.each do |type| mime = Mime.const_get(type.to_s.upcase) + assert mime.respond_to?("#{type}?"), "#{mime.inspect} does not respond to #{type}?" assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?" invalid_types = types - [type] invalid_types.delete(:html) if Mime::Type.html_types.include?(type) diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb index d854d55173..ad44b4b16a 100644 --- a/actionpack/test/dispatch/request/json_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb @@ -32,13 +32,21 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest test "logs error if parsing unsuccessful" do with_test_routing do + output = StringIO.new + json = "[\"person]\": {\"name\": \"David\"}}" + post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)} + assert_response :error + output.rewind && err = output.read + assert err =~ /Error occurred while parsing request parameters/ + end + end + + test "occurring a parse error if parsing unsuccessful" do + with_test_routing do begin - $stderr = StringIO.new + $stderr = StringIO.new # suppress the log json = "[\"person]\": {\"name\": \"David\"}}" - post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true} - assert_response :error - $stderr.rewind && err = $stderr.read - assert err =~ /Error occurred while parsing request parameters/ + assert_raise(MultiJson::DecodeError) { post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => false} } ensure $stderr = STDERR end diff --git a/actionpack/test/dispatch/request/xml_params_parsing_test.rb b/actionpack/test/dispatch/request/xml_params_parsing_test.rb index 38453dfe48..d8fa751548 100644 --- a/actionpack/test/dispatch/request/xml_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/xml_params_parsing_test.rb @@ -54,13 +54,21 @@ class XmlParamsParsingTest < ActionDispatch::IntegrationTest test "logs error if parsing unsuccessful" do with_test_routing do + output = StringIO.new + xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>" + post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)) + assert_response :error + output.rewind && err = output.read + assert err =~ /Error occurred while parsing request parameters/ + end + end + + test "occurring a parse error if parsing unsuccessful" do + with_test_routing do begin - $stderr = StringIO.new - xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>" - post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true) - assert_response :error - $stderr.rewind && err = $stderr.read - assert err =~ /Error occurred while parsing request parameters/ + $stderr = StringIO.new # suppress the log + xml = "<person><name>David</name></pineapple>" + assert_raise(REXML::ParseException) { post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => false) } ensure $stderr = STDERR end diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb new file mode 100644 index 0000000000..b6e8b6c3ad --- /dev/null +++ b/actionpack/test/dispatch/request_id_test.rb @@ -0,0 +1,65 @@ +require 'abstract_unit' + +class RequestIdTest < ActiveSupport::TestCase + test "passing on the request id from the outside" do + assert_equal "external-uu-rid", stub_request('HTTP_X_REQUEST_ID' => 'external-uu-rid').uuid + end + + test "ensure that only alphanumeric uurids are accepted" do + assert_equal "X-Hacked-HeaderStuff", stub_request('HTTP_X_REQUEST_ID' => '; X-Hacked-Header: Stuff').uuid + end + + test "ensure that 255 char limit on the request id is being enforced" do + assert_equal "X" * 255, stub_request('HTTP_X_REQUEST_ID' => 'X' * 500).uuid + end + + test "generating a request id when none is supplied" do + assert_match(/\w+/, stub_request.uuid) + end + + private + + def stub_request(env = {}) + ActionDispatch::RequestId.new(lambda { |environment| [ 200, environment, [] ] }).call(env) + ActionDispatch::Request.new(env) + end +end + +class RequestIdResponseTest < ActionDispatch::IntegrationTest + class TestController < ActionController::Base + def index + head :ok + end + end + + test "request id is passed all the way to the response" do + with_test_route_set do + get '/' + assert_match(/\w+/, @response.headers["X-Request-Id"]) + end + end + + test "request id given on request is passed all the way to the response" do + with_test_route_set do + get '/', {}, 'HTTP_X_REQUEST_ID' => 'X' * 500 + assert_equal "X" * 255, @response.headers["X-Request-Id"] + end + end + + + private + + def with_test_route_set + with_routing do |set| + set.draw do + match '/', :to => ::RequestIdResponseTest::TestController.action(:index) + end + + @app = self.class.build_app(set) do |middleware| + middleware.use ActionDispatch::RequestId + end + + yield + end + end +end
\ No newline at end of file diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 060bcfb5ec..4d805464c2 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -15,6 +15,7 @@ class RequestTest < ActiveSupport::TestCase assert_equal 'http://www.example.com', url_for assert_equal 'http://api.example.com', url_for(:subdomain => 'api') + assert_equal 'http://example.com', url_for(:subdomain => false) assert_equal 'http://www.ror.com', url_for(:domain => 'ror.com') assert_equal 'http://api.ror.co.uk', url_for(:host => 'www.ror.co.uk', :subdomain => 'api', :tld_length => 2) assert_equal 'http://www.example.com:8080', url_for(:port => 8080) @@ -35,7 +36,7 @@ class RequestTest < ActiveSupport::TestCase request = stub_request 'REMOTE_ADDR' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - assert_equal '1.2.3.4', request.remote_ip + assert_equal '3.4.5.6', request.remote_ip request = stub_request 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' @@ -88,6 +89,11 @@ class RequestTest < ActiveSupport::TestCase assert_equal '9.9.9.9', request.remote_ip end + test "remote ip when the remote ip middleware returns nil" do + request = stub_request 'REMOTE_ADDR' => '127.0.0.1' + assert_equal '127.0.0.1', request.remote_ip + end + test "remote ip with user specified trusted proxies" do @trusted_proxies = /^67\.205\.106\.73$/i @@ -105,7 +111,7 @@ class RequestTest < ActiveSupport::TestCase request = stub_request 'REMOTE_ADDR' => '67.205.106.74,172.16.0.1', 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - assert_equal '67.205.106.74', request.remote_ip + assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,67.205.106.73' assert_equal 'unknown', request.remote_ip diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 1938348375..19eee379fd 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -62,13 +62,8 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest match 'secure', :to => redirect("/secure/login") match 'mobile', :to => redirect(:subdomain => 'mobile') - match 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '') - match 'new_documentation', :to => redirect(:path => '/documentation/new') match 'super_new_documentation', :to => redirect(:host => 'super-docs.com') - match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}') - match 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}') - match 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector) constraints(lambda { |req| true }) do @@ -79,7 +74,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest match 'sign_in' => "sessions#new" match 'account/modulo/:name', :to => redirect("/%{name}s") - match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" } + match 'account/proc/:name', :to => redirect {|params, req| "/#{params[:name].pluralize}" } match 'account/proc_req' => redirect {|params, req| "/#{req.method}" } match 'account/google' => redirect('http://www.google.com/', :status => 302) @@ -339,6 +334,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end scope '(:locale)', :locale => /en|pl/ do + get "registrations/new" resources :descriptions root :to => 'projects#index' end @@ -710,20 +706,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end - def test_redirect_hash_with_domain_and_path - with_test_routes do - get '/documentation' - verify_redirect 'http://www.example-documentation.com' - end - end - - def test_redirect_hash_with_path - with_test_routes do - get '/new_documentation' - verify_redirect 'http://www.example.com/documentation/new' - end - end - def test_redirect_hash_with_host with_test_routes do get '/super_new_documentation?section=top' @@ -731,20 +713,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end - def test_redirect_hash_path_substitution - with_test_routes do - get '/stores/iernest' - verify_redirect 'http://stores.example.com/iernest' - end - end - - def test_redirect_hash_path_substitution_with_catch_all - with_test_routes do - get '/stores/iernest/products' - verify_redirect 'http://stores.example.com/iernest/products' - end - end - def test_redirect_class with_test_routes do get '/youtube_favorites/oHg5SJYRHA0/rick-rolld' @@ -851,6 +819,29 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + # tests the use of dup in url_for + def test_url_for_with_no_side_effects + # without dup, additional (and possibly unwanted) values will be present in the options (eg. :host) + original_options = {:controller => 'projects', :action => 'status'} + options = original_options.dup + + url_for options + + # verify that the options passed in have not changed from the original ones + assert_equal original_options, options + end + + # tests the arguments modification free version of define_hash_access + def test_named_route_with_no_side_effects + original_options = { :host => 'test.host' } + options = original_options.dup + + profile_customer_url("customer_model", options) + + # verify that the options passed in have not changed from the original ones + assert_equal original_options, options + end + def test_projects_status with_test_routes do assert_equal '/projects/status', url_for(:controller => 'projects', :action => 'status', :only_path => true) @@ -1448,6 +1439,16 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + def test_nested_optional_path_shorthand + with_test_routes do + get '/registrations/new' + assert @request.params[:locale].nil? + + get '/en/registrations/new' + assert 'en', @request.params[:locale] + end + end + def test_default_params with_test_routes do get '/inline_pages' @@ -2298,6 +2299,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal "/forced_collision", routes_forced_collision_path end + def test_redirect_argument_error + routes = Class.new { include ActionDispatch::Routing::Redirection }.new + assert_raises(ArgumentError) { routes.redirect Object.new } + end + def test_explicitly_avoiding_the_named_route assert !respond_to?(:routes_no_collision_path) end @@ -2494,3 +2500,40 @@ class TestHttpMethods < ActionDispatch::IntegrationTest end end end + +class TestUriPathEscaping < ActionDispatch::IntegrationTest + Routes = ActionDispatch::Routing::RouteSet.new.tap do |app| + app.draw do + match '/:segment' => lambda { |env| + path_params = env['action_dispatch.request.path_parameters'] + [200, { 'Content-Type' => 'text/plain' }, [path_params[:segment]]] + }, :as => :segment + + match '/*splat' => lambda { |env| + path_params = env['action_dispatch.request.path_parameters'] + [200, { 'Content-Type' => 'text/plain' }, [path_params[:splat]]] + }, :as => :splat + end + end + + include Routes.url_helpers + def app; Routes end + + test 'escapes generated path segment' do + assert_equal '/a%20b/c+d', segment_path(:segment => 'a b/c+d') + end + + test 'unescapes recognized path segment' do + get '/a%20b%2Fc+d' + assert_equal 'a b/c+d', @response.body + end + + test 'escapes generated path splat' do + assert_equal '/a%20b/c+d', splat_path(:splat => 'a b/c+d') + end + + test 'unescapes recognized path splat' do + get '/a%20b/c+d' + assert_equal 'a b/c+d', @response.body + end +end diff --git a/actionpack/test/dispatch/session/cache_store_test.rb b/actionpack/test/dispatch/session/cache_store_test.rb new file mode 100644 index 0000000000..73e056de23 --- /dev/null +++ b/actionpack/test/dispatch/session/cache_store_test.rb @@ -0,0 +1,181 @@ +require 'abstract_unit' + +class CacheStoreTest < ActionDispatch::IntegrationTest + class TestController < ActionController::Base + def no_session_access + head :ok + end + + def set_session_value + session[:foo] = "bar" + head :ok + end + + def set_serialized_session_value + session[:foo] = SessionAutoloadTest::Foo.new + head :ok + end + + def get_session_value + render :text => "foo: #{session[:foo].inspect}" + end + + def get_session_id + render :text => "#{request.session_options[:id]}" + end + + def call_reset_session + session[:bar] + reset_session + session[:bar] = "baz" + head :ok + end + + def rescue_action(e) raise end + end + + def test_setting_and_getting_session_value + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + + get '/get_session_value' + assert_response :success + assert_equal 'foo: "bar"', response.body + end + end + + def test_getting_nil_session_value + with_test_route_set do + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + end + end + + def test_getting_session_value_after_session_reset + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + session_cookie = cookies.send(:hash_for)['_session_id'] + + get '/call_reset_session' + assert_response :success + assert_not_equal [], headers['Set-Cookie'] + + cookies << session_cookie # replace our new session_id with our old, pre-reset session_id + + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body, "data for this session should have been obliterated from cache" + end + end + + def test_getting_from_nonexistent_session + with_test_route_set do + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + assert_nil cookies['_session_id'], "should only create session on write, not read" + end + end + + def test_setting_session_value_after_session_reset + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + session_id = cookies['_session_id'] + + get '/call_reset_session' + assert_response :success + assert_not_equal [], headers['Set-Cookie'] + + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + + get '/get_session_id' + assert_response :success + assert_not_equal session_id, response.body + end + end + + def test_getting_session_id + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + session_id = cookies['_session_id'] + + get '/get_session_id' + assert_response :success + assert_equal session_id, response.body, "should be able to read session id without accessing the session hash" + end + end + + def test_deserializes_unloaded_class + with_test_route_set do + with_autoload_path "session_autoload_test" do + get '/set_serialized_session_value' + assert_response :success + assert cookies['_session_id'] + end + with_autoload_path "session_autoload_test" do + get '/get_session_id' + assert_response :success + end + with_autoload_path "session_autoload_test" do + get '/get_session_value' + assert_response :success + assert_equal 'foo: #<SessionAutoloadTest::Foo bar:"baz">', response.body, "should auto-load unloaded class" + end + end + end + + def test_doesnt_write_session_cookie_if_session_id_is_already_exists + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + + get '/get_session_value' + assert_response :success + assert_equal nil, headers['Set-Cookie'], "should not resend the cookie again if session_id cookie is already exists" + end + end + + def test_prevents_session_fixation + with_test_route_set do + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + session_id = cookies['_session_id'] + + reset! + + get '/set_session_value', :_session_id => session_id + assert_response :success + assert_not_equal session_id, cookies['_session_id'] + end + end + + private + def with_test_route_set + with_routing do |set| + set.draw do + match ':action', :to => ::CacheStoreTest::TestController + end + + @app = self.class.build_app(set) do |middleware| + cache = ActiveSupport::Cache::MemoryStore.new + middleware.use ActionDispatch::Session::CacheStore, :key => '_session_id', :cache => cache + middleware.delete "ActionDispatch::ShowExceptions" + end + + yield + end + end +end diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index 301bf9c6d2..92df6967d6 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -5,7 +5,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest SessionKey = '_myapp_session' SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33' - Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1') + Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, :digest => 'SHA1') SignedBar = Verifier.generate(:foo => "bar", :session_id => SecureRandom.hex(16)) class TestController < ActionController::Base diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb index 42f6c7f79f..90f13a3bb9 100644 --- a/actionpack/test/dispatch/show_exceptions_test.rb +++ b/actionpack/test/dispatch/show_exceptions_test.rb @@ -2,32 +2,38 @@ require 'abstract_unit' class ShowExceptionsTest < ActionDispatch::IntegrationTest - Boomer = lambda do |env| - req = ActionDispatch::Request.new(env) - case req.path - when "/not_found" - raise ActionController::UnknownAction - when "/runtime_error" - raise RuntimeError - when "/method_not_allowed" - raise ActionController::MethodNotAllowed - when "/not_implemented" - raise ActionController::NotImplemented - when "/unprocessable_entity" - raise ActionController::InvalidAuthenticityToken - when "/not_found_original_exception" - raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new) - else - raise "puke!" + class Boomer + def initialize(detailed = false) + @detailed = detailed + end + + def call(env) + env['action_dispatch.show_detailed_exceptions'] = @detailed + req = ActionDispatch::Request.new(env) + case req.path + when "/not_found" + raise ActionController::UnknownAction + when "/runtime_error" + raise RuntimeError + when "/method_not_allowed" + raise ActionController::MethodNotAllowed + when "/not_implemented" + raise ActionController::NotImplemented + when "/unprocessable_entity" + raise ActionController::InvalidAuthenticityToken + when "/not_found_original_exception" + raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new) + else + raise "puke!" + end end end - ProductionApp = ActionDispatch::ShowExceptions.new(Boomer, false) - DevelopmentApp = ActionDispatch::ShowExceptions.new(Boomer, true) + ProductionApp = ActionDispatch::ShowExceptions.new(Boomer.new(false)) + DevelopmentApp = ActionDispatch::ShowExceptions.new(Boomer.new(true)) - test "rescue in public from a remote ip" do + test "rescue with error page when show_exceptions is false" do @app = ProductionApp - self.remote_addr = '208.77.188.166' get "/", {}, {'action_dispatch.show_exceptions' => true} assert_response 500 @@ -42,32 +48,28 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest assert_equal "", body end - test "rescue locally from a local request" do - @app = ProductionApp - ['127.0.0.1', '127.0.0.127', '::1', '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1%0'].each do |ip_address| - self.remote_addr = ip_address + test "rescue with diagnostics message when show_exceptions is true" do + @app = DevelopmentApp - get "/", {}, {'action_dispatch.show_exceptions' => true} - assert_response 500 - assert_match(/puke/, body) + get "/", {}, {'action_dispatch.show_exceptions' => true} + assert_response 500 + assert_match(/puke/, body) - get "/not_found", {}, {'action_dispatch.show_exceptions' => true} - assert_response 404 - assert_match(/#{ActionController::UnknownAction.name}/, body) + get "/not_found", {}, {'action_dispatch.show_exceptions' => true} + assert_response 404 + assert_match(/#{ActionController::UnknownAction.name}/, body) - get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true} - assert_response 405 - assert_match(/ActionController::MethodNotAllowed/, body) - end + get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true} + assert_response 405 + assert_match(/ActionController::MethodNotAllowed/, body) end - test "localize public rescue message" do + test "localize rescue error page" do # Change locale old_locale, I18n.locale = I18n.locale, :da begin @app = ProductionApp - self.remote_addr = '208.77.188.166' get "/", {}, {'action_dispatch.show_exceptions' => true} assert_response 500 @@ -81,23 +83,6 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest end end - test "always rescue locally in development mode" do - @app = DevelopmentApp - self.remote_addr = '208.77.188.166' - - get "/", {}, {'action_dispatch.show_exceptions' => true} - assert_response 500 - assert_match(/puke/, body) - - get "/not_found", {}, {'action_dispatch.show_exceptions' => true} - assert_response 404 - assert_match(/#{ActionController::UnknownAction.name}/, body) - - get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true} - assert_response 405 - assert_match(/ActionController::MethodNotAllowed/, body) - end - test "does not show filtered parameters" do @app = DevelopmentApp @@ -107,16 +92,15 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest assert_match(""foo"=>"[FILTERED]"", body) end - test "show registered original exception for wrapped exceptions when consider_all_requests_local is false" do + test "show registered original exception for wrapped exceptions when show_exceptions is false" do @app = ProductionApp - self.remote_addr = '208.77.188.166' get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true} assert_response 404 assert_match(/404 error/, body) end - test "show registered original exception for wrapped exceptions when consider_all_requests_local is true" do + test "show registered original exception for wrapped exceptions when show_exceptions is true" do @app = DevelopmentApp get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true} @@ -125,7 +109,7 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest end test "show the controller name in the diagnostics template when controller name is present" do - @app = ProductionApp + @app = DevelopmentApp get("/runtime_error", {}, { 'action_dispatch.show_exceptions' => true, 'action_dispatch.request.parameters' => { @@ -144,4 +128,18 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest get "/", {}, {'action_dispatch.show_exceptions' => true} assert_equal "text/html; charset=utf-8", response.headers["Content-Type"] end + + test 'uses logger from env' do + @app = ProductionApp + output = StringIO.new + get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)} + assert_match(/puke/, output.rewind && output.read) + end + + test 'uses backtrace cleaner from env' do + @app = DevelopmentApp + cleaner = stub(:clean => ['passed backtrace cleaner']) + get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner} + assert_match(/passed backtrace cleaner/, body) + end end diff --git a/actionpack/test/fixtures/comments/empty.de.html.erb b/actionpack/test/fixtures/comments/empty.de.html.erb new file mode 100644 index 0000000000..cffd90dd26 --- /dev/null +++ b/actionpack/test/fixtures/comments/empty.de.html.erb @@ -0,0 +1 @@ +<h1>Kein Kommentar</h1>
\ No newline at end of file diff --git a/actionpack/test/fixtures/comments/empty.html.builder b/actionpack/test/fixtures/comments/empty.html.builder new file mode 100644 index 0000000000..2b0c7207a3 --- /dev/null +++ b/actionpack/test/fixtures/comments/empty.html.builder @@ -0,0 +1 @@ +xml.h1 'No Comment'
\ No newline at end of file diff --git a/actionpack/test/fixtures/comments/empty.html.erb b/actionpack/test/fixtures/comments/empty.html.erb new file mode 100644 index 0000000000..827f3861de --- /dev/null +++ b/actionpack/test/fixtures/comments/empty.html.erb @@ -0,0 +1 @@ +<h1>No Comment</h1>
\ No newline at end of file diff --git a/actionpack/test/fixtures/comments/empty.xml.erb b/actionpack/test/fixtures/comments/empty.xml.erb new file mode 100644 index 0000000000..db1027cd7d --- /dev/null +++ b/actionpack/test/fixtures/comments/empty.xml.erb @@ -0,0 +1 @@ +<error>No Comment</error>
\ No newline at end of file diff --git a/actionpack/test/fixtures/company.rb b/actionpack/test/fixtures/company.rb index cd39ea7898..e29978801e 100644 --- a/actionpack/test/fixtures/company.rb +++ b/actionpack/test/fixtures/company.rb @@ -1,10 +1,10 @@ class Company < ActiveRecord::Base has_one :mascot attr_protected :rating - set_sequence_name :companies_nonstd_seq + self.sequence_name = :companies_nonstd_seq validates_presence_of :name def validate errors.add('rating', 'rating should not be 2') if rating == 2 end -end
\ No newline at end of file +end diff --git a/actionpack/test/fixtures/developer.rb b/actionpack/test/fixtures/developer.rb index c70eda34c6..dd14548fac 100644 --- a/actionpack/test/fixtures/developer.rb +++ b/actionpack/test/fixtures/developer.rb @@ -5,5 +5,5 @@ class Developer < ActiveRecord::Base end class DeVeLoPeR < ActiveRecord::Base - set_table_name "developers" + self.table_name = "developers" end diff --git a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb index c479adb897..fa5e6bd318 100644 --- a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb +++ b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb @@ -1,2 +1,3 @@ Hello <%= cache do %>This bit's fragment cached<% end %> +<%= 'Ciao' %> diff --git a/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb new file mode 100644 index 0000000000..2f21a75dd9 --- /dev/null +++ b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb @@ -0,0 +1,3 @@ +<%= content_tag 'p' do %> + <%= content_tag 'b', 'Hello' %> +<% end %> diff --git a/actionpack/test/fixtures/test/_label_with_block.erb b/actionpack/test/fixtures/test/_label_with_block.erb new file mode 100644 index 0000000000..40117e594e --- /dev/null +++ b/actionpack/test/fixtures/test/_label_with_block.erb @@ -0,0 +1,4 @@ +<%= label 'post', 'message' do %> + Message + <%= text_field 'post', 'message' %> +<% end %> diff --git a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb index 5db0822f07..820e7db789 100644 --- a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb +++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb @@ -1,4 +1,4 @@ Before -<%= render :partial => "test/partial.html.erb" %> +<%= render :partial => "test/partial" %> <%= yield %> After diff --git a/actionpack/test/fixtures/test/hello,world.erb b/actionpack/test/fixtures/test/hello,world.erb new file mode 100644 index 0000000000..bc8fa5e0ca --- /dev/null +++ b/actionpack/test/fixtures/test/hello,world.erb @@ -0,0 +1 @@ +Hello w*rld!
\ No newline at end of file diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb index cbef74f992..f2362714d7 100644 --- a/actionpack/test/lib/controller/fake_models.rb +++ b/actionpack/test/lib/controller/fake_models.rb @@ -48,26 +48,19 @@ module Quiz end end -class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost) +class Post < Struct.new(:title, :author_name, :body, :secret, :persisted, :written_on, :cost) extend ActiveModel::Naming include ActiveModel::Conversion extend ActiveModel::Translation alias_method :secret?, :secret + alias_method :persisted?, :persisted def initialize(*args) super @persisted = false end - def persisted=(boolean) - @persisted = boolean - end - - def persisted? - @persisted - end - attr_accessor :author def author_attributes=(attributes); end @@ -182,8 +175,8 @@ class HashBackedAuthor < Hash end module Blog - def self._railtie - self + def self.use_relative_model_naming? + true end class Post < Struct.new(:title, :id) diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index d93433deac..aa7304b3ed 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -366,6 +366,10 @@ class AssetTagHelperTest < ActionView::TestCase assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe? end + def test_stylesheet_link_tag_escapes_options + assert_dom_equal %(<link href="/file.css" media="<script>" rel="stylesheet" type="text/css" />), stylesheet_link_tag('/file', :media => '<script>') + end + def test_custom_stylesheet_expansions ENV["RAILS_ASSET_ID"] = '' ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :robbery => ["bank", "robber"] diff --git a/actionpack/test/template/capture_helper_test.rb b/actionpack/test/template/capture_helper_test.rb index a9157e711c..13e2d5b595 100644 --- a/actionpack/test/template/capture_helper_test.rb +++ b/actionpack/test/template/capture_helper_test.rb @@ -46,6 +46,42 @@ class CaptureHelperTest < ActionView::TestCase assert_equal "bar", content_for(:bar) end + def test_content_for_with_multiple_calls + assert ! content_for?(:title) + content_for :title, 'foo' + content_for :title, 'bar' + assert_equal 'foobar', content_for(:title) + end + + def test_content_for_with_block + assert ! content_for?(:title) + content_for :title do + output_buffer << 'foo' + output_buffer << 'bar' + nil + end + assert_equal 'foobar', content_for(:title) + end + + def test_content_for_with_whitespace_block + assert ! content_for?(:title) + content_for :title, 'foo' + content_for :title do + output_buffer << " \n " + nil + end + content_for :title, 'bar' + assert_equal 'foobar', content_for(:title) + end + + def test_content_for_returns_nil_when_writing + assert ! content_for?(:title) + assert_equal nil, content_for(:title, 'foo') + assert_equal nil, content_for(:title) { output_buffer << 'bar'; nil } + assert_equal nil, content_for(:title) { output_buffer << " \n "; nil } + assert_equal 'foobar', content_for(:title) + end + def test_content_for_question_mark assert ! content_for?(:title) content_for :title, 'title' diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb index 3f31edd5ce..8fc78283d8 100644 --- a/actionpack/test/template/compiled_templates_test.rb +++ b/actionpack/test/template/compiled_templates_test.rb @@ -10,24 +10,24 @@ class CompiledTemplatesTest < Test::Unit::TestCase end def test_template_gets_recompiled_when_using_different_keys_in_local_assigns - assert_equal "one", render(:file => "test/render_file_with_locals_and_default.erb") - assert_equal "two", render(:file => "test/render_file_with_locals_and_default.erb", :locals => { :secret => "two" }) + assert_equal "one", render(:file => "test/render_file_with_locals_and_default") + assert_equal "two", render(:file => "test/render_file_with_locals_and_default", :locals => { :secret => "two" }) end def test_template_changes_are_not_reflected_with_cached_templates - assert_equal "Hello world!", render(:file => "test/hello_world.erb") + assert_equal "Hello world!", render(:file => "test/hello_world") modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Hello world!", render(:file => "test/hello_world.erb") + assert_equal "Hello world!", render(:file => "test/hello_world") end - assert_equal "Hello world!", render(:file => "test/hello_world.erb") + assert_equal "Hello world!", render(:file => "test/hello_world") end def test_template_changes_are_reflected_with_uncached_templates - assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb") + assert_equal "Hello world!", render_without_cache(:file => "test/hello_world") modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb") + assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world") end - assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb") + assert_equal "Hello world!", render_without_cache(:file => "test/hello_world") end private @@ -42,7 +42,7 @@ class CompiledTemplatesTest < Test::Unit::TestCase def render_without_cache(*args) path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH) - view_paths = ActionView::Base.process_view_paths(path) + view_paths = ActionView::PathSet.new([path]) ActionView::Base.new(view_paths, {}).render(*args) end diff --git a/actionpack/test/template/compressors_test.rb b/actionpack/test/template/compressors_test.rb new file mode 100644 index 0000000000..a273f15bd7 --- /dev/null +++ b/actionpack/test/template/compressors_test.rb @@ -0,0 +1,28 @@ +require 'abstract_unit' +require 'sprockets/compressors' + +class CompressorsTest < ActiveSupport::TestCase + def test_register_css_compressor + Sprockets::Compressors.register_css_compressor(:null, Sprockets::NullCompressor) + compressor = Sprockets::Compressors.registered_css_compressor(:null) + assert_kind_of Sprockets::NullCompressor, compressor + end + + def test_register_js_compressor + Sprockets::Compressors.register_js_compressor(:uglifier, 'Uglifier', :require => 'uglifier') + compressor = Sprockets::Compressors.registered_js_compressor(:uglifier) + assert_kind_of Uglifier, compressor + end + + def test_register_default_css_compressor + Sprockets::Compressors.register_css_compressor(:null, Sprockets::NullCompressor, :default => true) + compressor = Sprockets::Compressors.registered_css_compressor(:default) + assert_kind_of Sprockets::NullCompressor, compressor + end + + def test_register_default_js_compressor + Sprockets::Compressors.register_js_compressor(:null, Sprockets::NullCompressor, :default => true) + compressor = Sprockets::Compressors.registered_js_compressor(:default) + assert_kind_of Sprockets::NullCompressor, compressor + end +end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 09c53a36f0..af30ec9892 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -664,6 +664,15 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]") end + def test_select_date_with_too_big_range_between_start_year_and_end_year + assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 20000, :prefix => "date[first]", :order => [:month, :day, :year]) } + assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => Date.today.year - 100.years, :end_year => 2000, :prefix => "date[first]", :order => [:month, :day, :year]) } + end + + def test_select_date_can_have_more_then_1000_years_interval_if_forced_via_parameter + assert_nothing_raised { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 3100, :max_years_allowed => 2000) } + end + def test_select_date_with_order expected = %(<select id="date_first_month" name="date[first][month]">\n) expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 71a2c46d92..3fee366804 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -3,6 +3,8 @@ require 'controller/fake_models' require 'active_support/core_ext/object/inclusion' class FormHelperTest < ActionView::TestCase + include RenderERBUtils + tests ActionView::Helpers::FormHelper def form_for(*) @@ -27,7 +29,13 @@ class FormHelperTest < ActionView::TestCase :body => "Write entire text here", :color => { :red => "Rojo" + }, + :comments => { + :body => "Write body here" } + }, + :tag => { + :value => "Tag" } } } @@ -68,6 +76,12 @@ class FormHelperTest < ActionView::TestCase @post.secret = 1 @post.written_on = Date.new(2004, 6, 15) + @post.comments = [] + @post.comments << @comment + + @post.tags = [] + @post.tags << Tag.new + @blog_post = Blog::Post.new("And his name will be forty and four.", 44) end @@ -151,6 +165,40 @@ class FormHelperTest < ActionView::TestCase I18n.locale = old_locale end + def test_label_with_locales_and_nested_attributes + old_locale, I18n.locale = I18n.locale, :label + form_for(@post, :html => { :id => 'create-post' }) do |f| + f.fields_for(:comments) do |cf| + concat cf.label(:body) + end + end + + expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do + "<label for=\"post_comments_attributes_0_body\">Write body here</label>" + end + + assert_dom_equal expected, output_buffer + ensure + I18n.locale = old_locale + end + + def test_label_with_locales_fallback_and_nested_attributes + old_locale, I18n.locale = I18n.locale, :label + form_for(@post, :html => { :id => 'create-post' }) do |f| + f.fields_for(:tags) do |cf| + concat cf.label(:value) + end + end + + expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do + "<label for=\"post_tags_attributes_0_value\">Tag</label>" + end + + assert_dom_equal expected, output_buffer + ensure + I18n.locale = old_locale + end + def test_label_with_for_attribute_as_symbol assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for")) end @@ -184,6 +232,10 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal('<label for="post_title">The title, please:</label>', label(:post, :title) { "The title, please:" }) end + def test_label_with_block_in_erb + assert_equal "<label for=\"post_message\">\n Message\n <input id=\"post_message\" name=\"post[message]\" size=\"30\" type=\"text\" />\n</label>", view.render("test/label_with_block") + end + def test_text_field assert_dom_equal( '<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title") @@ -438,13 +490,17 @@ class FormHelperTest < ActionView::TestCase end def test_number_field - expected = %{<input name="order[quantity]" size="30" max="9" id="order_quantity" type="number" min="1" />} + expected = %{<input name="order[quantity]" max="9" id="order_quantity" type="number" min="1" />} assert_dom_equal(expected, number_field("order", "quantity", :in => 1...10)) + expected = %{<input name="order[quantity]" size="30" max="9" id="order_quantity" type="number" min="1" />} + assert_dom_equal(expected, number_field("order", "quantity", :size => 30, :in => 1...10)) end def test_range_input - expected = %{<input name="hifi[volume]" step="0.1" size="30" max="11" id="hifi_volume" type="range" min="0" />} + expected = %{<input name="hifi[volume]" step="0.1" max="11" id="hifi_volume" type="range" min="0" />} assert_dom_equal(expected, range_field("hifi", "volume", :in => 0..11, :step => 0.1)) + expected = %{<input name="hifi[volume]" step="0.1" size="30" max="11" id="hifi_volume" type="range" min="0" />} + assert_dom_equal(expected, range_field("hifi", "volume", :size => 30, :in => 0..11, :step => 0.1)) end def test_explicit_name @@ -690,7 +746,7 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - def test_form_for_with_isolated_namespaced_model + def test_form_for_with_model_using_relative_model_naming form_for(@blog_post) do |f| concat f.text_field :title concat f.submit('Edit post') @@ -698,8 +754,7 @@ class FormHelperTest < ActionView::TestCase expected = whole_form("/posts/44", "edit_post_44" , "edit_post", :method => "put") do "<input name='post[title]' size='30' type='text' id='post_title' value='And his name will be forty and four.' />" + - "<input name='commit' type='submit' value='Edit post' />" + - "</form>" + "<input name='commit' type='submit' value='Edit post' />" end assert_dom_equal expected, output_buffer @@ -879,6 +934,82 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_with_namespace + form_for(@post, :namespace => 'namespace') do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do + "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" + + "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='namespace_post_secret' value='1' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_for_with_namespace_with_label + form_for(@post, :namespace => 'namespace') do |f| + concat f.label(:title) + concat f.text_field(:title) + end + + expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do + "<label for='namespace_post_title'>Title</label>" + + "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_two_form_for_with_namespace + form_for(@post, :namespace => 'namespace_1') do |f| + concat f.label(:title) + concat f.text_field(:title) + end + + expected_1 = whole_form('/posts/123', 'namespace_1_edit_post_123', 'edit_post', 'put') do + "<label for='namespace_1_post_title'>Title</label>" + + "<input name='post[title]' size='30' type='text' id='namespace_1_post_title' value='Hello World' />" + end + + assert_dom_equal expected_1, output_buffer + + form_for(@post, :namespace => 'namespace_2') do |f| + concat f.label(:title) + concat f.text_field(:title) + end + + expected_2 = whole_form('/posts/123', 'namespace_2_edit_post_123', 'edit_post', 'put') do + "<label for='namespace_2_post_title'>Title</label>" + + "<input name='post[title]' size='30' type='text' id='namespace_2_post_title' value='Hello World' />" + end + + assert_dom_equal expected_2, output_buffer + end + + def test_fields_for_with_namespace + @comment.body = 'Hello World' + form_for(@post, :namespace => 'namespace') do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.fields_for(@comment) { |c| + concat c.text_field(:body) + } + end + + expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do + "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" + + "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[comment][body]' size='30' type='text' id='namespace_post_comment_body' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + def test_submit_with_object_as_new_record_and_locale_strings old_locale, I18n.locale = I18n.locale, :submit @@ -1895,7 +2026,7 @@ class FormHelperTest < ActionView::TestCase path = nil form_for(@post, :builder => LabelledFormBuilder) do |f| - path = f.to_path + path = f.to_partial_path '' end diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index 6aea991f7c..469718e1bd 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -587,6 +587,24 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_empty + @post = Post.new + @post.category = "" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>", + select("post", "category", [], :prompt => true, :include_blank => true) + ) + end + + def test_list_of_lists + @post = Post.new + @post.category = "" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"number\">Number</option>\n<option value=\"text\">Text</option>\n<option value=\"boolean\">Yes/No</option></select>", + select("post", "category", [["Number", "number"], ["Text", "text"], ["Yes/No", "boolean"]], :prompt => true, :include_blank => true) + ) + end + def test_select_with_selected_value @post = Post.new @post.category = "<mus>" diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 979251bfd1..233907d07a 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -2,6 +2,8 @@ require 'abstract_unit' require 'active_support/core_ext/object/inclusion' class FormTagHelperTest < ActionView::TestCase + include RenderERBUtils + tests ActionView::Helpers::FormTagHelper def setup @@ -104,14 +106,14 @@ class FormTagHelperTest < ActionView::TestCase end def test_form_tag_with_block_in_erb - output_buffer = form_tag("http://www.example.com") { concat "Hello world!" } + output_buffer = render_erb("<%= form_tag('http://www.example.com') do %>Hello world!<% end %>") expected = whole_form { "Hello world!" } assert_dom_equal expected, output_buffer end def test_form_tag_with_block_and_method_in_erb - output_buffer = form_tag("http://www.example.com", :method => :put) { concat "Hello world!" } + output_buffer = render_erb("<%= form_tag('http://www.example.com', :method => :put) do %>Hello world!<% end %>") expected = whole_form("http://www.example.com", :method => "put") do "Hello world!" @@ -485,27 +487,57 @@ class FormTagHelperTest < ActionView::TestCase end def test_field_set_tag_in_erb - output_buffer = field_set_tag("Your details") { concat "Hello world!" } + output_buffer = render_erb("<%= field_set_tag('Your details') do %>Hello world!<% end %>") expected = %(<fieldset><legend>Your details</legend>Hello world!</fieldset>) assert_dom_equal expected, output_buffer - output_buffer = field_set_tag { concat "Hello world!" } + output_buffer = render_erb("<%= field_set_tag do %>Hello world!<% end %>") expected = %(<fieldset>Hello world!</fieldset>) assert_dom_equal expected, output_buffer - output_buffer = field_set_tag('') { concat "Hello world!" } + output_buffer = render_erb("<%= field_set_tag('') do %>Hello world!<% end %>") expected = %(<fieldset>Hello world!</fieldset>) assert_dom_equal expected, output_buffer - output_buffer = field_set_tag('', :class => 'format') { concat "Hello world!" } + output_buffer = render_erb("<%= field_set_tag('', :class => 'format') do %>Hello world!<% end %>") expected = %(<fieldset class="format">Hello world!</fieldset>) assert_dom_equal expected, output_buffer end + def test_text_area_tag_options_symbolize_keys_side_effects + options = { :option => "random_option" } + text_area_tag "body", "hello world", options + assert_equal options, { :option => "random_option" } + end + + def test_submit_tag_options_symbolize_keys_side_effects + options = { :option => "random_option" } + submit_tag "submit value", options + assert_equal options, { :option => "random_option" } + end + + def test_button_tag_options_symbolize_keys_side_effects + options = { :option => "random_option" } + button_tag "button value", options + assert_equal options, { :option => "random_option" } + end + + def test_image_submit_tag_options_symbolize_keys_side_effects + options = { :option => "random_option" } + image_submit_tag "submit source", options + assert_equal options, { :option => "random_option" } + end + + def test_image_label_tag_options_symbolize_keys_side_effects + options = { :option => "random_option" } + label_tag "submit source", "title", options + assert_equal options, { :option => "random_option" } + end + def protect_against_forgery? false end diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb index 678cb9eeeb..62ad6be680 100644 --- a/actionpack/test/template/html-scanner/sanitizer_test.rb +++ b/actionpack/test/template/html-scanner/sanitizer_test.rb @@ -5,6 +5,13 @@ class SanitizerTest < ActionController::TestCase @sanitizer = nil # used by assert_sanitizer end + def test_strip_tags_with_quote + sanitizer = HTML::FullSanitizer.new + string = '<" <img src="trollface.gif" onload="alert(1)"> hi' + + assert_equal ' hi', sanitizer.sanitize(string) + end + def test_strip_tags sanitizer = HTML::FullSanitizer.new assert_equal("<<<bad html", sanitizer.sanitize("<<<bad html")) diff --git a/actionpack/test/template/html-scanner/tag_node_test.rb b/actionpack/test/template/html-scanner/tag_node_test.rb index 0d87f1bd42..3b72243e7d 100644 --- a/actionpack/test/template/html-scanner/tag_node_test.rb +++ b/actionpack/test/template/html-scanner/tag_node_test.rb @@ -55,7 +55,12 @@ class TagNodeTest < Test::Unit::TestCase def test_to_s node = tag("<a b=c d='f' g=\"h 'i'\" />") - assert_equal %(<a b="c" d="f" g="h 'i'" />), node.to_s + node = node.to_s + assert node.include?('a') + assert node.include?('b="c"') + assert node.include?('d="f"') + assert node.include?('g="h') + assert node.include?('i') end def test_tag diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb index dd8b7b7cd5..4b9c3c97b1 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/core_ext/string/encoding' class JavaScriptHelperTest < ActionView::TestCase tests ActionView::Helpers::JavaScriptHelper @@ -27,6 +28,11 @@ class JavaScriptHelperTest < ActionView::TestCase assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos')) assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) ) assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags)) + if "ruby".encoding_aware? + assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding('UTF-8').encode!) + else + assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\250 newline)) + end assert_equal %(dont <\\/close> tags), j(%(dont </close> tags)) end diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb index 50e1cccd3b..752b0f23a8 100644 --- a/actionpack/test/template/log_subscriber_test.rb +++ b/actionpack/test/template/log_subscriber_test.rb @@ -27,7 +27,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_file_template - @view.render(:file => "test/hello_world.erb") + @view.render(:file => "test/hello_world") wait assert_equal 1, @logger.logged(:info).size diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index 47b70f05ab..bac2530e3d 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -31,16 +31,6 @@ class LookupContextTest < ActiveSupport::TestCase assert @lookup_context.formats.frozen? end - test "allows me to change some details to execute an specific block of code" do - formats = Mime::SET - @lookup_context.update_details(:locale => :pt) do - assert_equal formats, @lookup_context.formats - assert_equal :pt, @lookup_context.locale - end - assert_equal formats, @lookup_context.formats - assert_equal :en, @lookup_context.locale - end - test "provides getters and setters for formats" do @lookup_context.formats = [:html] assert_equal [:html], @lookup_context.formats diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 0e3475d98b..8d679aac1d 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -27,6 +27,7 @@ class NumberHelperTest < ActionView::TestCase assert_equal("800 555 1212", number_to_phone(8005551212, {:delimiter => " "})) assert_equal("(800) 555-1212 x 123", number_to_phone(8005551212, {:area_code => true, :extension => 123})) assert_equal("800-555-1212", number_to_phone(8005551212, :extension => " ")) + assert_equal("555.1212", number_to_phone(5551212, :delimiter => '.')) assert_equal("800-555-1212", number_to_phone("8005551212")) assert_equal("+1-800-555-1212", number_to_phone(8005551212, :country_code => 1)) assert_equal("+18005551212", number_to_phone(8005551212, :country_code => 1, :delimiter => '')) diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb index 1ba14e8bc9..ec777d15c4 100644 --- a/actionpack/test/template/record_tag_helper_test.rb +++ b/actionpack/test/template/record_tag_helper_test.rb @@ -4,15 +4,26 @@ require 'controller/fake_models' class Post extend ActiveModel::Naming include ActiveModel::Conversion + attr_writer :id, :body + + def initialize + @id = nil + @body = nil + super + end + def id - 45 + @id || 45 end + def body - super || "What a wonderful world!" + super || @body || "What a wonderful world!" end end class RecordTagHelperTest < ActionView::TestCase + include RenderERBUtils + tests ActionView::Helpers::RecordTagHelper def setup @@ -49,13 +60,41 @@ class RecordTagHelperTest < ActionView::TestCase def test_block_works_with_content_tag_for_in_erb expected = %(<tr class="post" id="post_45">#{@post.body}</tr>) - actual = content_tag_for(:tr, @post) { concat @post.body } + actual = render_erb("<%= content_tag_for(:tr, @post) do %><%= @post.body %><% end %>") assert_dom_equal expected, actual end def test_div_for_in_erb expected = %(<div class="post bar" id="post_45">#{@post.body}</div>) - actual = div_for(@post, :class => "bar") { concat @post.body } + actual = render_erb("<%= div_for(@post, :class => 'bar') do %><%= @post.body %><% end %>") + assert_dom_equal expected, actual + end + + def test_content_tag_for_collection + post_1 = Post.new.tap { |post| post.id = 101; post.body = "Hello!"; post.persisted = true } + post_2 = Post.new.tap { |post| post.id = 102; post.body = "World!"; post.persisted = true } + expected = %(<li class="post" id="post_101">Hello!</li>\n<li class="post" id="post_102">World!</li>) + actual = content_tag_for(:li, [post_1, post_2]) { |post| concat post.body } + assert_dom_equal expected, actual + end + + def test_div_for_collection + post_1 = Post.new.tap { |post| post.id = 101; post.body = "Hello!"; post.persisted = true } + post_2 = Post.new.tap { |post| post.id = 102; post.body = "World!"; post.persisted = true } + expected = %(<div class="post" id="post_101">Hello!</div>\n<div class="post" id="post_102">World!</div>) + actual = div_for([post_1, post_2]) { |post| concat post.body } assert_dom_equal expected, actual end + + def test_content_tag_for_single_record_is_html_safe + result = div_for(@post, :class => "bar") { concat @post.body } + assert result.html_safe? + end + + def test_content_tag_for_collection_is_html_safe + post_1 = Post.new.tap { |post| post.id = 101; post.body = "Hello!"; post.persisted = true } + post_2 = Post.new.tap { |post| post.id = 102; post.body = "World!"; post.persisted = true } + result = content_tag_for(:li, [post_1, post_2]) { |post| concat post.body } + assert result.html_safe? + end end diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 0b91e55091..c29519276d 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -21,18 +21,48 @@ module RenderTestCases end def test_render_file - assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb") + assert_equal "Hello world!", @view.render(:file => "test/hello_world") end def test_render_file_not_using_full_path - assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb") + assert_equal "Hello world!", @view.render(:file => "test/hello_world") end def test_render_file_without_specific_extension assert_equal "Hello world!", @view.render(:file => "test/hello_world") end - def test_render_file_with_localization + # Test if :formats, :locale etc. options are passed correctly to the resolvers. + def test_render_file_with_format + assert_match "<h1>No Comment</h1>", @view.render(:file => "comments/empty", :formats => [:html]) + assert_match "<error>No Comment</error>", @view.render(:file => "comments/empty", :formats => [:xml]) + assert_match "<error>No Comment</error>", @view.render(:file => "comments/empty", :formats => :xml) + end + + def test_render_template_with_format + assert_match "<h1>No Comment</h1>", @view.render(:template => "comments/empty", :formats => [:html]) + assert_match "<error>No Comment</error>", @view.render(:template => "comments/empty", :formats => [:xml]) + end + + def test_render_file_with_locale + assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => [:de]) + assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => :de) + end + + def test_render_template_with_locale + assert_equal "<h1>Kein Kommentar</h1>", @view.render(:template => "comments/empty", :locale => [:de]) + end + + def test_render_file_with_handlers + assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => [:builder]) + assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => :builder) + end + + def test_render_template_with_handlers + assert_equal "<h1>No Comment</h1>\n", @view.render(:template => "comments/empty", :handlers => [:builder]) + end + + def test_render_file_with_localization_on_context_level old_locale, @view.locale = @view.locale, :da assert_equal "Hey verden", @view.render(:file => "test/hello_world") ensure @@ -51,17 +81,17 @@ module RenderTestCases end def test_render_file_with_full_path - template_path = File.join(File.dirname(__FILE__), '../fixtures/test/hello_world.erb') + template_path = File.join(File.dirname(__FILE__), '../fixtures/test/hello_world') assert_equal "Hello world!", @view.render(:file => template_path) end def test_render_file_with_instance_variables - assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar.erb") + assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar") end def test_render_file_with_locals locals = { :secret => 'in the sauce' } - assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals.erb", :locals => locals) + assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals", :locals => locals) end def test_render_file_not_using_full_path_with_dot_in_path @@ -80,13 +110,18 @@ module RenderTestCases assert_equal 'partial html', @view.render(:partial => 'test/partial') end + def test_render_partial_with_selected_format + assert_equal 'partial html', @view.render(:partial => 'test/partial', :formats => :html) + assert_equal 'partial js', @view.render(:partial => 'test/partial', :formats => [:js]) + end + def test_render_partial_at_top_level - # file fixtures/_top_level_partial_only.erb (not fixtures/test) + # file fixtures/_top_level_partial_only (not fixtures/test) assert_equal 'top level partial', @view.render(:partial => '/top_level_partial_only') end def test_render_partial_with_format_at_top_level - # file fixtures/_top_level_partial.html.erb (not fixtures/test, with format extension) + # file fixtures/_top_level_partial.html (not fixtures/test, with format extension) assert_equal 'top level partial html', @view.render(:partial => '/top_level_partial') end @@ -107,6 +142,13 @@ module RenderTestCases "and is followed by any combinations of letters, numbers, or underscores.", e.message end + def test_render_partial_with_incompatible_object + @view.render(:partial => nil) + flunk "Render did not raise ArgumentError" + rescue ArgumentError => e + assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object that returns a valid partial path.", e.message + end + def test_render_partial_with_errors @view.render(:partial => "test/raise") flunk "Render did not raise Template::Error" @@ -214,14 +256,14 @@ module RenderTestCases end def test_render_partial_using_object_with_deprecated_partial_path - assert_deprecated(/#model_name.*#partial_path.*#to_path/) do + assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do assert_equal "Hello: nertzy", @controller_view.render(CustomerWithDeprecatedPartialPath.new("nertzy"), :greeting => "Hello") end end def test_render_partial_using_collection_with_deprecated_partial_path - assert_deprecated(/#model_name.*#partial_path.*#to_path/) do + assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do customers = [ CustomerWithDeprecatedPartialPath.new("nertzy"), CustomerWithDeprecatedPartialPath.new("peeja") @@ -245,7 +287,7 @@ module RenderTestCases end def test_render_layout_with_block_and_other_partial_inside - render = @view.render(:layout => "test/layout_with_partial_and_yield.html.erb") { "Yield!" } + render = @view.render(:layout => "test/layout_with_partial_and_yield") { "Yield!" } assert_equal "Before\npartial html\nYield!\nAfter\n", render end @@ -282,24 +324,26 @@ module RenderTestCases end def test_render_ignores_templates_with_malformed_template_handlers - %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name| - assert_raise(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") } + ActiveSupport::Deprecation.silence do + %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name| + assert_raise(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") } + end end end def test_render_with_layout assert_equal %(<title></title>\nHello world!\n), - @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield") + @view.render(:file => "test/hello_world", :layout => "layouts/yield") end def test_render_with_layout_which_has_render_inline assert_equal %(welcome\nHello world!\n), - @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_inline_inside") + @view.render(:file => "test/hello_world", :layout => "layouts/yield_with_render_inline_inside") end def test_render_with_layout_which_renders_another_partial assert_equal %(partial html\nHello world!\n), - @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_partial_inside") + @view.render(:file => "test/hello_world", :layout => "layouts/yield_with_render_partial_inside") end def test_render_layout_with_block_and_yield @@ -344,17 +388,17 @@ module RenderTestCases def test_render_with_nested_layout assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n), - @view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield") + @view.render(:file => "test/nested_layout", :layout => "layouts/yield") end def test_render_with_file_in_layout assert_equal %(\n<title>title</title>\n\n), - @view.render(:file => "test/layout_render_file.erb") + @view.render(:file => "test/layout_render_file") end def test_render_layout_with_object assert_equal %(<title>David</title>), - @view.render(:file => "test/layout_render_object.erb") + @view.render(:file => "test/layout_render_object") end end @@ -380,7 +424,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase # is not eager loaded def setup path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH) - view_paths = ActionView::Base.process_view_paths(path) + view_paths = ActionView::PathSet.new([path]) assert_equal ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH), view_paths.first setup_view(view_paths) end @@ -392,7 +436,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase if '1.9'.respond_to?(:force_encoding) def test_render_utf8_template_with_magic_comment with_external_encoding Encoding::ASCII_8BIT do - result = @view.render(:file => "test/utf8_magic.html.erb", :layouts => "layouts/yield") + result = @view.render(:file => "test/utf8_magic", :formats => [:html], :layouts => "layouts/yield") assert_equal Encoding::UTF_8, result.encoding assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result end @@ -400,7 +444,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase def test_render_utf8_template_with_default_external_encoding with_external_encoding Encoding::UTF_8 do - result = @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield") + result = @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield") assert_equal Encoding::UTF_8, result.encoding assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result end @@ -409,7 +453,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase def test_render_utf8_template_with_incompatible_external_encoding with_external_encoding Encoding::SHIFT_JIS do begin - @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield") + @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield") flunk 'Should have raised incompatible encoding error' rescue ActionView::Template::Error => error assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message @@ -420,7 +464,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase def test_render_utf8_template_with_partial_with_incompatible_encoding with_external_encoding Encoding::SHIFT_JIS do begin - @view.render(:file => "test/utf8_magic_with_bare_partial.html.erb", :layouts => "layouts/yield") + @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield") flunk 'Should have raised incompatible encoding error' rescue ActionView::Template::Error => error assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message diff --git a/actionpack/test/template/sprockets_helper_test.rb b/actionpack/test/template/sprockets_helper_test.rb index b9161b62c5..64fdd53e73 100644 --- a/actionpack/test/template/sprockets_helper_test.rb +++ b/actionpack/test/template/sprockets_helper_test.rb @@ -28,17 +28,40 @@ class SprocketsHelperTest < ActionView::TestCase application = Struct.new(:config, :assets).new(config, @assets) Rails.stubs(:application).returns(application) @config = config - @config.action_controller ||= ActiveSupport::InheritableOptions.new @config.perform_caching = true + @config.assets.digest = true + @config.assets.compile = true end def url_for(*args) "http://www.example.com" end + def config + @controller ? @controller.config : @config + end + + def compute_host(source, request, options = {}) + raise "Should never get here" + end + test "asset_path" do assert_match %r{/assets/logo-[0-9a-f]+.png}, asset_path("logo.png") + assert_match %r{/assets/logo-[0-9a-f]+.png}, + asset_path("logo.png", :digest => true) + assert_match %r{/assets/logo.png}, + asset_path("logo.png", :digest => false) + end + + test "custom_asset_path" do + @config.assets.prefix = '/s' + assert_match %r{/s/logo-[0-9a-f]+.png}, + asset_path("logo.png") + assert_match %r{/s/logo-[0-9a-f]+.png}, + asset_path("logo.png", :digest => true) + assert_match %r{/s/logo.png}, + asset_path("logo.png", :digest => false) end test "asset_path with root relative assets" do @@ -59,8 +82,9 @@ class SprocketsHelperTest < ActionView::TestCase end test "with a simple asset host the url should default to protocol relative" do + @controller.config.default_asset_host_protocol = :relative @controller.config.asset_host = "assets-%d.example.com" - assert_match %r{//assets-\d.example.com/assets/logo-[0-9a-f]+.png}, + assert_match %r{^//assets-\d.example.com/assets/logo-[0-9a-f]+.png}, asset_path("logo.png") end @@ -72,10 +96,11 @@ class SprocketsHelperTest < ActionView::TestCase end test "With a proc asset host that returns no protocol the url should be protocol relative" do + @controller.config.default_asset_host_protocol = :relative @controller.config.asset_host = Proc.new do |asset| "assets-999.example.com" end - assert_match %r{//assets-999.example.com/assets/logo-[0-9a-f]+.png}, + assert_match %r{^//assets-999.example.com/assets/logo-[0-9a-f]+.png}, asset_path("logo.png") end @@ -97,20 +122,52 @@ class SprocketsHelperTest < ActionView::TestCase end test "stylesheets served without a controller in scope cannot access the request" do - remove_instance_variable("@controller") - @config.action_controller.asset_host = Proc.new do |asset, request| + @controller = nil + @config.asset_host = Proc.new do |asset, request| fail "This should not have been called." end assert_raises ActionController::RoutingError do asset_path("logo.png") end + @config.asset_host = method :compute_host + assert_raises ActionController::RoutingError do + asset_path("logo.png") + end + end + + test "image_tag" do + assert_dom_equal '<img alt="Xml" src="/assets/xml.png" />', image_tag("xml.png") + end + + test "image_path" do + assert_match %r{/assets/logo-[0-9a-f]+.png}, + image_path("logo.png") + + assert_match %r{/assets/logo-[0-9a-f]+.png}, + path_to_image("logo.png") + end + + test "javascript_path" do + assert_match %r{/assets/application-[0-9a-f]+.js}, + javascript_path("application.js") + + assert_match %r{/assets/application-[0-9a-f]+.js}, + path_to_javascript("application.js") + end + + test "stylesheet_path" do + assert_match %r{/assets/application-[0-9a-f]+.css}, + stylesheet_path("application.css") + + assert_match %r{/assets/application-[0-9a-f]+.css}, + path_to_stylesheet("application.css") end test "stylesheets served without a controller in do not use asset hosts when the default protocol is :request" do - remove_instance_variable("@controller") - @config.action_controller.asset_host = "assets-%d.example.com" - @config.action_controller.default_asset_host_protocol = :request - @config.action_controller.perform_caching = true + @controller = nil + @config.asset_host = "assets-%d.example.com" + @config.default_asset_host_protocol = :request + @config.perform_caching = true assert_match %r{/assets/logo-[0-9a-f]+.png}, asset_path("logo.png") @@ -122,27 +179,38 @@ class SprocketsHelperTest < ActionView::TestCase asset_path("/images/logo.gif") end - test "javascript path" do + test "asset path with relative url root when controller isn't present but relative_url_root is" do + @controller = nil + @config.relative_url_root = "/collaboration/hieraki" + assert_equal "/collaboration/hieraki/images/logo.gif", + asset_path("/images/logo.gif") + end + + test "javascript path through asset_path" do assert_match %r{/assets/application-[0-9a-f]+.js}, - asset_path(:application, "js") + asset_path(:application, :ext => "js") assert_match %r{/assets/xmlhr-[0-9a-f]+.js}, - asset_path("xmlhr", "js") + asset_path("xmlhr", :ext => "js") assert_match %r{/assets/dir/xmlhr-[0-9a-f]+.js}, - asset_path("dir/xmlhr.js", "js") + asset_path("dir/xmlhr.js", :ext => "js") assert_equal "/dir/xmlhr.js", - asset_path("/dir/xmlhr", "js") + asset_path("/dir/xmlhr", :ext => "js") assert_equal "http://www.example.com/js/xmlhr", - asset_path("http://www.example.com/js/xmlhr", "js") + asset_path("http://www.example.com/js/xmlhr", :ext => "js") assert_equal "http://www.example.com/js/xmlhr.js", - asset_path("http://www.example.com/js/xmlhr.js", "js") + asset_path("http://www.example.com/js/xmlhr.js", :ext => "js") end test "javascript include tag" do assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>}, javascript_include_tag(:application) + assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>}, + javascript_include_tag(:application, :digest => true) + assert_match %r{<script src="/assets/application.js" type="text/javascript"></script>}, + javascript_include_tag(:application, :digest => false) assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js" type="text/javascript"></script>}, javascript_include_tag("xmlhr") @@ -151,29 +219,43 @@ class SprocketsHelperTest < ActionView::TestCase assert_equal '<script src="http://www.example.com/xmlhr" type="text/javascript"></script>', javascript_include_tag("http://www.example.com/xmlhr") + assert_match %r{<script src=\"/assets/xmlhr-[0-9a-f]+.js" type=\"text/javascript\"></script>\n<script src=\"/assets/extra-[0-9a-f]+.js" type=\"text/javascript\"></script>}, + javascript_include_tag("xmlhr", "extra") + assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>}, javascript_include_tag(:application, :debug => true) - assert_match %r{<script src=\"/assets/xmlhr-[0-9a-f]+.js\" type=\"text/javascript\"></script>\n<script src=\"/assets/extra-[0-9a-f]+.js\" type=\"text/javascript\"></script>}, - javascript_include_tag("xmlhr", "extra") + assert_match %r{<script src="/assets/jquery.plugin.js" type="text/javascript"></script>}, + javascript_include_tag('jquery.plugin', :digest => false) + + @config.assets.compile = true + @config.assets.debug = true + assert_match %r{<script src="/javascripts/application.js" type="text/javascript"></script>}, + javascript_include_tag('/javascripts/application') + assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>}, + javascript_include_tag(:application) end - test "stylesheet path" do - assert_match %r{/assets/application-[0-9a-f]+.css}, asset_path(:application, "css") + test "stylesheet path through asset_path" do + assert_match %r{/assets/application-[0-9a-f]+.css}, asset_path(:application, :ext => "css") - assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", "css") - assert_match %r{/assets/dir/style-[0-9a-f]+.css}, asset_path("dir/style.css", "css") - assert_equal "/dir/style.css", asset_path("/dir/style.css", "css") + assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", :ext => "css") + assert_match %r{/assets/dir/style-[0-9a-f]+.css}, asset_path("dir/style.css", :ext => "css") + assert_equal "/dir/style.css", asset_path("/dir/style.css", :ext => "css") assert_equal "http://www.example.com/css/style", - asset_path("http://www.example.com/css/style", "css") + asset_path("http://www.example.com/css/style", :ext => "css") assert_equal "http://www.example.com/css/style.css", - asset_path("http://www.example.com/css/style.css", "css") + asset_path("http://www.example.com/css/style.css", :ext => "css") end test "stylesheet link tag" do assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, stylesheet_link_tag(:application) + assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, + stylesheet_link_tag(:application, :digest => true) + assert_match %r{<link href="/assets/application.css" media="screen" rel="stylesheet" type="text/css" />}, + stylesheet_link_tag(:application, :digest => false) assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, stylesheet_link_tag("style") @@ -187,22 +269,54 @@ class SprocketsHelperTest < ActionView::TestCase assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="print" rel="stylesheet" type="text/css" />}, stylesheet_link_tag("style", :media => "print") + assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/extra-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, + stylesheet_link_tag("style", "extra") + assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />}, stylesheet_link_tag(:application, :debug => true) - assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/extra-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag("style", "extra") + @config.assets.compile = true + @config.assets.debug = true + assert_match %r{<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />}, + stylesheet_link_tag('/stylesheets/application') + + assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />}, + stylesheet_link_tag(:application) + + assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="print" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="print" rel="stylesheet" type="text/css" />}, + stylesheet_link_tag(:application, :media => "print") end test "alternate asset prefix" do stubs(:asset_prefix).returns("/themes/test") - assert_match %r{/themes/test/style-[0-9a-f]+.css}, asset_path("style", "css") + assert_match %r{/themes/test/style-[0-9a-f]+.css}, asset_path("style", :ext => "css") end test "alternate asset environment" do assets = Sprockets::Environment.new assets.append_path(FIXTURES.join("sprockets/alternate/stylesheets")) stubs(:asset_environment).returns(assets) - assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", "css") + assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", :ext => "css") + end + + test "alternate hash based on environment" do + assets = Sprockets::Environment.new + assets.version = 'development' + assets.append_path(FIXTURES.join("sprockets/alternate/stylesheets")) + stubs(:asset_environment).returns(assets) + dev_path = asset_path("style", :ext => "css") + + assets.version = 'production' + prod_path = asset_path("style", :ext => "css") + + assert_not_equal prod_path, dev_path + end + + test "precedence of `config.digest = false` over manifest.yml asset digests" do + Rails.application.config.assets.digests = {'logo.png' => 'logo-d1g3st.png'} + @config.assets.digest = false + + assert_equal '/assets/logo.png', + asset_path("logo.png") end end diff --git a/actionpack/test/template/streaming_render_test.rb b/actionpack/test/template/streaming_render_test.rb index 023ce723ed..4d01352b43 100644 --- a/actionpack/test/template/streaming_render_test.rb +++ b/actionpack/test/template/streaming_render_test.rb @@ -28,7 +28,7 @@ class FiberedTest < ActiveSupport::TestCase def test_streaming_works content = [] - body = render_body(:template => "test/hello_world.erb", :layout => "layouts/yield") + body = render_body(:template => "test/hello_world", :layout => "layouts/yield") body.each do |piece| content << piece @@ -42,12 +42,12 @@ class FiberedTest < ActiveSupport::TestCase end def test_render_file - assert_equal "Hello world!", buffered_render(:file => "test/hello_world.erb") + assert_equal "Hello world!", buffered_render(:file => "test/hello_world") end def test_render_file_with_locals locals = { :secret => 'in the sauce' } - assert_equal "The secret is in the sauce\n", buffered_render(:file => "test/render_file_with_locals.erb", :locals => locals) + assert_equal "The secret is in the sauce\n", buffered_render(:file => "test/render_file_with_locals", :locals => locals) end def test_render_partial @@ -64,27 +64,27 @@ class FiberedTest < ActiveSupport::TestCase def test_render_with_layout assert_equal %(<title></title>\nHello world!\n), - buffered_render(:template => "test/hello_world.erb", :layout => "layouts/yield") + buffered_render(:template => "test/hello_world", :layout => "layouts/yield") end def test_render_with_layout_which_has_render_inline assert_equal %(welcome\nHello world!\n), - buffered_render(:template => "test/hello_world.erb", :layout => "layouts/yield_with_render_inline_inside") + buffered_render(:template => "test/hello_world", :layout => "layouts/yield_with_render_inline_inside") end def test_render_with_layout_which_renders_another_partial assert_equal %(partial html\nHello world!\n), - buffered_render(:template => "test/hello_world.erb", :layout => "layouts/yield_with_render_partial_inside") + buffered_render(:template => "test/hello_world", :layout => "layouts/yield_with_render_partial_inside") end def test_render_with_nested_layout assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n), - buffered_render(:template => "test/nested_layout.erb", :layout => "layouts/yield") + buffered_render(:template => "test/nested_layout", :layout => "layouts/yield") end def test_render_with_file_in_layout assert_equal %(\n<title>title</title>\n\n), - buffered_render(:template => "test/layout_render_file.erb") + buffered_render(:template => "test/layout_render_file") end def test_render_with_handler_without_streaming_support diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb index 60b466a9ff..6c325d5abb 100644 --- a/actionpack/test/template/tag_helper_test.rb +++ b/actionpack/test/template/tag_helper_test.rb @@ -1,6 +1,8 @@ require 'abstract_unit' class TagHelperTest < ActionView::TestCase + include RenderERBUtils + tests ActionView::Helpers::TagHelper def test_tag @@ -44,12 +46,12 @@ class TagHelperTest < ActionView::TestCase end def test_content_tag_with_block_in_erb - buffer = content_tag(:div) { concat "Hello world!" } + buffer = render_erb("<%= content_tag(:div) do %>Hello world!<% end %>") assert_dom_equal "<div>Hello world!</div>", buffer end def test_content_tag_with_block_and_options_in_erb - buffer = content_tag(:div, :class => "green") { concat "Hello world!" } + buffer = render_erb("<%= content_tag(:div, :class => 'green') do %>Hello world!<% end %>") assert_dom_equal %(<div class="green">Hello world!</div>), buffer end @@ -68,10 +70,8 @@ class TagHelperTest < ActionView::TestCase output_buffer end - # TAG TODO: Move this into a real template def test_content_tag_nested_in_content_tag_in_erb - buffer = content_tag("p") { concat content_tag("b", "Hello") } - assert_equal '<p><b>Hello</b></p>', buffer + assert_equal "<p>\n <b>Hello</b>\n</p>", view.render("test/content_tag_nested_in_content_tag") end def test_content_tag_with_escaped_array_class diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb index b0ca7de0b6..70ca876c67 100644 --- a/actionpack/test/template/template_test.rb +++ b/actionpack/test/template/template_test.rb @@ -8,6 +8,9 @@ class TestERBTemplate < ActiveSupport::TestCase def disable_cache yield end + + def find_template(*args) + end end class Context diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb index bf789cd8b7..adcbf1447f 100644 --- a/actionpack/test/template/test_test.rb +++ b/actionpack/test/template/test_test.rb @@ -62,3 +62,19 @@ class CrazyHelperTest < ActionView::TestCase assert_equal PeopleHelper, self.class.helper_class end end + +class CrazySymbolHelperTest < ActionView::TestCase + tests :people + + def test_set_helper_class_using_symbol + assert_equal PeopleHelper, self.class.helper_class + end +end + +class CrazyStringHelperTest < ActionView::TestCase + tests 'people' + + def test_set_helper_class_using_string + assert_equal PeopleHelper, self.class.helper_class + end +end diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index f7c3986bb1..a0afb77f05 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -48,10 +48,10 @@ class TextHelperTest < ActionView::TestCase assert_equal "<p><b> test with unsafe string </b><script>code!</script></p>", simple_format("<b> test with unsafe string </b><script>code!</script>", {}, :sanitize => false) end - def test_simple_format_should_not_change_the_frozen_text_passed + def test_simple_format_should_not_change_the_text_passed text = "<b>Ok</b><script>code!</script>" text_clone = text.dup - simple_format(text.freeze) + simple_format(text) assert_equal text_clone, text end @@ -194,6 +194,10 @@ class TextHelperTest < ActionView::TestCase "<p>This is a <strong class=\"highlight\">beautiful</strong> <a href=\"http://example.com/beautiful#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a <strong class=\"highlight\">beautiful</strong> day</p>", highlight("<p>This is a beautiful <a href=\"http://example.com/beautiful\#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a beautiful day</p>", "beautiful") ) + assert_equal( + "<div>abc <b>div</b></div>", + highlight("<div>abc div</div>", "div", :highlighter => '<b>\1</b>') + ) end def test_excerpt diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb index cd9f54e04c..397de9c2ce 100644 --- a/actionpack/test/template/translation_helper_test.rb +++ b/actionpack/test/template/translation_helper_test.rb @@ -17,8 +17,13 @@ class TranslationHelperTest < ActiveSupport::TestCase :hello => '<a>Hello World</a>', :html => '<a>Hello World</a>', :hello_html => '<a>Hello World</a>', + :interpolated_html => '<a>Hello %{word}</a>', :array_html => %w(foo bar), - :array => %w(foo bar) + :array => %w(foo bar), + :count_html => { + :one => '<a>One %{count}</a>', + :other => '<a>Other %{count}</a>' + } } ) @view = ::ActionView::Base.new(ActionController::Base.view_paths, {}) @@ -83,6 +88,17 @@ class TranslationHelperTest < ActiveSupport::TestCase assert translate(:'translations.hello_html').html_safe? end + def test_translate_escapes_interpolations_in_translations_with_a_html_suffix + assert_equal '<a>Hello <World></a>', translate(:'translations.interpolated_html', :word => '<World>') + assert_equal '<a>Hello <World></a>', translate(:'translations.interpolated_html', :word => stub(:to_s => "<World>")) + end + + def test_translate_with_html_count + assert_equal '<a>One 1</a>', translate(:'translations.count_html', :count => 1) + assert_equal '<a>Other 2</a>', translate(:'translations.count_html', :count => 2) + assert_equal '<a>Other <One></a>', translate(:'translations.count_html', :count => '<One>') + end + def test_translation_returning_an_array_ignores_html_suffix assert_equal ["foo", "bar"], translate(:'translations.array_html') end diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 78245c1f95..bc45fabf34 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -88,6 +88,10 @@ class UrlHelperTest < ActiveSupport::TestCase ) end + def test_button_to_with_remote_and_form_options + assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"custom-class\" data-remote=\"true\" data-type=\"json\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :remote => true, :form => { :class => "custom-class", "data-type" => "json" } ) + end + def test_button_to_with_remote_and_javascript_confirm assert_dom_equal( "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>", @@ -304,8 +308,8 @@ class UrlHelperTest < ActiveSupport::TestCase assert_equal "Showing", link_to_if(false, "Showing", url_hash) end - def request_for_url(url) - env = Rack::MockRequest.env_for("http://www.example.com#{url}") + def request_for_url(url, opts = {}) + env = Rack::MockRequest.env_for("http://www.example.com#{url}", opts) ActionDispatch::Request.new(env) end @@ -329,6 +333,12 @@ class UrlHelperTest < ActiveSupport::TestCase assert current_page?("http://www.example.com/?order=desc&page=1") end + def test_current_page_with_not_get_verb + @request = request_for_url("/events", :method => :post) + + assert !current_page?('/events') + end + def test_link_unless_current @request = request_for_url("/") |