unfreeze rails 2.3.9

This commit is contained in:
Reinier Balt 2011-02-04 16:35:00 +01:00
parent 6443adac78
commit dea6dbe4da
1916 changed files with 0 additions and 240923 deletions

View file

@ -1,545 +0,0 @@
require 'abstract_unit'
# a controller class to facilitate the tests
class ActionPackAssertionsController < ActionController::Base
# this does absolutely nothing
def nothing() head :ok end
# a standard template
def hello_world() render :template => "test/hello_world"; end
# a standard template
def hello_xml_world() render :template => "test/hello_xml_world"; end
# a standard partial
def partial() render :partial => 'test/partial'; end
# a redirect to an internal location
def redirect_internal() redirect_to "/nothing"; end
def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end
def redirect_to_controller() redirect_to :controller => "elsewhere", :action => "flash_me"; end
def redirect_to_controller_with_symbol() redirect_to :controller => :elsewhere, :action => :flash_me; end
def redirect_to_path() redirect_to '/some/path' end
def redirect_to_named_route() redirect_to route_one_url end
# a redirect to an external location
def redirect_external() redirect_to "http://www.rubyonrails.org"; end
# a 404
def response404() head '404 AWOL' end
# a 500
def response500() head '500 Sorry' end
# a fictional 599
def response599() head '599 Whoah!' end
# putting stuff in the flash
def flash_me
flash['hello'] = 'my name is inigo montoya...'
render :text => "Inconceivable!"
end
# we have a flash, but nothing is in it
def flash_me_naked
flash.clear
render :text => "wow!"
end
# assign some template instance variables
def assign_this
@howdy = "ho"
render :inline => "Mr. Henke"
end
def render_based_on_parameters
render :text => "Mr. #{params[:name]}"
end
def render_url
render :text => "<div>#{url_for(:action => 'flash_me', :only_path => true)}</div>"
end
def render_text_with_custom_content_type
render :text => "Hello!", :content_type => Mime::RSS
end
# puts something in the session
def session_stuffing
session['xmas'] = 'turkey'
render :text => "ho ho ho"
end
# raises exception on get requests
def raise_on_get
raise "get" if request.get?
render :text => "request method: #{request.env['REQUEST_METHOD']}"
end
# raises exception on post requests
def raise_on_post
raise "post" if request.post?
render :text => "request method: #{request.env['REQUEST_METHOD']}"
end
def get_valid_record
@record = Class.new do
def valid?
true
end
def errors
Class.new do
def full_messages; []; end
end.new
end
end.new
render :nothing => true
end
def get_invalid_record
@record = Class.new do
def valid?
false
end
def errors
Class.new do
def full_messages; ['...stuff...']; end
end.new
end
end.new
render :nothing => true
end
# 911
def rescue_action(e) raise; end
end
# Used to test that assert_response includes the exception message
# in the failure message when an action raises and assert_response
# is expecting something other than an error.
class AssertResponseWithUnexpectedErrorController < ActionController::Base
def index
raise 'FAIL'
end
def show
render :text => "Boom", :status => 500
end
end
class UserController < ActionController::Base
end
module Admin
class InnerModuleController < ActionController::Base
def index
render :nothing => true
end
def redirect_to_index
redirect_to admin_inner_module_path
end
def redirect_to_absolute_controller
redirect_to :controller => '/content'
end
def redirect_to_fellow_controller
redirect_to :controller => 'user'
end
def redirect_to_top_level_named_route
redirect_to top_level_url(:id => "foo")
end
end
end
# a test case to exercise the new capabilities TestRequest & TestResponse
class ActionPackAssertionsControllerTest < ActionController::TestCase
# let's get this party started
def setup
ActionController::Routing::Routes.reload
ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module user content admin/user))
end
def teardown
ActionController::Routing::Routes.reload
end
# -- assertion-based testing ------------------------------------------------
def test_assert_tag_and_url_for
get :render_url
assert_tag :content => "/action_pack_assertions/flash_me"
end
# test the get method, make sure the request really was a get
def test_get
assert_raise(RuntimeError) { get :raise_on_get }
get :raise_on_post
assert_equal @response.body, 'request method: GET'
end
# test the get method, make sure the request really was a get
def test_post
assert_raise(RuntimeError) { post :raise_on_post }
post :raise_on_get
assert_equal @response.body, 'request method: POST'
end
# the following test fails because the request_method is now cached on the request instance
# test the get/post switch within one test action
# def test_get_post_switch
# post :raise_on_get
# assert_equal @response.body, 'request method: POST'
# get :raise_on_post
# assert_equal @response.body, 'request method: GET'
# post :raise_on_get
# assert_equal @response.body, 'request method: POST'
# get :raise_on_post
# assert_equal @response.body, 'request method: GET'
# end
# test the redirection to a named route
def test_assert_redirect_to_named_route
with_routing do |set|
set.draw do |map|
map.route_one 'route_one', :controller => 'action_pack_assertions', :action => 'nothing'
map.connect ':controller/:action/:id'
end
set.install_helpers
process :redirect_to_named_route
assert_redirected_to 'http://test.host/route_one'
assert_redirected_to route_one_url
end
end
def test_assert_redirect_to_named_route_failure
with_routing do |set|
set.draw do |map|
map.route_one 'route_one', :controller => 'action_pack_assertions', :action => 'nothing', :id => 'one'
map.route_two 'route_two', :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two'
map.connect ':controller/:action/:id'
end
process :redirect_to_named_route
assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to 'http://test.host/route_two'
end
assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two'
end
assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to route_two_url
end
end
end
def test_assert_redirect_to_nested_named_route
with_routing do |set|
set.draw do |map|
map.admin_inner_module 'admin/inner_module', :controller => 'admin/inner_module', :action => 'index'
map.connect ':controller/:action/:id'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_index
# redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}>
assert_redirected_to admin_inner_module_path
end
end
def test_assert_redirected_to_top_level_named_route_from_nested_controller
with_routing do |set|
set.draw do |map|
map.top_level '/action_pack_assertions/:id', :controller => 'action_pack_assertions', :action => 'index'
map.connect ':controller/:action/:id'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_top_level_named_route
# assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return
assert_redirected_to "/action_pack_assertions/foo"
end
end
def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces
with_routing do |set|
set.draw do |map|
# this controller exists in the admin namespace as well which is the only difference from previous test
map.top_level '/user/:id', :controller => 'user', :action => 'index'
map.connect ':controller/:action/:id'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_top_level_named_route
# assert_redirected_to top_level_url('foo') would pass because of exact match early return
assert_redirected_to top_level_path('foo')
end
end
# -- standard request/response object testing --------------------------------
# make sure that the template objects exist
def test_template_objects_alive
process :assign_this
assert !@response.has_template_object?('hi')
assert @response.has_template_object?('howdy')
end
# make sure we don't have template objects when we shouldn't
def test_template_object_missing
process :nothing
assert_nil @response.template_objects['howdy']
end
# check the empty flashing
def test_flash_me_naked
process :flash_me_naked
assert !@response.has_flash?
assert !@response.has_flash_with_contents?
end
# check if we have flash objects
def test_flash_haves
process :flash_me
assert @response.has_flash?
assert @response.has_flash_with_contents?
assert @response.has_flash_object?('hello')
end
# ensure we don't have flash objects
def test_flash_have_nots
process :nothing
assert !@response.has_flash?
assert !@response.has_flash_with_contents?
assert_nil @response.flash['hello']
end
# check if we were rendered by a file-based template?
def test_rendered_action
process :nothing
assert_nil @response.rendered[:template]
process :hello_world
assert @response.rendered[:template]
assert 'hello_world', @response.rendered[:template].to_s
end
def test_assert_template_with_partial
get :partial
assert_template :partial => '_partial'
end
def test_assert_template_with_nil
get :nothing
assert_template nil
end
def test_assert_template_with_string
get :hello_world
assert_template 'hello_world'
end
def test_assert_template_with_symbol
get :hello_world
assert_template :hello_world
end
def test_assert_template_with_bad_argument
assert_raise(ArgumentError) { assert_template 1 }
end
# check the redirection location
def test_redirection_location
process :redirect_internal
assert_equal 'http://test.host/nothing', @response.redirect_url
process :redirect_external
assert_equal 'http://www.rubyonrails.org', @response.redirect_url
end
def test_no_redirect_url
process :nothing
assert_nil @response.redirect_url
end
# check server errors
def test_server_error_response_code
process :response500
assert @response.server_error?
process :response599
assert @response.server_error?
process :response404
assert !@response.server_error?
end
# check a 404 response code
def test_missing_response_code
process :response404
assert @response.missing?
end
# check client errors
def test_client_error_response_code
process :response404
assert @response.client_error?
end
# check to see if our redirection matches a pattern
def test_redirect_url_match
process :redirect_external
assert @response.redirect?
assert @response.redirect_url_match?("rubyonrails")
assert @response.redirect_url_match?(/rubyonrails/)
assert !@response.redirect_url_match?("phpoffrails")
assert !@response.redirect_url_match?(/perloffrails/)
end
# check for a redirection
def test_redirection
process :redirect_internal
assert @response.redirect?
process :redirect_external
assert @response.redirect?
process :nothing
assert !@response.redirect?
end
# check a successful response code
def test_successful_response_code
process :nothing
assert @response.success?
end
# a basic check to make sure we have a TestResponse object
def test_has_response
process :nothing
assert_kind_of ActionController::TestResponse, @response
end
def test_render_based_on_parameters
process :render_based_on_parameters, "name" => "David"
assert_equal "Mr. David", @response.body
end
def test_assert_redirection_fails_with_incorrect_controller
process :redirect_to_controller
assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to :controller => "action_pack_assertions", :action => "flash_me"
end
end
def test_assert_redirection_with_extra_controller_option
get :redirect_to_action
assert_redirected_to :controller => 'action_pack_assertions', :action => "flash_me", :id => 1, :params => { :panda => 'fun' }
end
def test_redirected_to_url_leading_slash
process :redirect_to_path
assert_redirected_to '/some/path'
end
def test_redirected_to_url_no_leadling_slash
process :redirect_to_path
assert_deprecated /leading/ do
assert_redirected_to 'some/path'
end
end
def test_redirected_to_url_full_url
process :redirect_to_path
assert_redirected_to 'http://test.host/some/path'
end
def test_assert_redirection_with_symbol
process :redirect_to_controller_with_symbol
assert_nothing_raised {
assert_redirected_to :controller => "elsewhere", :action => "flash_me"
}
process :redirect_to_controller_with_symbol
assert_nothing_raised {
assert_redirected_to :controller => :elsewhere, :action => :flash_me
}
end
def test_redirected_to_with_nested_controller
@controller = Admin::InnerModuleController.new
get :redirect_to_absolute_controller
assert_redirected_to :controller => '/content'
get :redirect_to_fellow_controller
assert_redirected_to :controller => 'admin/user'
end
def test_assert_valid
get :get_valid_record
assert_deprecated { assert_valid assigns('record') }
end
def test_assert_valid_failing
get :get_invalid_record
begin
assert_deprecated { assert_valid assigns('record') }
assert false
rescue ActiveSupport::TestCase::Assertion => e
end
end
def test_assert_response_uses_exception_message
@controller = AssertResponseWithUnexpectedErrorController.new
get :index
assert_response :success
flunk 'Expected non-success response'
rescue ActiveSupport::TestCase::Assertion => e
assert e.message.include?('FAIL')
end
def test_assert_response_failure_response_with_no_exception
@controller = AssertResponseWithUnexpectedErrorController.new
get :show
assert_response :success
flunk 'Expected non-success response'
rescue ActiveSupport::TestCase::Assertion
# success
rescue
flunk "assert_response failed to handle failure response with missing, but optional, exception."
end
end
class ActionPackHeaderTest < ActionController::TestCase
tests ActionPackAssertionsController
def test_rendering_xml_sets_content_type
process :hello_xml_world
assert_equal('application/xml; charset=utf-8', @response.headers['Content-Type'])
end
def test_rendering_xml_respects_content_type
@response.headers['type'] = 'application/pdf'
process :hello_xml_world
assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type'])
end
def test_render_text_with_custom_content_type
get :render_text_with_custom_content_type
assert_equal 'application/rss+xml; charset=utf-8', @response.headers['Content-Type']
end
end

View file

@ -1,37 +0,0 @@
require 'abstract_unit'
class Address
def Address.count(conditions = nil, join = nil)
nil
end
def Address.find_all(arg1, arg2, arg3, arg4)
[]
end
def self.find(*args)
[]
end
end
class AddressesTestController < ActionController::Base
def self.controller_name; "addresses"; end
def self.controller_path; "addresses"; end
end
class AddressesTest < ActionController::TestCase
tests AddressesTestController
def setup
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
@controller.logger = Logger.new(nil)
@request.host = "www.nextangle.com"
end
def test_list
get :list
assert_equal "We only need to get this far!", @response.body.chomp
end
end

View file

@ -1,735 +0,0 @@
# encoding: us-ascii
#--
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
# Under MIT and/or CC By license.
#++
require 'abstract_unit'
require 'controller/fake_controllers'
unless defined?(ActionMailer)
begin
$:.unshift("#{File.dirname(__FILE__)}/../../../actionmailer/lib")
require 'action_mailer'
rescue LoadError => e
raise unless e.message =~ /action_mailer/
require 'rubygems'
gem 'actionmailer'
end
end
ActionMailer::Base.template_root = FIXTURE_LOAD_PATH
class AssertSelectTest < ActionController::TestCase
Assertion = ActiveSupport::TestCase::Assertion
class AssertSelectMailer < ActionMailer::Base
def test(html)
recipients "test <test@test.host>"
from "test@test.host"
subject "Test e-mail"
part :content_type=>"text/html", :body=>html
end
end
class AssertSelectController < ActionController::Base
def response_with=(content)
@content = content
end
def response_with(&block)
@update = block
end
def html()
render :text=>@content, :layout=>false, :content_type=>Mime::HTML
@content = nil
end
def rjs()
render :update do |page|
@update.call page
end
@update = nil
end
def xml()
render :text=>@content, :layout=>false, :content_type=>Mime::XML
@content = nil
end
def rescue_action(e)
raise e
end
end
tests AssertSelectController
def setup
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
end
def teardown
ActionMailer::Base.deliveries.clear
end
def assert_failure(message, &block)
e = assert_raise(Assertion, &block)
assert_match(message, e.message) if Regexp === message
assert_equal(message, e.message) if String === message
end
#
# Test assert select.
#
def test_assert_select
render_html %Q{<div id="1"></div><div id="2"></div>}
assert_select "div", 2
assert_failure(/Expected at least 3 elements matching \"div\", found 2/) { assert_select "div", 3 }
assert_failure(/Expected at least 1 element matching \"p\", found 0/) { assert_select "p" }
end
def test_equality_true_false
render_html %Q{<div id="1"></div><div id="2"></div>}
assert_nothing_raised { assert_select "div" }
assert_raise(Assertion) { assert_select "p" }
assert_nothing_raised { assert_select "div", true }
assert_raise(Assertion) { assert_select "p", true }
assert_raise(Assertion) { assert_select "div", false }
assert_nothing_raised { assert_select "p", false }
end
def test_equality_string_and_regexp
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
assert_nothing_raised { assert_select "div", "foo" }
assert_raise(Assertion) { assert_select "div", "bar" }
assert_nothing_raised { assert_select "div", :text=>"foo" }
assert_raise(Assertion) { assert_select "div", :text=>"bar" }
assert_nothing_raised { assert_select "div", /(foo|bar)/ }
assert_raise(Assertion) { assert_select "div", /foobar/ }
assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ }
assert_raise(Assertion) { assert_select "div", :text=>/foobar/ }
assert_raise(Assertion) { assert_select "p", :text=>/foobar/ }
end
def test_equality_of_html
render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>}
text = "\"This is not a big problem,\" he said."
html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said."
assert_nothing_raised { assert_select "p", text }
assert_raise(Assertion) { assert_select "p", html }
assert_nothing_raised { assert_select "p", :html=>html }
assert_raise(Assertion) { assert_select "p", :html=>text }
# No stripping for pre.
render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>}
text = "\n\"This is not a big problem,\" he said.\n"
html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n"
assert_nothing_raised { assert_select "pre", text }
assert_raise(Assertion) { assert_select "pre", html }
assert_nothing_raised { assert_select "pre", :html=>html }
assert_raise(Assertion) { assert_select "pre", :html=>text }
end
def test_counts
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
assert_nothing_raised { assert_select "div", 2 }
assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do
assert_select "div", 3
end
assert_nothing_raised { assert_select "div", 1..2 }
assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do
assert_select "div", 3..4
end
assert_nothing_raised { assert_select "div", :count=>2 }
assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do
assert_select "div", :count=>3
end
assert_nothing_raised { assert_select "div", :minimum=>1 }
assert_nothing_raised { assert_select "div", :minimum=>2 }
assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do
assert_select "div", :minimum=>3
end
assert_nothing_raised { assert_select "div", :maximum=>2 }
assert_nothing_raised { assert_select "div", :maximum=>3 }
assert_failure(/Expected at most 1 element matching \"div\", found 2/) do
assert_select "div", :maximum=>1
end
assert_nothing_raised { assert_select "div", :minimum=>1, :maximum=>2 }
assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do
assert_select "div", :minimum=>3, :maximum=>4
end
end
def test_substitution_values
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
assert_select "div#?", /\d+/ do |elements|
assert_equal 2, elements.size
end
assert_select "div" do
assert_select "div#?", /\d+/ do |elements|
assert_equal 2, elements.size
assert_select "#1"
assert_select "#2"
end
end
end
def test_nested_assert_select
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
assert_select "div" do |elements|
assert_equal 2, elements.size
assert_select elements[0], "#1"
assert_select elements[1], "#2"
end
assert_select "div" do
assert_select "div" do |elements|
assert_equal 2, elements.size
# Testing in a group is one thing
assert_select "#1,#2"
# Testing individually is another.
assert_select "#1"
assert_select "#2"
assert_select "#3", false
end
end
assert_failure(/Expected at least 1 element matching \"#4\", found 0\./) do
assert_select "div" do
assert_select "#4"
end
end
end
def test_assert_select_text_match
render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>}
assert_select "div" do
assert_nothing_raised { assert_select "div", "foo" }
assert_nothing_raised { assert_select "div", "bar" }
assert_nothing_raised { assert_select "div", /\w*/ }
assert_nothing_raised { assert_select "div", :text => /\w*/, :count=>2 }
assert_raise(Assertion) { assert_select "div", :text=>"foo", :count=>2 }
assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
assert_nothing_raised { assert_select "div", :html=>/\w*/ }
assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 }
assert_raise(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 }
end
end
# With single result.
def test_assert_select_from_rjs_with_single_result
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
end
assert_select "div" do |elements|
assert elements.size == 2
assert_select "#1"
assert_select "#2"
end
assert_select "div#?", /\d+/ do |elements|
assert_select "#1"
assert_select "#2"
end
end
# With multiple results.
def test_assert_select_from_rjs_with_multiple_results
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
end
assert_select "div" do |elements|
assert elements.size == 2
assert_select "#1"
assert_select "#2"
end
end
def test_assert_select_rjs_for_positioned_insert_should_fail_when_mixing_arguments
render_rjs do |page|
page.insert_html :top, "test1", "<div id=\"1\">foo</div>"
page.insert_html :bottom, "test2", "<div id=\"2\">foo</div>"
end
assert_raise(Assertion) {assert_select_rjs :insert, :top, "test2"}
end
def test_elect_with_xml_namespace_attributes
render_html %Q{<link xlink:href="http://nowhere.com"></link>}
assert_nothing_raised { assert_select "link[xlink:href=http://nowhere.com]" }
end
#
# Test css_select.
#
def test_css_select
render_html %Q{<div id="1"></div><div id="2"></div>}
assert_equal 2, css_select("div").size
assert_equal 0, css_select("p").size
end
def test_nested_css_select
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
assert_select "div#?", /\d+/ do |elements|
assert_equal 1, css_select(elements[0], "div").size
assert_equal 1, css_select(elements[1], "div").size
end
assert_select "div" do
assert_equal 2, css_select("div").size
css_select("div").each do |element|
# Testing as a group is one thing
assert !css_select("#1,#2").empty?
# Testing individually is another
assert !css_select("#1").empty?
assert !css_select("#2").empty?
end
end
end
# With one result.
def test_css_select_from_rjs_with_single_result
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
end
assert_equal 2, css_select("div").size
assert_equal 1, css_select("#1").size
assert_equal 1, css_select("#2").size
end
# With multiple results.
def test_css_select_from_rjs_with_multiple_results
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
end
assert_equal 2, css_select("div").size
assert_equal 1, css_select("#1").size
assert_equal 1, css_select("#2").size
end
#
# Test assert_select_rjs.
#
# Test that we can pick up all statements in the result.
def test_assert_select_rjs_picks_up_all_statements
render_rjs do |page|
page.replace "test", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
page.insert_html :top, "test3", "<div id=\"3\">foo</div>"
end
found = false
assert_select_rjs do
assert_select "#1"
assert_select "#2"
assert_select "#3"
found = true
end
assert found
end
# Test that we fail if there is nothing to pick.
def test_assert_select_rjs_fails_if_nothing_to_pick
render_rjs { }
assert_raise(Assertion) { assert_select_rjs }
end
def test_assert_select_rjs_with_unicode
# Test that non-ascii characters (which are converted into \uXXXX in RJS) are decoded correctly.
render_rjs do |page|
page.replace "test", "<div id=\"1\">\343\203\201\343\202\261\343\203\203\343\203\210</div>"
end
assert_select_rjs do
str = "#1"
assert_select str, :text => "\343\203\201\343\202\261\343\203\203\343\203\210"
assert_select str, "\343\203\201\343\202\261\343\203\203\343\203\210"
if str.respond_to?(:force_encoding)
str.force_encoding(Encoding::UTF_8)
assert_select str, /\343\203\201..\343\203\210/u
assert_raise(Assertion) { assert_select str, /\343\203\201.\343\203\210/u }
else
assert_select str, Regexp.new("\343\203\201..\343\203\210",0,'U')
assert_raise(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') }
end
end
end
def test_assert_select_rjs_with_id
# Test that we can pick up all statements in the result.
render_rjs do |page|
page.replace "test1", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
page.insert_html :top, "test3", "<div id=\"3\">foo</div>"
end
assert_select_rjs "test1" do
assert_select "div", 1
assert_select "#1"
end
assert_select_rjs "test2" do
assert_select "div", 1
assert_select "#2"
end
assert_select_rjs "test3" do
assert_select "div", 1
assert_select "#3"
end
assert_raise(Assertion) { assert_select_rjs "test4" }
end
def test_assert_select_rjs_for_replace
render_rjs do |page|
page.replace "test1", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
page.insert_html :top, "test3", "<div id=\"3\">foo</div>"
end
# Replace.
assert_select_rjs :replace do
assert_select "div", 1
assert_select "#1"
end
assert_select_rjs :replace, "test1" do
assert_select "div", 1
assert_select "#1"
end
assert_raise(Assertion) { assert_select_rjs :replace, "test2" }
# Replace HTML.
assert_select_rjs :replace_html do
assert_select "div", 1
assert_select "#2"
end
assert_select_rjs :replace_html, "test2" do
assert_select "div", 1
assert_select "#2"
end
assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" }
end
def test_assert_select_rjs_for_chained_replace
render_rjs do |page|
page['test1'].replace "<div id=\"1\">foo</div>"
page['test2'].replace_html "<div id=\"2\">foo</div>"
page.insert_html :top, "test3", "<div id=\"3\">foo</div>"
end
# Replace.
assert_select_rjs :chained_replace do
assert_select "div", 1
assert_select "#1"
end
assert_select_rjs :chained_replace, "test1" do
assert_select "div", 1
assert_select "#1"
end
assert_raise(Assertion) { assert_select_rjs :chained_replace, "test2" }
# Replace HTML.
assert_select_rjs :chained_replace_html do
assert_select "div", 1
assert_select "#2"
end
assert_select_rjs :chained_replace_html, "test2" do
assert_select "div", 1
assert_select "#2"
end
assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" }
end
# Simple remove
def test_assert_select_rjs_for_remove
render_rjs do |page|
page.remove "test1"
end
assert_select_rjs :remove, "test1"
end
def test_assert_select_rjs_for_remove_offers_useful_error_when_assertion_fails
render_rjs do |page|
page.remove "test_with_typo"
end
assert_select_rjs :remove, "test1"
rescue Assertion
assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_remove_ignores_block
render_rjs do |page|
page.remove "test1"
end
assert_nothing_raised do
assert_select_rjs :remove, "test1" do
assert_select "p"
end
end
end
# Simple show
def test_assert_select_rjs_for_show
render_rjs do |page|
page.show "test1"
end
assert_select_rjs :show, "test1"
end
def test_assert_select_rjs_for_show_offers_useful_error_when_assertion_fails
render_rjs do |page|
page.show "test_with_typo"
end
assert_select_rjs :show, "test1"
rescue Assertion
assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_show_ignores_block
render_rjs do |page|
page.show "test1"
end
assert_nothing_raised do
assert_select_rjs :show, "test1" do
assert_select "p"
end
end
end
# Simple hide
def test_assert_select_rjs_for_hide
render_rjs do |page|
page.hide "test1"
end
assert_select_rjs :hide, "test1"
end
def test_assert_select_rjs_for_hide_offers_useful_error_when_assertion_fails
render_rjs do |page|
page.hide "test_with_typo"
end
assert_select_rjs :hide, "test1"
rescue Assertion
assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_hide_ignores_block
render_rjs do |page|
page.hide "test1"
end
assert_nothing_raised do
assert_select_rjs :hide, "test1" do
assert_select "p"
end
end
end
# Simple toggle
def test_assert_select_rjs_for_toggle
render_rjs do |page|
page.toggle "test1"
end
assert_select_rjs :toggle, "test1"
end
def test_assert_select_rjs_for_toggle_offers_useful_error_when_assertion_fails
render_rjs do |page|
page.toggle "test_with_typo"
end
assert_select_rjs :toggle, "test1"
rescue Assertion
assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_toggle_ignores_block
render_rjs do |page|
page.toggle "test1"
end
assert_nothing_raised do
assert_select_rjs :toggle, "test1" do
assert_select "p"
end
end
end
# Non-positioned insert.
def test_assert_select_rjs_for_nonpositioned_insert
render_rjs do |page|
page.replace "test1", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
page.insert_html :top, "test3", "<div id=\"3\">foo</div>"
end
assert_select_rjs :insert_html do
assert_select "div", 1
assert_select "#3"
end
assert_select_rjs :insert_html, "test3" do
assert_select "div", 1
assert_select "#3"
end
assert_raise(Assertion) { assert_select_rjs :insert_html, "test1" }
end
# Positioned insert.
def test_assert_select_rjs_for_positioned_insert
render_rjs do |page|
page.insert_html :top, "test1", "<div id=\"1\">foo</div>"
page.insert_html :bottom, "test2", "<div id=\"2\">foo</div>"
page.insert_html :before, "test3", "<div id=\"3\">foo</div>"
page.insert_html :after, "test4", "<div id=\"4\">foo</div>"
end
assert_select_rjs :insert, :top do
assert_select "div", 1
assert_select "#1"
end
assert_select_rjs :insert, :bottom do
assert_select "div", 1
assert_select "#2"
end
assert_select_rjs :insert, :before do
assert_select "div", 1
assert_select "#3"
end
assert_select_rjs :insert, :after do
assert_select "div", 1
assert_select "#4"
end
assert_select_rjs :insert_html do
assert_select "div", 4
end
end
def test_assert_select_rjs_raise_errors
assert_raise(ArgumentError) { assert_select_rjs(:destroy) }
assert_raise(ArgumentError) { assert_select_rjs(:insert, :left) }
end
# Simple selection from a single result.
def test_nested_assert_select_rjs_with_single_result
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
end
assert_select_rjs "test" do |elements|
assert_equal 2, elements.size
assert_select "#1"
assert_select "#2"
end
end
# Deal with two results.
def test_nested_assert_select_rjs_with_two_results
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
end
assert_select_rjs "test" do |elements|
assert_equal 1, elements.size
assert_select "#1"
end
assert_select_rjs "test2" do |elements|
assert_equal 1, elements.size
assert_select "#2"
end
end
def test_feed_item_encoded
render_xml <<-EOF
<rss version="2.0">
<channel>
<item>
<description>
<![CDATA[
<p>Test 1</p>
]]>
</description>
</item>
<item>
<description>
<![CDATA[
<p>Test 2</p>
]]>
</description>
</item>
</channel>
</rss>
EOF
assert_select "channel item description" do
# Test element regardless of wrapper.
assert_select_encoded do
assert_select "p", :count=>2, :text=>/Test/
end
# Test through encoded wrapper.
assert_select_encoded do
assert_select "encoded p", :count=>2, :text=>/Test/
end
# Use :root instead (recommended)
assert_select_encoded do
assert_select ":root p", :count=>2, :text=>/Test/
end
# Test individually.
assert_select "description" do |elements|
assert_select_encoded elements[0] do
assert_select "p", "Test 1"
end
assert_select_encoded elements[1] do
assert_select "p", "Test 2"
end
end
end
# Test that we only un-encode element itself.
assert_select "channel item" do
assert_select_encoded do
assert_select "p", 0
end
end
end
#
# Test assert_select_email
#
def test_assert_select_email
assert_raise(Assertion) { assert_select_email {} }
AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>"
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
get :html
end
def render_rjs(&block)
@controller.response_with &block
get :rjs
end
def render_xml(xml)
@controller.response_with = xml
get :xml
end
end

View file

@ -1,217 +0,0 @@
require 'abstract_unit'
require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
# Provide some controller to run the tests on.
module Submodule
class ContainedEmptyController < ActionController::Base
end
class ContainedNonEmptyController < ActionController::Base
def public_action
render :nothing => true
end
hide_action :hidden_action
def hidden_action
raise "Noooo!"
end
def another_hidden_action
end
hide_action :another_hidden_action
end
class SubclassedController < ContainedNonEmptyController
hide_action :public_action # Hiding it here should not affect the superclass.
end
end
class EmptyController < ActionController::Base
end
class NonEmptyController < ActionController::Base
def public_action
end
hide_action :hidden_action
def hidden_action
end
end
class MethodMissingController < ActionController::Base
hide_action :shouldnt_be_called
def shouldnt_be_called
raise "NO WAY!"
end
protected
def method_missing(selector)
render :text => selector.to_s
end
end
class DefaultUrlOptionsController < ActionController::Base
def default_url_options_action
end
def default_url_options(options = nil)
{ :host => 'www.override.com', :action => 'new', :bacon => 'chunky' }
end
end
class ControllerClassTests < Test::Unit::TestCase
def test_controller_path
assert_equal 'empty', EmptyController.controller_path
assert_equal EmptyController.controller_path, EmptyController.new.controller_path
assert_equal 'submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path
end
def test_controller_name
assert_equal 'empty', EmptyController.controller_name
assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
end
end
class ControllerInstanceTests < Test::Unit::TestCase
def setup
@empty = EmptyController.new
@contained = Submodule::ContainedEmptyController.new
@empty_controllers = [@empty, @contained, Submodule::SubclassedController.new]
@non_empty_controllers = [NonEmptyController.new,
Submodule::ContainedNonEmptyController.new]
end
def test_action_methods
@empty_controllers.each do |c|
hide_mocha_methods_from_controller(c)
assert_equal Set.new, c.__send__(:action_methods), "#{c.controller_path} should be empty!"
end
@non_empty_controllers.each do |c|
hide_mocha_methods_from_controller(c)
assert_equal Set.new(%w(public_action)), c.__send__(:action_methods), "#{c.controller_path} should not be empty!"
end
end
protected
# Mocha adds some public instance methods to Object that would be
# considered actions, so explicitly hide_action them.
def hide_mocha_methods_from_controller(controller)
mocha_methods = [
:expects, :mocha, :mocha_inspect, :reset_mocha, :stubba_object,
:stubba_method, :stubs, :verify, :__metaclass__, :__is_a__, :to_matcher,
]
controller.class.__send__(:hide_action, *mocha_methods)
end
end
class PerformActionTest < ActionController::TestCase
class MockLogger
attr_reader :logged
def initialize
@logged = []
end
def method_missing(method, *args)
@logged << args.first
end
end
def use_controller(controller_class)
@controller = controller_class.new
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
@controller.logger = Logger.new(nil)
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.host = "www.nextangle.com"
rescue_action_in_public!
end
def test_get_on_priv_should_show_selector
use_controller MethodMissingController
get :shouldnt_be_called
assert_response :success
assert_equal 'shouldnt_be_called', @response.body
end
def test_method_missing_is_not_an_action_name
use_controller MethodMissingController
assert ! @controller.__send__(:action_methods).include?('method_missing')
get :method_missing
assert_response :success
assert_equal 'method_missing', @response.body
end
def test_get_on_hidden_should_fail
use_controller NonEmptyController
get :hidden_action
assert_response 404
get :another_hidden_action
assert_response 404
end
def test_namespaced_action_should_log_module_name
use_controller Submodule::ContainedNonEmptyController
@controller.logger = MockLogger.new
get :public_action
assert_match /Processing\sSubmodule::ContainedNonEmptyController#public_action/, @controller.logger.logged[1]
end
end
class DefaultUrlOptionsTest < ActionController::TestCase
tests DefaultUrlOptionsController
def setup
@request.host = 'www.example.com'
rescue_action_in_public!
end
def test_default_url_options_are_used_if_set
ActionController::Routing::Routes.draw do |map|
map.default_url_options 'default_url_options', :controller => 'default_url_options'
map.connect ':controller/:action/:id'
end
get :default_url_options_action # Make a dummy request so that the controller is initialized properly.
assert_equal 'http://www.override.com/default_url_options/new?bacon=chunky', @controller.url_for(:controller => 'default_url_options')
assert_equal 'http://www.override.com/default_url_options?bacon=chunky', @controller.send(:default_url_options_url)
ensure
ActionController::Routing::Routes.load!
end
end
class EmptyUrlOptionsTest < ActionController::TestCase
tests NonEmptyController
def setup
@request.host = 'www.example.com'
rescue_action_in_public!
end
def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set
get :public_action
assert_equal "http://www.example.com/non_empty/public_action", @controller.url_for
end
end
class EnsureNamedRoutesWorksTicket22BugTest < Test::Unit::TestCase
def test_named_routes_still_work
ActionController::Routing::Routes.draw do |map|
map.resources :things
end
EmptyController.send :include, ActionController::UrlWriter
assert_equal '/things', EmptyController.new.send(:things_path)
ensure
ActionController::Routing::Routes.load!
end
end

View file

@ -1,32 +0,0 @@
require 'abstract_unit'
# Provide some static controllers.
class BenchmarkedController < ActionController::Base
def public_action
render :nothing => true
end
def rescue_action(e)
raise e
end
end
class BenchmarkTest < ActionController::TestCase
tests BenchmarkedController
class MockLogger
def method_missing(*args)
end
end
def setup
# benchmark doesn't do anything unless a logger is set
@controller.logger = MockLogger.new
@request.host = "test.actioncontroller.i"
end
def test_with_http_1_0_request
@request.host = nil
assert_nothing_raised { get :public_action }
end
end

View file

@ -1,743 +0,0 @@
require 'fileutils'
require 'abstract_unit'
require 'active_record_unit'
CACHE_DIR = 'test_cache'
# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed
FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR)
ActionController::Base.page_cache_directory = FILE_STORE_PATH
ActionController::Base.cache_store = :file_store, FILE_STORE_PATH
# Force sweeper classes to load
ActionController::Caching::Sweeper
ActionController::Caching::Sweeping
class PageCachingTestController < ActionController::Base
caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? }
caches_page :found, :not_found
def ok
head :ok
end
def no_content
head :no_content
end
def found
redirect_to :action => 'ok'
end
def not_found
head :not_found
end
def custom_path
render :text => "Super soaker"
cache_page("Super soaker", "/index.html")
end
def expire_custom_path
expire_page("/index.html")
head :ok
end
def trailing_slash
render :text => "Sneak attack"
end
end
class PageCachingTest < ActionController::TestCase
def setup
ActionController::Base.perform_caching = true
ActionController::Routing::Routes.draw do |map|
map.main '', :controller => 'posts', :format => nil
map.formatted_posts 'posts.:format', :controller => 'posts'
map.resources :posts
map.connect ':controller/:action/:id'
end
@request = ActionController::TestRequest.new
@request.host = 'hostname.com'
@response = ActionController::TestResponse.new
@controller = PageCachingTestController.new
@params = {:controller => 'posts', :action => 'index', :only_path => true, :skip_relative_url_root => true}
@rewriter = ActionController::UrlRewriter.new(@request, @params)
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
FileUtils.mkdir_p(FILE_STORE_PATH)
end
def teardown
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
ActionController::Routing::Routes.clear!
ActionController::Base.perform_caching = false
end
def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_default_route
@params[:format] = 'rss'
assert_equal '/posts.rss', @rewriter.rewrite(@params)
@params[:format] = nil
assert_equal '/', @rewriter.rewrite(@params)
end
def test_should_cache_get_with_ok_status
get :ok
assert_response :ok
assert_page_cached :ok, "get with ok status should have been cached"
end
def test_should_cache_with_custom_path
get :custom_path
assert File.exist?("#{FILE_STORE_PATH}/index.html")
end
def test_should_expire_cache_with_custom_path
get :custom_path
assert File.exist?("#{FILE_STORE_PATH}/index.html")
get :expire_custom_path
assert !File.exist?("#{FILE_STORE_PATH}/index.html")
end
def test_should_cache_without_trailing_slash_on_url
@controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash'
assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html")
end
def test_should_cache_with_trailing_slash_on_url
@controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash/'
assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html")
end
def test_should_cache_ok_at_custom_path
@request.stubs(:path).returns("/index.html")
get :ok
assert_response :ok
assert File.exist?("#{FILE_STORE_PATH}/index.html")
end
[:ok, :no_content, :found, :not_found].each do |status|
[:get, :post, :put, :delete].each do |method|
unless method == :get and status == :ok
define_method "test_shouldnt_cache_#{method}_with_#{status}_status" do
send(method, status)
assert_response status
assert_page_not_cached status, "#{method} with #{status} status shouldn't have been cached"
end
end
end
end
def test_page_caching_conditional_options
get :ok, :format=>'json'
assert_page_not_cached :ok
end
private
def assert_page_cached(action, message = "#{action} should have been cached")
assert page_cached?(action), message
end
def assert_page_not_cached(action, message = "#{action} shouldn't have been cached")
assert !page_cached?(action), message
end
def page_cached?(action)
File.exist? "#{FILE_STORE_PATH}/page_caching_test/#{action}.html"
end
end
class ActionCachingTestController < ActionController::Base
caches_action :index, :redirected, :forbidden, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour
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 :layout_false, :layout => false
caches_action :record_not_found, :four_oh_four, :simple_runtime_error
layout 'talk_from_action.erb'
def index
@cache_this = MockTime.now.to_f.to_s
render :text => @cache_this
end
def redirected
redirect_to :action => 'index'
end
def forbidden
render :text => "Forbidden"
response.status = "403 Forbidden"
end
def with_layout
@cache_this = MockTime.now.to_f.to_s
render :text => @cache_this, :layout => true
end
def record_not_found
raise ActiveRecord::RecordNotFound, "oops!"
end
def four_oh_four
render :text => "404'd!", :status => 404
end
def simple_runtime_error
raise "oops!"
end
alias_method :show, :index
alias_method :edit, :index
alias_method :destroy, :index
alias_method :layout_false, :with_layout
def expire
expire_action :controller => 'action_caching_test', :action => 'index'
render :nothing => true
end
def expire_xml
expire_action :controller => 'action_caching_test', :action => 'index', :format => 'xml'
render :nothing => true
end
end
class MockTime < Time
# Let Time spicy to assure that Time.now != Time.now
def to_f
super+rand
end
end
class ActionCachingMockController
attr_accessor :mock_url_for
attr_accessor :mock_path
def initialize
yield self if block_given?
end
def url_for(*args)
@mock_url_for
end
def request
mocked_path = @mock_path
Object.new.instance_eval(<<-EVAL)
def path; '#{@mock_path}' end
def format; 'all' end
def cache_format; nil end
self
EVAL
end
end
class ActionCacheTest < ActionController::TestCase
def setup
reset!
FileUtils.mkdir_p(FILE_STORE_PATH)
@path_class = ActionController::Caching::Actions::ActionCachePath
@mock_controller = ActionCachingMockController.new
end
def teardown
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
end
def test_simple_action_cache
get :index
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test')
reset!
get :index
assert_equal cached_time, @response.body
end
def test_simple_action_not_cached
get :destroy
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert !fragment_exist?('hostname.com/action_caching_test/destroy')
reset!
get :destroy
assert_not_equal cached_time, @response.body
end
def test_action_cache_with_layout
get :with_layout
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/with_layout')
reset!
get :with_layout
assert_not_equal cached_time, @response.body
assert_equal @response.body, read_fragment('hostname.com/action_caching_test/with_layout')
end
def test_action_cache_with_layout_and_layout_cache_false
get :layout_false
cached_time = content_to_cache
assert_not_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/layout_false')
reset!
get :layout_false
assert_not_equal cached_time, @response.body
assert_equal cached_time, read_fragment('hostname.com/action_caching_test/layout_false')
end
def test_action_cache_conditional_options
old_use_accept_header = ActionController::Base.use_accept_header
ActionController::Base.use_accept_header = true
@request.env['HTTP_ACCEPT'] = 'application/json'
get :index
assert !fragment_exist?('hostname.com/action_caching_test')
ActionController::Base.use_accept_header = old_use_accept_header
end
def test_action_cache_with_store_options
MockTime.expects(:now).returns(12345).once
@controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
@controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once
get :index
end
def test_action_cache_with_custom_cache_path
get :show
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert fragment_exist?('test.host/custom/show')
reset!
get :show
assert_equal cached_time, @response.body
end
def test_action_cache_with_custom_cache_path_in_block
get :edit
assert fragment_exist?('test.host/edit')
reset!
get :edit, :id => 1
assert fragment_exist?('test.host/1;edit')
end
def test_cache_expiration
get :index
cached_time = content_to_cache
reset!
get :index
assert_equal cached_time, @response.body
reset!
get :expire
reset!
get :index
new_cached_time = content_to_cache
assert_not_equal cached_time, @response.body
reset!
get :index
assert_response :success
assert_equal new_cached_time, @response.body
end
def test_cache_expiration_isnt_affected_by_request_format
get :index
cached_time = content_to_cache
reset!
@request.set_REQUEST_URI "/action_caching_test/expire.xml"
get :expire, :format => :xml
reset!
get :index
new_cached_time = content_to_cache
assert_not_equal cached_time, @response.body
end
def test_cache_is_scoped_by_subdomain
@request.host = 'jamis.hostname.com'
get :index
jamis_cache = content_to_cache
reset!
@request.host = 'david.hostname.com'
get :index
david_cache = content_to_cache
assert_not_equal jamis_cache, @response.body
reset!
@request.host = 'jamis.hostname.com'
get :index
assert_equal jamis_cache, @response.body
reset!
@request.host = 'david.hostname.com'
get :index
assert_equal david_cache, @response.body
end
def test_redirect_is_not_cached
get :redirected
assert_response :redirect
reset!
get :redirected
assert_response :redirect
end
def test_forbidden_is_not_cached
get :forbidden
assert_response :forbidden
reset!
get :forbidden
assert_response :forbidden
end
def test_xml_version_of_resource_is_treated_as_different_cache
with_routing do |set|
set.draw do |map|
map.connect ':controller/:action.:format'
map.connect ':controller/:action'
end
get :index, :format => 'xml'
cached_time = content_to_cache
assert_equal cached_time, @response.body
assert fragment_exist?('hostname.com/action_caching_test/index.xml')
reset!
get :index, :format => 'xml'
assert_equal cached_time, @response.body
assert_equal 'application/xml', @response.content_type
reset!
get :expire_xml
reset!
get :index, :format => 'xml'
assert_not_equal cached_time, @response.body
end
end
def test_correct_content_type_is_returned_for_cache_hit
# run it twice to cache it the first time
get :index, :id => 'content-type.xml'
get :index, :id => 'content-type.xml'
assert_equal 'application/xml', @response.content_type
end
def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key
# run it twice to cache it the first time
get :show, :format => 'xml'
get :show, :format => 'xml'
assert_equal 'application/xml', @response.content_type
end
def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key_from_proc
# run it twice to cache it the first time
get :edit, :id => 1, :format => 'xml'
get :edit, :id => 1, :format => 'xml'
assert_equal 'application/xml', @response.content_type
end
def test_empty_path_is_normalized
@mock_controller.mock_url_for = 'http://example.org/'
@mock_controller.mock_path = '/'
assert_equal 'example.org/index', @path_class.path_for(@mock_controller, {})
end
def test_file_extensions
get :index, :id => 'kitten.jpg'
get :index, :id => 'kitten.jpg'
assert_response :success
end
def test_record_not_found_returns_404_for_multiple_requests
get :record_not_found
assert_response 404
get :record_not_found
assert_response 404
end
def test_four_oh_four_returns_404_for_multiple_requests
get :four_oh_four
assert_response 404
get :four_oh_four
assert_response 404
end
def test_simple_runtime_error_returns_500_for_multiple_requests
get :simple_runtime_error
assert_response 500
get :simple_runtime_error
assert_response 500
end
private
def content_to_cache
assigns(:cache_this)
end
def reset!
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = ActionCachingTestController.new
@request.host = 'hostname.com'
end
def fragment_exist?(path)
@controller.fragment_exist?(path)
end
def read_fragment(path)
@controller.read_fragment(path)
end
end
class FragmentCachingTestController < ActionController::Base
def some_action; end;
end
class FragmentCachingTest < ActionController::TestCase
def setup
ActionController::Base.perform_caching = true
@store = ActiveSupport::Cache::MemoryStore.new
ActionController::Base.cache_store = @store
@controller = FragmentCachingTestController.new
@params = {:controller => 'posts', :action => 'index'}
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller.params = @params
@controller.request = @request
@controller.response = @response
@controller.send(:initialize_current_url)
@controller.send(:initialize_template_class, @response)
@controller.send(:assign_shortcuts, @request, @response)
end
def test_fragment_cache_key
assert_equal 'views/what a key', @controller.fragment_cache_key('what a key')
assert_equal "views/test.host/fragment_caching_test/some_action",
@controller.fragment_cache_key(:controller => 'fragment_caching_test',:action => 'some_action')
end
def test_read_fragment_with_caching_enabled
@store.write('views/name', 'value')
assert_equal 'value', @controller.read_fragment('name')
end
def test_read_fragment_with_caching_disabled
ActionController::Base.perform_caching = false
@store.write('views/name', 'value')
assert_nil @controller.read_fragment('name')
end
def test_fragment_exist_with_caching_enabled
@store.write('views/name', 'value')
assert @controller.fragment_exist?('name')
assert !@controller.fragment_exist?('other_name')
end
def test_fragment_exist_with_caching_disabled
ActionController::Base.perform_caching = false
@store.write('views/name', 'value')
assert !@controller.fragment_exist?('name')
assert !@controller.fragment_exist?('other_name')
end
def test_write_fragment_with_caching_enabled
assert_nil @store.read('views/name')
assert_equal 'value', @controller.write_fragment('name', 'value')
assert_equal 'value', @store.read('views/name')
end
def test_write_fragment_with_caching_disabled
assert_nil @store.read('views/name')
ActionController::Base.perform_caching = false
assert_equal 'value', @controller.write_fragment('name', 'value')
assert_nil @store.read('views/name')
end
def test_expire_fragment_with_simple_key
@store.write('views/name', 'value')
@controller.expire_fragment 'name'
assert_nil @store.read('views/name')
end
def test_expire_fragment_with_regexp
@store.write('views/name', 'value')
@store.write('views/another_name', 'another_value')
@store.write('views/primalgrasp', 'will not expire ;-)')
@controller.expire_fragment /name/
assert_nil @store.read('views/name')
assert_nil @store.read('views/another_name')
assert_equal 'will not expire ;-)', @store.read('views/primalgrasp')
end
def test_fragment_for_with_disabled_caching
ActionController::Base.perform_caching = false
@store.write('views/expensive', 'fragment content')
fragment_computed = false
buffer = 'generated till now -> '.html_safe
@controller.fragment_for(buffer, 'expensive') { fragment_computed = true }
assert fragment_computed
assert_equal 'generated till now -> ', buffer
end
def test_fragment_for
@store.write('views/expensive', 'fragment content')
fragment_computed = false
buffer = 'generated till now -> '.html_safe
@controller.fragment_for(buffer, 'expensive') { fragment_computed = true }
assert !fragment_computed
assert_equal 'generated till now -> fragment content', buffer
end
def test_html_safety
assert_nil @store.read('views/name')
content = 'value'.html_safe
assert_equal content, @controller.write_fragment('name', content)
cached = @store.read('views/name')
assert_equal content, cached
assert_equal String, cached.class
html_safe = @controller.read_fragment('name')
assert_equal content, html_safe
assert html_safe.html_safe?
end
end
class FunctionalCachingController < ActionController::Base
def fragment_cached
end
def html_fragment_cached_with_partial
respond_to do |format|
format.html
end
end
def js_fragment_cached_with_partial
respond_to do |format|
format.js
end
end
def formatted_fragment_cached
respond_to do |format|
format.html
format.xml
format.js
end
end
def rescue_action(e)
raise e
end
end
class FunctionalFragmentCachingTest < ActionController::TestCase
def setup
ActionController::Base.perform_caching = true
@store = ActiveSupport::Cache::MemoryStore.new
ActionController::Base.cache_store = @store
@controller = FunctionalCachingController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_fragment_caching
get :fragment_cached
assert_response :success
expected_body = <<-CACHED
Hello
This bit's fragment cached
CACHED
assert_equal expected_body, @response.body
assert_equal "This bit's fragment cached", @store.read('views/test.host/functional_caching/fragment_cached')
end
def test_fragment_caching_in_partials
get :html_fragment_cached_with_partial
assert_response :success
assert_match /Fragment caching in a partial/, @response.body
assert_match "Fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial')
end
def test_render_inline_before_fragment_caching
get :inline_fragment_cached
assert_response :success
assert_match /Some inline content/, @response.body
assert_match /Some cached content/, @response.body
assert_match "Some cached content", @store.read('views/test.host/functional_caching/inline_fragment_cached')
end
def test_fragment_caching_in_rjs_partials
xhr :get, :js_fragment_cached_with_partial
assert_response :success
assert_match /Fragment caching in a partial/, @response.body
assert_match "Fragment caching in a partial", @store.read('views/test.host/functional_caching/js_fragment_cached_with_partial')
end
def test_html_formatted_fragment_caching
get :formatted_fragment_cached, :format => "html"
assert_response :success
expected_body = "<body>\n<p>ERB</p>\n</body>"
assert_equal expected_body, @response.body
assert_equal "<p>ERB</p>", @store.read('views/test.host/functional_caching/formatted_fragment_cached')
end
def test_xml_formatted_fragment_caching
get :formatted_fragment_cached, :format => "xml"
assert_response :success
expected_body = "<body>\n <p>Builder</p>\n</body>\n"
assert_equal expected_body, @response.body
assert_equal " <p>Builder</p>\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached')
end
def test_js_formatted_fragment_caching
get :formatted_fragment_cached, :format => "js"
assert_response :success
expected_body = %(title = "Hey";\n$("element_1").visualEffect("highlight");\n) +
%($("element_2").visualEffect("highlight");\nfooter = "Bye";)
assert_equal expected_body, @response.body
assert_equal ['$("element_1").visualEffect("highlight");', '$("element_2").visualEffect("highlight");'],
@store.read('views/test.host/functional_caching/formatted_fragment_cached')
end
end

View file

@ -1,66 +0,0 @@
require 'abstract_unit'
class CaptureController < ActionController::Base
def self.controller_name; "test"; end
def self.controller_path; "test"; end
def content_for
render :layout => "talk_from_action"
end
def content_for_with_parameter
render :layout => "talk_from_action"
end
def content_for_concatenated
render :layout => "talk_from_action"
end
def non_erb_block_content_for
render :layout => "talk_from_action"
end
def rescue_action(e) raise end
end
class CaptureTest < ActionController::TestCase
tests CaptureController
def setup
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
@controller.logger = Logger.new(nil)
@request.host = "www.nextangle.com"
end
def test_simple_capture
get :capturing
assert_equal "<p>Dreamy days</p>", @response.body.strip
end
def test_content_for
get :content_for
assert_equal expected_content_for_output, @response.body
end
def test_should_concatentate_content_for
get :content_for_concatenated
assert_equal expected_content_for_output, @response.body
end
def test_should_set_content_for_with_parameter
get :content_for_with_parameter
assert_equal expected_content_for_output, @response.body
end
def test_non_erb_block_content_for
get :non_erb_block_content_for
assert_equal expected_content_for_output, @response.body
end
private
def expected_content_for_output
"<title>Putting stuff in the title!</title>\n\nGreat stuff!"
end
end

View file

@ -1,168 +0,0 @@
require 'abstract_unit'
class ContentTypeController < ActionController::Base
def render_content_type_from_body
response.content_type = Mime::RSS
render :text => "hello world!"
end
def render_defaults
render :text => "hello world!"
end
def render_content_type_from_render
render :text => "hello world!", :content_type => Mime::RSS
end
def render_charset_from_body
response.charset = "utf-16"
render :text => "hello world!"
end
def render_nil_charset_from_body
response.charset = nil
render :text => "hello world!"
end
def render_default_for_rhtml
end
def render_default_for_rxml
end
def render_default_for_rjs
end
def render_change_for_rxml
response.content_type = Mime::HTML
render :action => "render_default_for_rxml"
end
def render_default_content_types_for_respond_to
respond_to do |format|
format.html { render :text => "hello world!" }
format.xml { render :action => "render_default_content_types_for_respond_to.rhtml" }
format.js { render :text => "hello world!" }
format.rss { render :text => "hello world!", :content_type => Mime::XML }
end
end
def rescue_action(e) raise end
end
class ContentTypeTest < ActionController::TestCase
tests ContentTypeController
def setup
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
@controller.logger = Logger.new(nil)
end
def test_render_defaults
get :render_defaults
assert_equal "utf-8", @response.charset
assert_equal Mime::HTML, @response.content_type
end
def test_render_changed_charset_default
ContentTypeController.default_charset = "utf-16"
get :render_defaults
assert_equal "utf-16", @response.charset
assert_equal Mime::HTML, @response.content_type
ContentTypeController.default_charset = "utf-8"
end
def test_content_type_from_body
get :render_content_type_from_body
assert_equal "application/rss+xml", @response.content_type
assert_equal "utf-8", @response.charset
end
def test_content_type_from_render
get :render_content_type_from_render
assert_equal "application/rss+xml", @response.content_type
assert_equal "utf-8", @response.charset
end
def test_charset_from_body
get :render_charset_from_body
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-16", @response.charset
end
def test_nil_charset_from_body
get :render_nil_charset_from_body
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-8", @response.charset, @response.headers.inspect
end
def test_nil_default_for_rhtml
ContentTypeController.default_charset = nil
get :render_default_for_rhtml
assert_equal Mime::HTML, @response.content_type
assert_nil @response.charset, @response.headers.inspect
ensure
ContentTypeController.default_charset = "utf-8"
end
def test_default_for_rhtml
get :render_default_for_rhtml
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-8", @response.charset
end
def test_default_for_rxml
get :render_default_for_rxml
assert_equal Mime::XML, @response.content_type
assert_equal "utf-8", @response.charset
end
def test_default_for_rjs
xhr :post, :render_default_for_rjs
assert_equal Mime::JS, @response.content_type
assert_equal "utf-8", @response.charset
end
def test_change_for_rxml
get :render_change_for_rxml
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-8", @response.charset
end
end
class AcceptBasedContentTypeTest < ActionController::TestCase
tests ContentTypeController
def setup
ActionController::Base.use_accept_header = true
end
def teardown
ActionController::Base.use_accept_header = false
end
def test_render_default_content_types_for_respond_to
@request.accept = Mime::HTML.to_s
get :render_default_content_types_for_respond_to
assert_equal Mime::HTML, @response.content_type
@request.accept = Mime::JS.to_s
get :render_default_content_types_for_respond_to
assert_equal Mime::JS, @response.content_type
end
def test_render_default_content_types_for_respond_to_with_template
@request.accept = Mime::XML.to_s
get :render_default_content_types_for_respond_to
assert_equal Mime::XML, @response.content_type
end
def test_render_default_content_types_for_respond_to_with_overwrite
@request.accept = Mime::RSS.to_s
get :render_default_content_types_for_respond_to
assert_equal Mime::XML, @response.content_type
end
end

View file

@ -1,170 +0,0 @@
require 'abstract_unit'
class CookieTest < ActionController::TestCase
class TestController < ActionController::Base
self.cookie_verifier_secret = "thisISverySECRET123"
def authenticate
cookies["user_name"] = "david"
end
def set_with_with_escapable_characters
cookies["that & guy"] = "foo & bar => baz"
end
def authenticate_for_fourteen_days
cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
end
def authenticate_for_fourteen_days_with_symbols
cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) }
end
def set_multiple_cookies
cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
cookies["login"] = "XJ-122"
end
def access_frozen_cookies
cookies["will"] = "work"
end
def logout
cookies.delete("user_name")
end
def delete_cookie_with_path
cookies.delete("user_name", :path => '/beaten')
render :text => "hello world"
end
def authenticate_with_http_only
cookies["user_name"] = { :value => "david", :httponly => true }
end
def set_permanent_cookie
cookies.permanent[:user_name] = "Jamie"
end
def set_signed_cookie
cookies.signed[:user_id] = 45
end
def set_permanent_signed_cookie
cookies.permanent.signed[:remember_me] = 100
end
def rescue_action(e)
raise unless ActionView::MissingTemplate # No templates here, and we don't care about the output
end
end
tests TestController
def setup
@request.host = "www.nextangle.com"
end
def test_setting_cookie
get :authenticate
assert_equal ["user_name=david; path=/"], @response.headers["Set-Cookie"]
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_setting_with_escapable_characters
get :set_with_with_escapable_characters
assert_equal ["that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"], @response.headers["Set-Cookie"]
assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies)
end
def test_setting_cookie_for_fourteen_days
get :authenticate_for_fourteen_days
assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"]
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_setting_cookie_for_fourteen_days_with_symbols
get :authenticate_for_fourteen_days_with_symbols
assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"]
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_setting_cookie_with_http_only
get :authenticate_with_http_only
assert_equal ["user_name=david; path=/; HttpOnly"], @response.headers["Set-Cookie"]
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_multiple_cookies
get :set_multiple_cookies
assert_equal 2, @response.cookies.size
assert_equal "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", @response.headers["Set-Cookie"][0]
assert_equal "login=XJ-122; path=/", @response.headers["Set-Cookie"][1]
assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies)
end
def test_setting_test_cookie
assert_nothing_raised { get :access_frozen_cookies }
end
def test_expiring_cookie
get :logout
assert_equal ["user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"]
assert_equal({"user_name" => nil}, @response.cookies)
end
def test_cookiejar_accessor
@request.cookies["user_name"] = "david"
@controller.request = @request
jar = ActionController::CookieJar.new(@controller)
assert_equal "david", jar["user_name"]
assert_equal nil, jar["something_else"]
end
def test_cookiejar_accessor_with_array_value
@request.cookies["pages"] = %w{1 2 3}
@controller.request = @request
jar = ActionController::CookieJar.new(@controller)
assert_equal %w{1 2 3}, jar["pages"]
end
def test_cookiejar_delete_removes_item_and_returns_its_value
@request.cookies["user_name"] = "david"
@controller.response = @response
jar = ActionController::CookieJar.new(@controller)
assert_equal "david", jar.delete("user_name")
end
def test_delete_cookie_with_path
get :delete_cookie_with_path
assert_equal ["user_name=; path=/beaten; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"]
end
def test_cookies_persist_throughout_request
get :authenticate
cookies = @controller.send(:cookies)
assert_equal 'david', cookies['user_name']
end
def test_permanent_cookie
get :set_permanent_cookie
assert_match /Jamie/, @response.headers["Set-Cookie"].first
assert_match %r(#{20.years.from_now.year}), @response.headers["Set-Cookie"].first
end
def test_signed_cookie
get :set_signed_cookie
assert_equal 45, @controller.send(:cookies).signed[:user_id]
end
def test_accessing_nonexistant_signed_cookie_should_not_raise_an_invalid_signature
get :set_signed_cookie
assert_nil @controller.send(:cookies).signed[:non_existant_attribute]
end
def test_permanent_signed_cookie
get :set_permanent_signed_cookie
assert_match %r(#{20.years.from_now.year}), @response.headers["Set-Cookie"].first
assert_equal 100, @controller.send(:cookies).signed[:remember_me]
end
end

View file

@ -1,32 +0,0 @@
require 'abstract_unit'
class DeprecatedBaseMethodsTest < ActionController::TestCase
class Target < ActionController::Base
def home_url(greeting)
"http://example.com/#{greeting}"
end
def raises_name_error
this_method_doesnt_exist
end
def rescue_action(e) raise e end
end
tests Target
def test_log_error_silences_deprecation_warnings
get :raises_name_error
rescue => e
assert_not_deprecated { @controller.send :log_error, e }
end
if defined? Test::Unit::Error
def test_assertion_failed_error_silences_deprecation_warnings
get :raises_name_error
rescue => e
error = Test::Unit::Error.new('testing ur doodz', e)
assert_not_deprecated { error.message }
end
end
end

View file

@ -1,144 +0,0 @@
require 'abstract_unit'
class DispatcherTest < Test::Unit::TestCase
Dispatcher = ActionController::Dispatcher
Reloader = ActionController::Reloader
def setup
ENV['REQUEST_METHOD'] = 'GET'
reset_dispatcher
Dispatcher.stubs(:require_dependency)
end
def teardown
ENV.delete 'REQUEST_METHOD'
reset_dispatcher
end
def test_clears_dependencies_after_dispatch_if_in_loading_mode
ActiveSupport::Dependencies.expects(:clear).once
# Close the response so dependencies kicks in
dispatch(false).last.close
end
def test_reloads_routes_before_dispatch_if_in_loading_mode
ActionController::Routing::Routes.expects(:reload).once
dispatch(false)
end
def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode
ActionController::Routing::Routes.expects(:reload).never
ActiveSupport::Dependencies.expects(:clear).never
dispatch
end
def test_builds_middleware_stack_only_during_initialization_if_not_in_loading_mode
dispatcher = create_dispatcher
assert_not_nil dispatcher.instance_variable_get(:"@app")
dispatcher.instance_variable_set(:"@app", lambda { |env| })
dispatcher.expects(:build_middleware_stack).never
dispatcher.call(nil)
dispatcher.call(nil)
end
def test_rebuilds_middleware_stack_on_every_request_if_in_loading_mode
dispatcher = create_dispatcher(false)
dispatcher.instance_variable_set(:"@app", lambda { |env| })
dispatcher.expects(:build_middleware_stack).twice
dispatcher.call(nil)
Reloader.default_lock.unlock
dispatcher.call(nil)
end
def test_doesnt_wrap_call_in_reloader_if_not_in_loading_mode
Reloader.expects(:run).never
dispatch
end
def test_wraps_call_in_reloader_if_in_loading_mode
Reloader.expects(:run).once
dispatch(false)
end
# Stub out dispatch error logger
class << Dispatcher
def log_failsafe_exception(status, exception); end
end
def test_failsafe_response
Dispatcher.any_instance.expects(:dispatch).raises('b00m')
ActionController::Failsafe.any_instance.expects(:log_failsafe_exception)
response = nil
assert_nothing_raised do
response = dispatch
end
assert_equal 3, response.size
assert_equal 500, response[0]
assert_equal({"Content-Type" => "text/html"}, response[1])
assert_match /500 Internal Server Error/, response[2].join
end
def test_prepare_callbacks
a = b = c = nil
Dispatcher.to_prepare { |*args| a = b = c = 1 }
Dispatcher.to_prepare { |*args| b = c = 2 }
Dispatcher.to_prepare { |*args| c = 3 }
# Ensure to_prepare callbacks are not run when defined
assert_nil a || b || c
# Run callbacks
Dispatcher.run_prepare_callbacks
assert_equal 1, a
assert_equal 2, b
assert_equal 3, c
# Make sure they are only run once
a = b = c = nil
dispatch
assert_nil a || b || c
end
def test_to_prepare_with_identifier_replaces
a = b = nil
Dispatcher.to_prepare(:unique_id) { |*args| a = b = 1 }
Dispatcher.to_prepare(:unique_id) { |*args| a = 2 }
Dispatcher.run_prepare_callbacks
assert_equal 2, a
assert_equal nil, b
end
private
def dispatch(cache_classes = true)
ActionController::Routing::RouteSet.any_instance.stubs(:call).returns([200, {}, 'response'])
Dispatcher.define_dispatcher_callbacks(cache_classes)
Dispatcher.new.call({'rack.input' => StringIO.new('')})
end
def create_dispatcher(cache_classes = true)
Dispatcher.define_dispatcher_callbacks(cache_classes)
Dispatcher.new
end
def reset_dispatcher
Dispatcher.middleware = ActionController::MiddlewareStack.new do |middleware|
middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/middlewares.rb"))
middleware.instance_eval(File.read(middlewares))
end
# Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks
Dispatcher.instance_variable_set("@prepare_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
Dispatcher.instance_variable_set("@before_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
Dispatcher.instance_variable_set("@after_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
Dispatcher.define_dispatcher_callbacks(true)
end
def assert_subclasses(howmany, klass, message = klass.subclasses.inspect)
assert_equal howmany, klass.subclasses.size, message
end
end

View file

@ -1,53 +0,0 @@
require 'abstract_unit'
class DomAssertionsTest < ActionView::TestCase
def setup
super
@html_only = '<ul><li>foo</li><li>bar</li></ul>'
@html_with_meaningless_whitespace = %{
<ul>
<li>\tfoo </li>
<li>
bar
</li>
</ul>
}
@more_html_with_meaningless_whitespace = %{<ul>
<li>foo</li>
<li>bar</li></ul>}
end
test "assert_dom_equal strips meaningless whitespace from expected string" do
assert_dom_equal @html_with_meaningless_whitespace, @html_only
end
test "assert_dom_equal strips meaningless whitespace from actual string" do
assert_dom_equal @html_only, @html_with_meaningless_whitespace
end
test "assert_dom_equal strips meaningless whitespace from both expected and actual strings" do
assert_dom_equal @more_html_with_meaningless_whitespace, @html_with_meaningless_whitespace
end
test "assert_dom_not_equal strips meaningless whitespace from expected string" do
assert_assertion_fails { assert_dom_not_equal @html_with_meaningless_whitespace, @html_only }
end
test "assert_dom_not_equal strips meaningless whitespace from actual string" do
assert_assertion_fails { assert_dom_not_equal @html_only, @html_with_meaningless_whitespace }
end
test "assert_dom_not_equal strips meaningless whitespace from both expected and actual strings" do
assert_assertion_fails do
assert_dom_not_equal @more_html_with_meaningless_whitespace, @html_with_meaningless_whitespace
end
end
private
def assert_assertion_fails
assert_raise(ActiveSupport::TestCase::Assertion) { yield }
end
end

View file

@ -1,60 +0,0 @@
require 'abstract_unit'
require 'stringio'
require 'logger'
class FailsafeTest < ActionController::TestCase
FIXTURE_PUBLIC = "#{File.dirname(__FILE__)}/../fixtures/failsafe".freeze
def setup
@old_error_file_path = ActionController::Failsafe.error_file_path
ActionController::Failsafe.error_file_path = FIXTURE_PUBLIC
@app = mock
@log_io = StringIO.new
@logger = Logger.new(@log_io)
@failsafe = ActionController::Failsafe.new(@app)
@failsafe.stubs(:failsafe_logger).returns(@logger)
end
def teardown
ActionController::Failsafe.error_file_path = @old_error_file_path
end
def app_will_raise_error!
@app.expects(:call).then.raises(RuntimeError.new("Printer on fire"))
end
def test_calls_app_and_returns_its_return_value
@app.expects(:call).returns([200, { "Content-Type" => "text/html" }, "ok"])
assert_equal [200, { "Content-Type" => "text/html" }, "ok"], @failsafe.call({})
end
def test_writes_to_log_file_on_exception
app_will_raise_error!
@failsafe.call({})
assert_match /Printer on fire/, @log_io.string # Logs exception message.
assert_match /failsafe_test\.rb/, @log_io.string # Logs backtrace.
end
def test_returns_500_internal_server_error_on_exception
app_will_raise_error!
response = @failsafe.call({})
assert_equal 3, response.size # It is a valid Rack response.
assert_equal 500, response[0] # Status is 500.
end
def test_renders_error_page_file_with_erb
app_will_raise_error!
response = @failsafe.call({})
assert_equal 500, response[0]
assert_equal "hello my world", response[2].join
end
def test_returns_a_default_message_if_erb_rendering_failed
app_will_raise_error!
@failsafe.expects(:render_template).raises(RuntimeError.new("Harddisk is crashing"))
response = @failsafe.call({})
assert_equal 500, response[0]
assert_match /500 Internal Server Error/, response[2].join
assert_match %r(please read this web application's log file), response[2].join
end
end

View file

@ -1,33 +0,0 @@
class << Object; alias_method :const_available?, :const_defined?; end
class ContentController < Class.new(ActionController::Base)
end
class NotAController
end
module Admin
class << self; alias_method :const_available?, :const_defined?; end
class UserController < Class.new(ActionController::Base); end
class NewsFeedController < Class.new(ActionController::Base); end
end
# For speed test
class SpeedController < ActionController::Base; end
class SearchController < SpeedController; end
class VideosController < SpeedController; end
class VideoFileController < SpeedController; end
class VideoSharesController < SpeedController; end
class VideoAbusesController < SpeedController; end
class VideoUploadsController < SpeedController; end
class VideoVisitsController < SpeedController; end
class UsersController < SpeedController; end
class SettingsController < SpeedController; end
class ChannelsController < SpeedController; end
class ChannelVideosController < SpeedController; end
class SessionsController < SpeedController; end
class LostPasswordsController < SpeedController; end
class PagesController < SpeedController; end
ActionController::Routing::Routes.draw do |map|
map.route_one 'route_one', :controller => 'elsewhere', :action => 'flash_me'
map.connect ':controller/:action/:id'
end

View file

@ -1,19 +0,0 @@
class Customer < Struct.new(:name, :id)
def to_param
id.to_s
end
end
class BadCustomer < Customer
end
class GoodCustomer < Customer
end
module Quiz
class Question < Struct.new(:name, :id)
def to_param
id.to_s
end
end
end

View file

@ -1,52 +0,0 @@
require 'abstract_unit'
class FilterParamController < ActionController::Base
end
class FilterParamTest < Test::Unit::TestCase
def setup
@controller = FilterParamController.new
end
def test_filter_parameters
assert FilterParamController.respond_to?(:filter_parameter_logging)
assert !@controller.respond_to?(:filter_parameters)
FilterParamController.filter_parameter_logging
assert @controller.respond_to?(:filter_parameters)
test_hashes = [[{},{},[]],
[{'foo'=>nil},{'foo'=>nil},[]],
[{'foo'=>'bar'},{'foo'=>'bar'},[]],
[{'foo'=>1},{'foo'=>1},[]],
[{'foo'=>'bar'},{'foo'=>'bar'},%w'food'],
[{'foo'=>'bar'},{'foo'=>'[FILTERED]'},%w'foo'],
[{'foo'=>'bar', 'bar'=>'foo'},{'foo'=>'[FILTERED]', 'bar'=>'foo'},%w'foo baz'],
[{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'],
[{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'],
[{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'],
[{'baz'=>[{'foo'=>'baz'}]}, {'baz'=>[{'foo'=>'[FILTERED]'}]}, %w(foo)],
[{'baz'=>[{'foo'=>'baz'}, 1, 2, 3]}, {'baz'=>[{'foo'=>'[FILTERED]'}, 1, 2, 3]}, %w(foo)]]
test_hashes.each do |before_filter, after_filter, filter_words|
FilterParamController.filter_parameter_logging(*filter_words)
assert_equal after_filter, @controller.__send__(:filter_parameters, before_filter)
filter_words.push('blah')
FilterParamController.filter_parameter_logging(*filter_words) do |key, value|
value.reverse! if key =~ /bargain/
end
before_filter['barg'] = {'bargain'=>'gain', 'blah'=>'bar', 'bar'=>{'bargain'=>{'blah'=>'foo'}}}
after_filter['barg'] = {'bargain'=>'niag', 'blah'=>'[FILTERED]', 'bar'=>{'bargain'=>{'blah'=>'[FILTERED]'}}}
assert_equal after_filter, @controller.__send__(:filter_parameters, before_filter)
end
end
def test_filter_parameters_is_protected
FilterParamController.filter_parameter_logging(:foo)
assert !FilterParamController.action_methods.include?('filter_parameters')
assert_raise(NoMethodError) { @controller.filter_parameters([{'password' => '[FILTERED]'}]) }
end
end

View file

@ -1,885 +0,0 @@
require 'abstract_unit'
# FIXME: crashes Ruby 1.9
class FilterTest < Test::Unit::TestCase
class TestController < ActionController::Base
before_filter :ensure_login
after_filter :clean_up
def show
render :inline => "ran action"
end
private
def ensure_login
@ran_filter ||= []
@ran_filter << "ensure_login"
end
def clean_up
@ran_after_filter ||= []
@ran_after_filter << "clean_up"
end
end
class ChangingTheRequirementsController < TestController
before_filter :ensure_login, :except => [:go_wild]
def go_wild
render :text => "gobble"
end
end
class TestMultipleFiltersController < ActionController::Base
before_filter :try_1
before_filter :try_2
before_filter :try_3
(1..3).each do |i|
define_method "fail_#{i}" do
render :text => i.to_s
end
end
protected
(1..3).each do |i|
define_method "try_#{i}" do
instance_variable_set :@try, i
if action_name == "fail_#{i}"
head(404)
end
end
end
end
class RenderingController < ActionController::Base
before_filter :render_something_else
def show
@ran_action = true
render :inline => "ran action"
end
private
def render_something_else
render :inline => "something else"
end
end
class ConditionalFilterController < ActionController::Base
def show
render :inline => "ran action"
end
def another_action
render :inline => "ran action"
end
def show_without_filter
render :inline => "ran action without filter"
end
private
def ensure_login
@ran_filter ||= []
@ran_filter << "ensure_login"
end
def clean_up_tmp
@ran_filter ||= []
@ran_filter << "clean_up_tmp"
end
def rescue_action(e) raise(e) end
end
class ConditionalCollectionFilterController < ConditionalFilterController
before_filter :ensure_login, :except => [ :show_without_filter, :another_action ]
end
class OnlyConditionSymController < ConditionalFilterController
before_filter :ensure_login, :only => :show
end
class ExceptConditionSymController < ConditionalFilterController
before_filter :ensure_login, :except => :show_without_filter
end
class BeforeAndAfterConditionController < ConditionalFilterController
before_filter :ensure_login, :only => :show
after_filter :clean_up_tmp, :only => :show
end
class OnlyConditionProcController < ConditionalFilterController
before_filter(:only => :show) {|c| c.instance_variable_set(:"@ran_proc_filter", true) }
end
class ExceptConditionProcController < ConditionalFilterController
before_filter(:except => :show_without_filter) {|c| c.instance_variable_set(:"@ran_proc_filter", true) }
end
class ConditionalClassFilter
def self.filter(controller) controller.instance_variable_set(:"@ran_class_filter", true) end
end
class OnlyConditionClassController < ConditionalFilterController
before_filter ConditionalClassFilter, :only => :show
end
class ExceptConditionClassController < ConditionalFilterController
before_filter ConditionalClassFilter, :except => :show_without_filter
end
class AnomolousYetValidConditionController < ConditionalFilterController
before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)}
end
class ConditionalOptionsFilter < ConditionalFilterController
before_filter :ensure_login, :if => Proc.new { |c| true }
before_filter :clean_up_tmp, :if => Proc.new { |c| false }
end
class EmptyFilterChainController < TestController
self.filter_chain.clear
def show
@action_executed = true
render :text => "yawp!"
end
end
class PrependingController < TestController
prepend_before_filter :wonderful_life
# skip_before_filter :fire_flash
private
def wonderful_life
@ran_filter ||= []
@ran_filter << "wonderful_life"
end
end
class SkippingAndLimitedController < TestController
skip_before_filter :ensure_login
before_filter :ensure_login, :only => :index
def index
render :text => 'ok'
end
def public
end
end
class SkippingAndReorderingController < TestController
skip_before_filter :ensure_login
before_filter :find_record
before_filter :ensure_login
private
def find_record
@ran_filter ||= []
@ran_filter << "find_record"
end
end
class ConditionalSkippingController < TestController
skip_before_filter :ensure_login, :only => [ :login ]
skip_after_filter :clean_up, :only => [ :login ]
before_filter :find_user, :only => [ :change_password ]
def login
render :inline => "ran action"
end
def change_password
render :inline => "ran action"
end
protected
def find_user
@ran_filter ||= []
@ran_filter << "find_user"
end
end
class ConditionalParentOfConditionalSkippingController < ConditionalFilterController
before_filter :conditional_in_parent, :only => [:show, :another_action]
after_filter :conditional_in_parent, :only => [:show, :another_action]
private
def conditional_in_parent
@ran_filter ||= []
@ran_filter << 'conditional_in_parent'
end
end
class ChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
skip_before_filter :conditional_in_parent, :only => :another_action
skip_after_filter :conditional_in_parent, :only => :another_action
end
class AnotherChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
skip_before_filter :conditional_in_parent, :only => :show
end
class ProcController < PrependingController
before_filter(proc { |c| c.instance_variable_set(:"@ran_proc_filter", true) })
end
class ImplicitProcController < PrependingController
before_filter { |c| c.instance_variable_set(:"@ran_proc_filter", true) }
end
class AuditFilter
def self.filter(controller)
controller.instance_variable_set(:"@was_audited", true)
end
end
class AroundFilter
def before(controller)
@execution_log = "before"
controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log
controller.instance_variable_set(:"@before_ran", true)
end
def after(controller)
controller.instance_variable_set(:"@execution_log", @execution_log + " and after")
controller.instance_variable_set(:"@after_ran", true)
controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log
end
end
class AppendedAroundFilter
def before(controller)
controller.class.execution_log << " before appended aroundfilter "
end
def after(controller)
controller.class.execution_log << " after appended aroundfilter "
end
end
class AuditController < ActionController::Base
before_filter(AuditFilter)
def show
render :text => "hello"
end
end
class AroundFilterController < PrependingController
around_filter AroundFilter.new
end
class BeforeAfterClassFilterController < PrependingController
begin
filter = AroundFilter.new
before_filter filter
after_filter filter
end
end
class MixedFilterController < PrependingController
cattr_accessor :execution_log
def initialize
@@execution_log = ""
end
before_filter { |c| c.class.execution_log << " before procfilter " }
prepend_around_filter AroundFilter.new
after_filter { |c| c.class.execution_log << " after procfilter " }
append_around_filter AppendedAroundFilter.new
end
class MixedSpecializationController < ActionController::Base
class OutOfOrder < StandardError; end
before_filter :first
before_filter :second, :only => :foo
def foo
render :text => 'foo'
end
def bar
render :text => 'bar'
end
protected
def first
@first = true
end
def second
raise OutOfOrder unless @first
end
end
class DynamicDispatchController < ActionController::Base
before_filter :choose
%w(foo bar baz).each do |action|
define_method(action) { render :text => action }
end
private
def choose
self.action_name = params[:choose]
end
end
class PrependingBeforeAndAfterController < ActionController::Base
prepend_before_filter :before_all
prepend_after_filter :after_all
before_filter :between_before_all_and_after_all
def before_all
@ran_filter ||= []
@ran_filter << 'before_all'
end
def after_all
@ran_filter ||= []
@ran_filter << 'after_all'
end
def between_before_all_and_after_all
@ran_filter ||= []
@ran_filter << 'between_before_all_and_after_all'
end
def show
render :text => 'hello'
end
end
class ErrorToRescue < Exception; end
class RescuingAroundFilterWithBlock
def filter(controller)
begin
yield
rescue ErrorToRescue => ex
controller.__send__ :render, :text => "I rescued this: #{ex.inspect}"
end
end
end
class RescuedController < ActionController::Base
around_filter RescuingAroundFilterWithBlock.new
def show
raise ErrorToRescue.new("Something made the bad noise.")
end
private
def rescue_action(exception)
raise exception
end
end
class NonYieldingAroundFilterController < ActionController::Base
before_filter :filter_one
around_filter :non_yielding_filter
before_filter :filter_two
after_filter :filter_three
def index
render :inline => "index"
end
#make sure the controller complains
def rescue_action(e); raise e; end
private
def filter_one
@filters ||= []
@filters << "filter_one"
end
def filter_two
@filters << "filter_two"
end
def non_yielding_filter
@filters << "zomg it didn't yield"
@filter_return_value
end
def filter_three
@filters << "filter_three"
end
end
def test_non_yielding_around_filters_not_returning_false_do_not_raise
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", true
assert_nothing_raised do
test_process(controller, "index")
end
end
def test_non_yielding_around_filters_returning_false_do_not_raise
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", false
assert_nothing_raised do
test_process(controller, "index")
end
end
def test_after_filters_are_not_run_if_around_filter_returns_false
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", false
test_process(controller, "index")
assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters']
end
def test_after_filters_are_not_run_if_around_filter_does_not_yield
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", true
test_process(controller, "index")
assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters']
end
def test_empty_filter_chain
assert_equal 0, EmptyFilterChainController.filter_chain.size
assert test_process(EmptyFilterChainController).template.assigns['action_executed']
end
def test_added_filter_to_inheritance_graph
assert_equal [ :ensure_login ], TestController.before_filters
end
def test_base_class_in_isolation
assert_equal [ ], ActionController::Base.before_filters
end
def test_prepending_filter
assert_equal [ :wonderful_life, :ensure_login ], PrependingController.before_filters
end
def test_running_filters
assert_equal %w( wonderful_life ensure_login ), test_process(PrependingController).template.assigns["ran_filter"]
end
def test_running_filters_with_proc
assert test_process(ProcController).template.assigns["ran_proc_filter"]
end
def test_running_filters_with_implicit_proc
assert test_process(ImplicitProcController).template.assigns["ran_proc_filter"]
end
def test_running_filters_with_class
assert test_process(AuditController).template.assigns["was_audited"]
end
def test_running_anomolous_yet_valid_condition_filters
response = test_process(AnomolousYetValidConditionController)
assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
assert response.template.assigns["ran_class_filter"]
assert response.template.assigns["ran_proc_filter1"]
assert response.template.assigns["ran_proc_filter2"]
response = test_process(AnomolousYetValidConditionController, "show_without_filter")
assert_equal nil, response.template.assigns["ran_filter"]
assert !response.template.assigns["ran_class_filter"]
assert !response.template.assigns["ran_proc_filter1"]
assert !response.template.assigns["ran_proc_filter2"]
end
def test_running_conditional_options
response = test_process(ConditionalOptionsFilter)
assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
end
def test_running_collection_condition_filters
assert_equal %w( ensure_login ), test_process(ConditionalCollectionFilterController).template.assigns["ran_filter"]
assert_equal nil, test_process(ConditionalCollectionFilterController, "show_without_filter").template.assigns["ran_filter"]
assert_equal nil, test_process(ConditionalCollectionFilterController, "another_action").template.assigns["ran_filter"]
end
def test_running_only_condition_filters
assert_equal %w( ensure_login ), test_process(OnlyConditionSymController).template.assigns["ran_filter"]
assert_equal nil, test_process(OnlyConditionSymController, "show_without_filter").template.assigns["ran_filter"]
assert test_process(OnlyConditionProcController).template.assigns["ran_proc_filter"]
assert !test_process(OnlyConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
assert test_process(OnlyConditionClassController).template.assigns["ran_class_filter"]
assert !test_process(OnlyConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
end
def test_running_except_condition_filters
assert_equal %w( ensure_login ), test_process(ExceptConditionSymController).template.assigns["ran_filter"]
assert_equal nil, test_process(ExceptConditionSymController, "show_without_filter").template.assigns["ran_filter"]
assert test_process(ExceptConditionProcController).template.assigns["ran_proc_filter"]
assert !test_process(ExceptConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
assert test_process(ExceptConditionClassController).template.assigns["ran_class_filter"]
assert !test_process(ExceptConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
end
def test_running_before_and_after_condition_filters
assert_equal %w( ensure_login clean_up_tmp), test_process(BeforeAndAfterConditionController).template.assigns["ran_filter"]
assert_equal nil, test_process(BeforeAndAfterConditionController, "show_without_filter").template.assigns["ran_filter"]
end
def test_around_filter
controller = test_process(AroundFilterController)
assert controller.template.assigns["before_ran"]
assert controller.template.assigns["after_ran"]
end
def test_before_after_class_filter
controller = test_process(BeforeAfterClassFilterController)
assert controller.template.assigns["before_ran"]
assert controller.template.assigns["after_ran"]
end
def test_having_properties_in_around_filter
controller = test_process(AroundFilterController)
assert_equal "before and after", controller.template.assigns["execution_log"]
end
def test_prepending_and_appending_around_filter
controller = test_process(MixedFilterController)
assert_equal " before aroundfilter before procfilter before appended aroundfilter " +
" after appended aroundfilter after aroundfilter after procfilter ",
MixedFilterController.execution_log
end
def test_rendering_breaks_filtering_chain
response = test_process(RenderingController)
assert_equal "something else", response.body
assert !response.template.assigns["ran_action"]
end
def test_filters_with_mixed_specialization_run_in_order
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'bar')
assert_equal 'bar', response.body
end
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'foo')
assert_equal 'foo', response.body
end
end
def test_dynamic_dispatch
%w(foo bar baz).each do |action|
request = ActionController::TestRequest.new
request.query_parameters[:choose] = action
response = DynamicDispatchController.process(request, ActionController::TestResponse.new)
assert_equal action, response.body
end
end
def test_running_prepended_before_and_after_filter
assert_equal 3, PrependingBeforeAndAfterController.filter_chain.length
response = test_process(PrependingBeforeAndAfterController)
assert_equal %w( before_all between_before_all_and_after_all after_all ), response.template.assigns["ran_filter"]
end
def test_skipping_and_limiting_controller
assert_equal %w( ensure_login ), test_process(SkippingAndLimitedController, "index").template.assigns["ran_filter"]
assert_nil test_process(SkippingAndLimitedController, "public").template.assigns["ran_filter"]
end
def test_skipping_and_reordering_controller
assert_equal %w( find_record ensure_login ), test_process(SkippingAndReorderingController, "index").template.assigns["ran_filter"]
end
def test_conditional_skipping_of_filters
assert_nil test_process(ConditionalSkippingController, "login").template.assigns["ran_filter"]
assert_equal %w( ensure_login find_user ), test_process(ConditionalSkippingController, "change_password").template.assigns["ran_filter"]
assert_nil test_process(ConditionalSkippingController, "login").template.controller.instance_variable_get("@ran_after_filter")
assert_equal %w( clean_up ), test_process(ConditionalSkippingController, "change_password").template.controller.instance_variable_get("@ran_after_filter")
end
def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
assert_nil test_process(ChildOfConditionalParentController, 'another_action').template.assigns['ran_filter']
end
def test_condition_skipping_of_filters_when_siblings_also_have_conditions
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'], "1"
assert_equal nil, test_process(AnotherChildOfConditionalParentController).template.assigns['ran_filter']
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
end
def test_changing_the_requirements
assert_equal nil, test_process(ChangingTheRequirementsController, "go_wild").template.assigns['ran_filter']
end
def test_a_rescuing_around_filter
response = nil
assert_nothing_raised do
response = test_process(RescuedController)
end
assert response.success?
assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body)
end
private
def test_process(controller, action = "show")
ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
request = ActionController::TestRequest.new
request.action = action
controller = controller.new if controller.is_a?(Class)
controller.process_with_test(request, ActionController::TestResponse.new)
end
end
class PostsController < ActionController::Base
def rescue_action(e); raise e; end
module AroundExceptions
class Error < StandardError ; end
class Before < Error ; end
class After < Error ; end
end
include AroundExceptions
class DefaultFilter
include AroundExceptions
end
module_eval %w(raises_before raises_after raises_both no_raise no_filter).map { |action| "def #{action}; default_action end" }.join("\n")
private
def default_action
render :inline => "#{action_name} called"
end
end
class ControllerWithSymbolAsFilter < PostsController
around_filter :raise_before, :only => :raises_before
around_filter :raise_after, :only => :raises_after
around_filter :without_exception, :only => :no_raise
private
def raise_before
raise Before
yield
end
def raise_after
yield
raise After
end
def without_exception
# Do stuff...
1 + 1
yield
# Do stuff...
1 + 1
end
end
class ControllerWithFilterClass < PostsController
class YieldingFilter < DefaultFilter
def self.filter(controller)
yield
raise After
end
end
around_filter YieldingFilter, :only => :raises_after
end
class ControllerWithFilterInstance < PostsController
class YieldingFilter < DefaultFilter
def filter(controller)
yield
raise After
end
end
around_filter YieldingFilter.new, :only => :raises_after
end
class ControllerWithFilterMethod < PostsController
class YieldingFilter < DefaultFilter
def filter(controller)
yield
raise After
end
end
around_filter YieldingFilter.new.method(:filter), :only => :raises_after
end
class ControllerWithProcFilter < PostsController
around_filter(:only => :no_raise) do |c,b|
c.instance_variable_set(:"@before", true)
b.call
c.instance_variable_set(:"@after", true)
end
end
class ControllerWithNestedFilters < ControllerWithSymbolAsFilter
around_filter :raise_before, :raise_after, :without_exception, :only => :raises_both
end
class ControllerWithAllTypesOfFilters < PostsController
before_filter :before
around_filter :around
after_filter :after
around_filter :around_again
private
def before
@ran_filter ||= []
@ran_filter << 'before'
end
def around
@ran_filter << 'around (before yield)'
yield
@ran_filter << 'around (after yield)'
end
def after
@ran_filter << 'after'
end
def around_again
@ran_filter << 'around_again (before yield)'
yield
@ran_filter << 'around_again (after yield)'
end
end
class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters
skip_filter :around_again
skip_filter :after
end
class YieldingAroundFiltersTest < Test::Unit::TestCase
include PostsController::AroundExceptions
def test_filters_registering
assert_equal 1, ControllerWithFilterMethod.filter_chain.size
assert_equal 1, ControllerWithFilterClass.filter_chain.size
assert_equal 1, ControllerWithFilterInstance.filter_chain.size
assert_equal 3, ControllerWithSymbolAsFilter.filter_chain.size
assert_equal 6, ControllerWithNestedFilters.filter_chain.size
assert_equal 4, ControllerWithAllTypesOfFilters.filter_chain.size
end
def test_base
controller = PostsController
assert_nothing_raised { test_process(controller,'no_raise') }
assert_nothing_raised { test_process(controller,'raises_before') }
assert_nothing_raised { test_process(controller,'raises_after') }
assert_nothing_raised { test_process(controller,'no_filter') }
end
def test_with_symbol
controller = ControllerWithSymbolAsFilter
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(Before) { test_process(controller,'raises_before') }
assert_raise(After) { test_process(controller,'raises_after') }
assert_nothing_raised { test_process(controller,'no_raise') }
end
def test_with_class
controller = ControllerWithFilterClass
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(After) { test_process(controller,'raises_after') }
end
def test_with_instance
controller = ControllerWithFilterInstance
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(After) { test_process(controller,'raises_after') }
end
def test_with_method
controller = ControllerWithFilterMethod
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(After) { test_process(controller,'raises_after') }
end
def test_with_proc
controller = test_process(ControllerWithProcFilter,'no_raise')
assert controller.template.assigns['before']
assert controller.template.assigns['after']
end
def test_nested_filters
controller = ControllerWithNestedFilters
assert_nothing_raised do
begin
test_process(controller,'raises_both')
rescue Before, After
end
end
assert_raise Before do
begin
test_process(controller,'raises_both')
rescue After
end
end
end
def test_filter_order_with_all_filter_types
controller = test_process(ControllerWithAllTypesOfFilters,'no_raise')
assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after',controller.template.assigns['ran_filter'].join(' ')
end
def test_filter_order_with_skip_filter_method
controller = test_process(ControllerWithTwoLessFilters,'no_raise')
assert_equal 'before around (before yield) around (after yield)',controller.template.assigns['ran_filter'].join(' ')
end
def test_first_filter_in_multiple_before_filter_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_1')
assert_equal ' ', response.body
assert_equal 1, controller.instance_variable_get(:@try)
assert controller.instance_variable_get(:@before_filter_chain_aborted)
end
def test_second_filter_in_multiple_before_filter_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_2')
assert_equal ' ', response.body
assert_equal 2, controller.instance_variable_get(:@try)
assert controller.instance_variable_get(:@before_filter_chain_aborted)
end
def test_last_filter_in_multiple_before_filter_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_3')
assert_equal ' ', response.body
assert_equal 3, controller.instance_variable_get(:@try)
assert controller.instance_variable_get(:@before_filter_chain_aborted)
end
protected
def test_process(controller, action = "show")
ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
request = ActionController::TestRequest.new
request.action = action
controller = controller.new if controller.is_a?(Class)
controller.process_with_test(request, ActionController::TestResponse.new)
end
end

View file

@ -1,174 +0,0 @@
require 'abstract_unit'
class FlashTest < ActionController::TestCase
class TestController < ActionController::Base
def set_flash
flash["that"] = "hello"
render :inline => "hello"
end
def set_flash_now
flash.now["that"] = "hello"
flash.now["foo"] ||= "bar"
flash.now["foo"] ||= "err"
@flashy = flash.now["that"]
@flash_copy = {}.update flash
render :inline => "hello"
end
def attempt_to_use_flash_now
@flash_copy = {}.update flash
@flashy = flash["that"]
render :inline => "hello"
end
def use_flash
@flash_copy = {}.update flash
@flashy = flash["that"]
render :inline => "hello"
end
def use_flash_and_keep_it
@flash_copy = {}.update flash
@flashy = flash["that"]
flash.keep
render :inline => "hello"
end
def use_flash_and_update_it
flash.update("this" => "hello again")
@flash_copy = {}.update flash
render :inline => "hello"
end
def use_flash_after_reset_session
flash["that"] = "hello"
@flashy_that = flash["that"]
reset_session
@flashy_that_reset = flash["that"]
flash["this"] = "good-bye"
@flashy_this = flash["this"]
render :inline => "hello"
end
def rescue_action(e)
raise unless ActionView::MissingTemplate === e
end
# methods for test_sweep_after_halted_filter_chain
before_filter :halt_and_redir, :only => "filter_halting_action"
def std_action
@flash_copy = {}.update(flash)
end
def filter_halting_action
@flash_copy = {}.update(flash)
end
def halt_and_redir
flash["foo"] = "bar"
redirect_to :action => "std_action"
@flash_copy = {}.update(flash)
end
def redirect_with_alert
redirect_to '/nowhere', :alert => "Beware the nowheres!"
end
def redirect_with_notice
redirect_to '/somewhere', :notice => "Good luck in the somewheres!"
end
def redirect_with_other_flashes
redirect_to '/wonderland', :flash => { :joyride => "Horses!" }
end
end
tests TestController
def test_flash
get :set_flash
get :use_flash
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "hello", @response.template.assigns["flashy"]
get :use_flash
assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
end
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "hello", @response.template.assigns["flashy"]
get :use_flash
assert_equal "hello", @response.template.assigns["flash_copy"]["that"], "On second flash"
get :use_flash
assert_nil @response.template.assigns["flash_copy"]["that"], "On third flash"
end
def test_flash_now
get :set_flash_now
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "bar" , @response.template.assigns["flash_copy"]["foo"]
assert_equal "hello", @response.template.assigns["flashy"]
get :attempt_to_use_flash_now
assert_nil @response.template.assigns["flash_copy"]["that"]
assert_nil @response.template.assigns["flash_copy"]["foo"]
assert_nil @response.template.assigns["flashy"]
end
def test_update_flash
get :set_flash
get :use_flash_and_update_it
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "hello again", @response.template.assigns["flash_copy"]["this"]
get :use_flash
assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
assert_equal "hello again", @response.template.assigns["flash_copy"]["this"], "On second flash"
end
def test_flash_after_reset_session
get :use_flash_after_reset_session
assert_equal "hello", @response.template.assigns["flashy_that"]
assert_equal "good-bye", @response.template.assigns["flashy_this"]
assert_nil @response.template.assigns["flashy_that_reset"]
end
def test_sweep_after_halted_filter_chain
get :std_action
assert_nil @response.template.assigns["flash_copy"]["foo"]
get :filter_halting_action
assert_equal "bar", @response.template.assigns["flash_copy"]["foo"]
get :std_action # follow redirection
assert_equal "bar", @response.template.assigns["flash_copy"]["foo"]
get :std_action
assert_nil @response.template.assigns["flash_copy"]["foo"]
end
def test_does_not_set_the_session_if_the_flash_is_empty
get :std_action
assert_nil session["flash"]
end
def test_redirect_to_with_alert
get :redirect_with_alert
assert_equal "Beware the nowheres!", @controller.send(:flash)[:alert]
end
def test_redirect_to_with_notice
get :redirect_with_notice
assert_equal "Good luck in the somewheres!", @controller.send(:flash)[:notice]
end
def test_redirect_to_with_other_flashes
get :redirect_with_other_flashes
assert_equal "Horses!", @controller.send(:flash)[:joyride]
end
end

View file

@ -1,14 +0,0 @@
require 'abstract_unit'
class HeaderTest < Test::Unit::TestCase
def setup
@headers = ActionController::Http::Headers.new("HTTP_CONTENT_TYPE"=>"text/plain")
end
def test_content_type_works
assert_equal "text/plain", @headers["Content-Type"]
assert_equal "text/plain", @headers["content-type"]
assert_equal "text/plain", @headers["CONTENT_TYPE"]
assert_equal "text/plain", @headers["HTTP_CONTENT_TYPE"]
end
end

View file

@ -1,224 +0,0 @@
require 'abstract_unit'
ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers'
class TestController < ActionController::Base
attr_accessor :delegate_attr
def delegate_method() end
def rescue_action(e) raise end
end
module Fun
class GamesController < ActionController::Base
def render_hello_world
render :inline => "hello: <%= stratego %>"
end
def rescue_action(e) raise end
end
class PdfController < ActionController::Base
def test
render :inline => "test: <%= foobar %>"
end
def rescue_action(e) raise end
end
end
class ApplicationController < ActionController::Base
helper :all
end
module LocalAbcHelper
def a() end
def b() end
def c() end
end
class HelperTest < Test::Unit::TestCase
def setup
# Increment symbol counter.
@symbol = (@@counter ||= 'A0').succ!.dup
# Generate new controller class.
controller_class_name = "Helper#{@symbol}Controller"
eval("class #{controller_class_name} < TestController; end")
@controller_class = self.class.const_get(controller_class_name)
# Set default test helper.
self.test_helper = LocalAbcHelper
end
def test_deprecated_helper
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised { @controller_class.helper TestHelper }
assert_equal [], missing_methods
end
def test_declare_helper
require 'abc_helper'
self.test_helper = AbcHelper
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised { @controller_class.helper :abc }
assert_equal [], missing_methods
end
def test_declare_missing_helper
assert_equal expected_helper_methods, missing_methods
assert_raise(MissingSourceFile) { @controller_class.helper :missing }
end
def test_declare_missing_file_from_helper
require 'broken_helper'
rescue LoadError => e
assert_nil(/\bbroken_helper\b/.match(e.to_s)[1])
end
def test_helper_block
assert_nothing_raised {
@controller_class.helper { def block_helper_method; end }
}
assert master_helper_methods.include?('block_helper_method')
end
def test_helper_block_include
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised {
@controller_class.helper { include HelperTest::TestHelper }
}
assert_equal [], missing_methods
end
def test_helper_method
assert_nothing_raised { @controller_class.helper_method :delegate_method }
assert master_helper_methods.include?('delegate_method')
end
def test_helper_attr
assert_nothing_raised { @controller_class.helper_attr :delegate_attr }
assert master_helper_methods.include?('delegate_attr')
assert master_helper_methods.include?('delegate_attr=')
end
def test_helper_for_nested_controller
request = ActionController::TestRequest.new
response = ActionController::TestResponse.new
request.action = 'render_hello_world'
assert_equal 'hello: Iz guuut!', Fun::GamesController.process(request, response).body
end
def test_helper_for_acronym_controller
request = ActionController::TestRequest.new
response = ActionController::TestResponse.new
request.action = 'test'
assert_equal 'test: baz', Fun::PdfController.process(request, response).body
end
def test_all_helpers
methods = ApplicationController.master_helper_module.instance_methods.map(&:to_s)
# abc_helper.rb
assert methods.include?('bare_a')
# fun/games_helper.rb
assert methods.include?('stratego')
# fun/pdf_helper.rb
assert methods.include?('foobar')
end
def test_all_helpers_with_alternate_helper_dir
@controller_class.helpers_dir = File.dirname(__FILE__) + '/../fixtures/alternate_helpers'
# Reload helpers
@controller_class.master_helper_module = Module.new
@controller_class.helper :all
# helpers/abc_helper.rb should not be included
assert !master_helper_methods.include?('bare_a')
# alternate_helpers/foo_helper.rb
assert master_helper_methods.include?('baz')
end
def test_helper_proxy
methods = ApplicationController.helpers.methods.map(&:to_s)
# ActionView
assert methods.include?('pluralize')
# abc_helper.rb
assert methods.include?('bare_a')
# fun/games_helper.rb
assert methods.include?('stratego')
# fun/pdf_helper.rb
assert methods.include?('foobar')
end
private
def expected_helper_methods
TestHelper.instance_methods.map(&:to_s)
end
def master_helper_methods
@controller_class.master_helper_module.instance_methods.map(&:to_s)
end
def missing_methods
expected_helper_methods - master_helper_methods
end
def test_helper=(helper_module)
silence_warnings { self.class.const_set('TestHelper', helper_module) }
end
end
class IsolatedHelpersTest < Test::Unit::TestCase
class A < ActionController::Base
def index
render :inline => '<%= shout %>'
end
def rescue_action(e) raise end
end
class B < A
helper { def shout; 'B' end }
def index
render :inline => '<%= shout %>'
end
end
class C < A
helper { def shout; 'C' end }
def index
render :inline => '<%= shout %>'
end
end
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.action = 'index'
end
def test_helper_in_a
assert_raise(NameError) { A.process(@request, @response) }
end
def test_helper_in_b
assert_equal 'B', B.process(@request, @response).body
end
def test_helper_in_c
assert_equal 'C', C.process(@request, @response).body
end
end

View file

@ -1,15 +0,0 @@
require 'abstract_unit'
class CDATANodeTest < Test::Unit::TestCase
def setup
@node = HTML::CDATA.new(nil, 0, 0, "<p>howdy</p>")
end
def test_to_s
assert_equal "<![CDATA[<p>howdy</p>]]>", @node.to_s
end
def test_content
assert_equal "<p>howdy</p>", @node.content
end
end

View file

@ -1,148 +0,0 @@
require 'abstract_unit'
class DocumentTest < Test::Unit::TestCase
def test_handle_doctype
doc = nil
assert_nothing_raised do
doc = HTML::Document.new <<-HTML.strip
<!DOCTYPE "blah" "blah" "blah">
<html>
</html>
HTML
end
assert_equal 3, doc.root.children.length
assert_equal %{<!DOCTYPE "blah" "blah" "blah">}, doc.root.children[0].content
assert_match %r{\s+}m, doc.root.children[1].content
assert_equal "html", doc.root.children[2].name
end
def test_find_img
doc = HTML::Document.new <<-HTML.strip
<html>
<body>
<p><img src="hello.gif"></p>
</body>
</html>
HTML
assert doc.find(:tag=>"img", :attributes=>{"src"=>"hello.gif"})
end
def test_find_all
doc = HTML::Document.new <<-HTML.strip
<html>
<body>
<p class="test"><img src="hello.gif"></p>
<div class="foo">
<p class="test">something</p>
<p>here is <em class="test">more</em></p>
</div>
</body>
</html>
HTML
all = doc.find_all :attributes => { :class => "test" }
assert_equal 3, all.length
assert_equal [ "p", "p", "em" ], all.map { |n| n.name }
end
def test_find_with_text
doc = HTML::Document.new <<-HTML.strip
<html>
<body>
<p>Some text</p>
</body>
</html>
HTML
assert doc.find(:content => "Some text")
assert doc.find(:tag => "p", :child => { :content => "Some text" })
assert doc.find(:tag => "p", :child => "Some text")
assert doc.find(:tag => "p", :content => "Some text")
end
def test_parse_xml
assert_nothing_raised { HTML::Document.new("<tags><tag/></tags>", true, true) }
assert_nothing_raised { HTML::Document.new("<outer><link>something</link></outer>", true, true) }
end
def test_parse_document
doc = HTML::Document.new(<<-HTML)
<div>
<h2>blah</h2>
<table>
</table>
</div>
HTML
assert_not_nil doc.find(:tag => "div", :children => { :count => 1, :only => { :tag => "table" } })
end
def test_tag_nesting_nothing_to_s
doc = HTML::Document.new("<tag></tag>")
assert_equal "<tag></tag>", doc.root.to_s
end
def test_tag_nesting_space_to_s
doc = HTML::Document.new("<tag> </tag>")
assert_equal "<tag> </tag>", doc.root.to_s
end
def test_tag_nesting_text_to_s
doc = HTML::Document.new("<tag>text</tag>")
assert_equal "<tag>text</tag>", doc.root.to_s
end
def test_tag_nesting_tag_to_s
doc = HTML::Document.new("<tag><nested /></tag>")
assert_equal "<tag><nested /></tag>", doc.root.to_s
end
def test_parse_cdata
doc = HTML::Document.new(<<-HTML)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><![CDATA[<br>]]></title>
</head>
<body>
<p>this document has &lt;br&gt; for a title</p>
</body>
</html>
HTML
assert_nil doc.find(:tag => "title", :descendant => { :tag => "br" })
assert doc.find(:tag => "title", :child => "<br>")
end
def test_find_empty_tag
doc = HTML::Document.new("<div id='map'></div>")
assert_nil doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /./)
assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /\A\Z/)
assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /^$/)
assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => "")
assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => nil)
end
def test_parse_invalid_document
assert_nothing_raised do
doc = HTML::Document.new("<html>
<table>
<tr>
<td style=\"color: #FFFFFF; height: 17px; onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" style=\"cursor:pointer; height: 17px;\"; nowrap onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" onmouseout=\"this.bgColor='#0066cc'; this.style.color='#FFFFFF'\" onmouseover=\"this.bgColor='#ffffff'; this.style.color='#0033cc'\">About Us</td>
</tr>
</table>
</html>")
end
end
def test_invalid_document_raises_exception_when_strict
assert_raise RuntimeError do
doc = HTML::Document.new("<html>
<table>
<tr>
<td style=\"color: #FFFFFF; height: 17px; onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" style=\"cursor:pointer; height: 17px;\"; nowrap onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" onmouseout=\"this.bgColor='#0066cc'; this.style.color='#FFFFFF'\" onmouseover=\"this.bgColor='#ffffff'; this.style.color='#0033cc'\">About Us</td>
</tr>
</table>
</html>", true)
end
end
end

View file

@ -1,89 +0,0 @@
require 'abstract_unit'
class NodeTest < Test::Unit::TestCase
class MockNode
def initialize(matched, value)
@matched = matched
@value = value
end
def find(conditions)
@matched && self
end
def to_s
@value.to_s
end
end
def setup
@node = HTML::Node.new("parent")
@node.children.concat [MockNode.new(false,1), MockNode.new(true,"two"), MockNode.new(false,:three)]
end
def test_match
assert !@node.match("foo")
end
def test_tag
assert !@node.tag?
end
def test_to_s
assert_equal "1twothree", @node.to_s
end
def test_find
assert_equal "two", @node.find('blah').to_s
end
def test_parse_strict
s = "<b foo='hello'' bar='baz'>"
assert_raise(RuntimeError) { HTML::Node.parse(nil,0,0,s) }
end
def test_parse_relaxed
s = "<b foo='hello'' bar='baz'>"
node = nil
assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
assert node.attributes.has_key?("foo")
assert !node.attributes.has_key?("bar")
end
def test_to_s_with_boolean_attrs
s = "<b foo bar>"
node = HTML::Node.parse(nil,0,0,s)
assert node.attributes.has_key?("foo")
assert node.attributes.has_key?("bar")
assert "<b foo bar>", node.to_s
end
def test_parse_with_unclosed_tag
s = "<span onmouseover='bang'"
node = nil
assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
assert node.attributes.has_key?("onmouseover")
end
def test_parse_with_valid_cdata_section
s = "<![CDATA[<span>contents</span>]]>"
node = nil
assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
assert_kind_of HTML::CDATA, node
assert_equal '<span>contents</span>', node.content
end
def test_parse_strict_with_unterminated_cdata_section
s = "<![CDATA[neverending..."
assert_raise(RuntimeError) { HTML::Node.parse(nil,0,0,s) }
end
def test_parse_relaxed_with_unterminated_cdata_section
s = "<![CDATA[neverending..."
node = nil
assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
assert_kind_of HTML::CDATA, node
assert_equal 'neverending...', node.content
end
end

View file

@ -1,274 +0,0 @@
require 'abstract_unit'
class SanitizerTest < ActionController::TestCase
def setup
@sanitizer = nil # used by assert_sanitizer
end
def test_strip_tags
sanitizer = HTML::FullSanitizer.new
assert_equal("<<<bad html", sanitizer.sanitize("<<<bad html"))
assert_equal("<<", sanitizer.sanitize("<<<bad html>"))
assert_equal("Dont touch me", sanitizer.sanitize("Dont touch me"))
assert_equal("This is a test.", sanitizer.sanitize("<p>This <u>is<u> a <a href='test.html'><strong>test</strong></a>.</p>"))
assert_equal("Weirdos", sanitizer.sanitize("Wei<<a>a onclick='alert(document.cookie);'</a>/>rdos"))
assert_equal("This is a test.", sanitizer.sanitize("This is a test."))
assert_equal(
%{This is a test.\n\n\nIt no longer contains any HTML.\n}, sanitizer.sanitize(
%{<title>This is <b>a <a href="" target="_blank">test</a></b>.</title>\n\n<!-- it has a comment -->\n\n<p>It no <b>longer <strong>contains <em>any <strike>HTML</strike></em>.</strong></b></p>\n}))
assert_equal "This has a here.", sanitizer.sanitize("This has a <!-- comment --> here.")
assert_equal "This has a here.", sanitizer.sanitize("This has a <![CDATA[<section>]]> here.")
assert_equal "This has an unclosed ", sanitizer.sanitize("This has an unclosed <![CDATA[<section>]] here...")
assert_equal "non printable char is a tag", sanitizer.sanitize("<\x07a href='/hello'>non printable char is a tag</a>")
[nil, '', ' '].each { |blank| assert_equal blank, sanitizer.sanitize(blank) }
end
def test_strip_links
sanitizer = HTML::LinkSanitizer.new
assert_equal "Dont touch me", sanitizer.sanitize("Dont touch me")
assert_equal "on my mind\nall day long", sanitizer.sanitize("<a href='almost'>on my mind</a>\n<A href='almost'>all day long</A>")
assert_equal "0wn3d", sanitizer.sanitize("<a href='http://www.rubyonrails.com/'><a href='http://www.rubyonrails.com/' onlclick='steal()'>0wn3d</a></a>")
assert_equal "Magic", sanitizer.sanitize("<a href='http://www.rubyonrails.com/'>Mag<a href='http://www.ruby-lang.org/'>ic")
assert_equal "FrrFox", sanitizer.sanitize("<href onlclick='steal()'>FrrFox</a></href>")
assert_equal "My mind\nall <b>day</b> long", sanitizer.sanitize("<a href='almost'>My mind</a>\n<A href='almost'>all <b>day</b> long</A>")
assert_equal "all <b>day</b> long", sanitizer.sanitize("<<a>a href='hello'>all <b>day</b> long<</A>/a>")
assert_equal "<a<a", sanitizer.sanitize("<a<a")
end
def test_sanitize_form
assert_sanitized "<form action=\"/foo/bar\" method=\"post\"><input></form>", ''
end
def test_sanitize_plaintext
raw = "<plaintext><span>foo</span></plaintext>"
assert_sanitized raw, "<span>foo</span>"
end
def test_sanitize_script
assert_sanitized "a b c<script language=\"Javascript\">blah blah blah</script>d e f", "a b cd e f"
end
# fucked
def test_sanitize_js_handlers
raw = %{onthis="do that" <a href="#" onclick="hello" name="foo" onbogus="remove me">hello</a>}
assert_sanitized raw, %{onthis="do that" <a name="foo" href="#">hello</a>}
end
def test_sanitize_javascript_href
raw = %{href="javascript:bang" <a href="javascript:bang" name="hello">foo</a>, <span href="javascript:bang">bar</span>}
assert_sanitized raw, %{href="javascript:bang" <a name="hello">foo</a>, <span>bar</span>}
end
def test_sanitize_image_src
raw = %{src="javascript:bang" <img src="javascript:bang" width="5">foo</img>, <span src="javascript:bang">bar</span>}
assert_sanitized raw, %{src="javascript:bang" <img width="5">foo</img>, <span>bar</span>}
end
HTML::WhiteListSanitizer.allowed_tags.each do |tag_name|
define_method "test_should_allow_#{tag_name}_tag" do
assert_sanitized "start <#{tag_name} title=\"1\" onclick=\"foo\">foo <bad>bar</bad> baz</#{tag_name}> end", %(start <#{tag_name} title="1">foo bar baz</#{tag_name}> end)
end
end
def test_should_allow_anchors
assert_sanitized %(<a href="foo" onclick="bar"><script>baz</script></a>), %(<a href="foo"></a>)
end
# RFC 3986, sec 4.2
def test_allow_colons_in_path_component
assert_sanitized("<a href=\"./this:that\">foo</a>")
end
%w(src width height alt).each do |img_attr|
define_method "test_should_allow_image_#{img_attr}_attribute" do
assert_sanitized %(<img #{img_attr}="foo" onclick="bar" />), %(<img #{img_attr}="foo" />)
end
end
def test_should_handle_non_html
assert_sanitized 'abc'
end
def test_should_handle_blank_text
assert_sanitized nil
assert_sanitized ''
end
def test_should_allow_custom_tags
text = "<u>foo</u>"
sanitizer = HTML::WhiteListSanitizer.new
assert_equal(text, sanitizer.sanitize(text, :tags => %w(u)))
end
def test_should_allow_only_custom_tags
text = "<u>foo</u> with <i>bar</i>"
sanitizer = HTML::WhiteListSanitizer.new
assert_equal("<u>foo</u> with bar", sanitizer.sanitize(text, :tags => %w(u)))
end
def test_should_allow_custom_tags_with_attributes
text = %(<blockquote cite="http://example.com/">foo</blockquote>)
sanitizer = HTML::WhiteListSanitizer.new
assert_equal(text, sanitizer.sanitize(text))
end
def test_should_allow_custom_tags_with_custom_attributes
text = %(<blockquote foo="bar">Lorem ipsum</blockquote>)
sanitizer = HTML::WhiteListSanitizer.new
assert_equal(text, sanitizer.sanitize(text, :attributes => ['foo']))
end
[%w(img src), %w(a href)].each do |(tag, attr)|
define_method "test_should_strip_#{attr}_attribute_in_#{tag}_with_bad_protocols" do
assert_sanitized %(<#{tag} #{attr}="javascript:bang" title="1">boo</#{tag}>), %(<#{tag} title="1">boo</#{tag}>)
end
end
def test_should_flag_bad_protocols
sanitizer = HTML::WhiteListSanitizer.new
%w(about chrome data disk hcp help javascript livescript lynxcgi lynxexec ms-help ms-its mhtml mocha opera res resource shell vbscript view-source vnd.ms.radio wysiwyg).each do |proto|
assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad")
end
end
def test_should_accept_good_protocols
sanitizer = HTML::WhiteListSanitizer.new
HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://good")
end
end
def test_should_reject_hex_codes_in_protocol
assert_sanitized %(<a href="&#37;6A&#37;61&#37;76&#37;61&#37;73&#37;63&#37;72&#37;69&#37;70&#37;74&#37;3A&#37;61&#37;6C&#37;65&#37;72&#37;74&#37;28&#37;22&#37;58&#37;53&#37;53&#37;22&#37;29">1</a>), "<a>1</a>"
assert @sanitizer.send(:contains_bad_protocols?, 'src', "%6A%61%76%61%73%63%72%69%70%74%3A%61%6C%65%72%74%28%22%58%53%53%22%29")
end
def test_should_block_script_tag
assert_sanitized %(<SCRIPT\nSRC=http://ha.ckers.org/xss.js></SCRIPT>), ""
end
[%(<IMG SRC="javascript:alert('XSS');">),
%(<IMG SRC=javascript:alert('XSS')>),
%(<IMG SRC=JaVaScRiPt:alert('XSS')>),
%(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">),
%(<IMG SRC=javascript:alert(&quot;XSS&quot;)>),
%(<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>),
%(<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>),
%(<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>),
%(<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>),
%(<IMG SRC="jav\tascript:alert('XSS');">),
%(<IMG SRC="jav&#x09;ascript:alert('XSS');">),
%(<IMG SRC="jav&#x0A;ascript:alert('XSS');">),
%(<IMG SRC="jav&#x0D;ascript:alert('XSS');">),
%(<IMG SRC=" &#14; javascript:alert('XSS');">),
%(<IMG SRC=`javascript:alert("RSnake says, 'XSS'")`>)].each_with_index do |img_hack, i|
define_method "test_should_not_fall_for_xss_image_hack_#{i+1}" do
assert_sanitized img_hack, "<img>"
end
end
def test_should_sanitize_tag_broken_up_by_null
assert_sanitized %(<SCR\0IPT>alert(\"XSS\")</SCR\0IPT>), "alert(\"XSS\")"
end
def test_should_sanitize_invalid_script_tag
assert_sanitized %(<SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT>), ""
end
def test_should_sanitize_script_tag_with_multiple_open_brackets
assert_sanitized %(<<SCRIPT>alert("XSS");//<</SCRIPT>), "&lt;"
assert_sanitized %(<iframe src=http://ha.ckers.org/scriptlet.html\n<a), %(&lt;a)
end
def test_should_sanitize_unclosed_script
assert_sanitized %(<SCRIPT SRC=http://ha.ckers.org/xss.js?<B>), "<b>"
end
def test_should_sanitize_half_open_scripts
assert_sanitized %(<IMG SRC="javascript:alert('XSS')"), "<img>"
end
def test_should_not_fall_for_ridiculous_hack
img_hack = %(<IMG\nSRC\n=\n"\nj\na\nv\na\ns\nc\nr\ni\np\nt\n:\na\nl\ne\nr\nt\n(\n'\nX\nS\nS\n'\n)\n"\n>)
assert_sanitized img_hack, "<img>"
end
# fucked
def test_should_sanitize_attributes
assert_sanitized %(<SPAN title="'><script>alert()</script>">blah</SPAN>), %(<span title="'&gt;&lt;script&gt;alert()&lt;/script&gt;">blah</span>)
end
def test_should_sanitize_illegal_style_properties
raw = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;)
expected = %(display: block; width: 100%; height: 100%; background-color: black; background-image: ; background-x: center; background-y: center;)
assert_equal expected, sanitize_css(raw)
end
def test_should_sanitize_with_trailing_space
raw = "display:block; "
expected = "display: block;"
assert_equal expected, sanitize_css(raw)
end
def test_should_sanitize_xul_style_attributes
raw = %(-moz-binding:url('http://ha.ckers.org/xssmoz.xml#xss'))
assert_equal '', sanitize_css(raw)
end
def test_should_sanitize_invalid_tag_names
assert_sanitized(%(a b c<script/XSS src="http://ha.ckers.org/xss.js"></script>d e f), "a b cd e f")
end
def test_should_sanitize_non_alpha_and_non_digit_characters_in_tags
assert_sanitized('<a onclick!#$%&()*~+-_.,:;?@[/|\]^`=alert("XSS")>foo</a>', "<a>foo</a>")
end
def test_should_sanitize_invalid_tag_names_in_single_tags
assert_sanitized('<img/src="http://ha.ckers.org/xss.js"/>', "<img />")
end
def test_should_sanitize_img_dynsrc_lowsrc
assert_sanitized(%(<img lowsrc="javascript:alert('XSS')" />), "<img />")
end
def test_should_sanitize_div_background_image_unicode_encoded
raw = %(background-image:\0075\0072\006C\0028'\006a\0061\0076\0061\0073\0063\0072\0069\0070\0074\003a\0061\006c\0065\0072\0074\0028.1027\0058.1053\0053\0027\0029'\0029)
assert_equal '', sanitize_css(raw)
end
def test_should_sanitize_div_style_expression
raw = %(width: expression(alert('XSS'));)
assert_equal '', sanitize_css(raw)
end
def test_should_sanitize_img_vbscript
assert_sanitized %(<img src='vbscript:msgbox("XSS")' />), '<img />'
end
def test_should_sanitize_cdata_section
assert_sanitized "<![CDATA[<span>section</span>]]>", "&lt;![CDATA[&lt;span>section&lt;/span>]]>"
end
def test_should_sanitize_unterminated_cdata_section
assert_sanitized "<![CDATA[<span>neverending...", "&lt;![CDATA[&lt;span>neverending...]]>"
end
def test_should_not_mangle_urls_with_ampersand
assert_sanitized %{<a href=\"http://www.domain.com?var1=1&amp;var2=2\">my link</a>}
end
protected
def assert_sanitized(input, expected = nil)
@sanitizer ||= HTML::WhiteListSanitizer.new
if input
assert_dom_equal expected || input, @sanitizer.sanitize(input)
else
assert_nil @sanitizer.sanitize(input)
end
end
def sanitize_css(input)
(@sanitizer ||= HTML::WhiteListSanitizer.new).sanitize_css(input)
end
end

View file

@ -1,238 +0,0 @@
require 'abstract_unit'
class TagNodeTest < Test::Unit::TestCase
def test_open_without_attributes
node = tag("<tag>")
assert_equal "tag", node.name
assert_equal Hash.new, node.attributes
assert_nil node.closing
end
def test_open_with_attributes
node = tag("<TAG1 foo=hey_ho x:bar=\"blah blah\" BAZ='blah blah blah' >")
assert_equal "tag1", node.name
assert_equal "hey_ho", node["foo"]
assert_equal "blah blah", node["x:bar"]
assert_equal "blah blah blah", node["baz"]
end
def test_self_closing_without_attributes
node = tag("<tag/>")
assert_equal "tag", node.name
assert_equal Hash.new, node.attributes
assert_equal :self, node.closing
end
def test_self_closing_with_attributes
node = tag("<tag a=b/>")
assert_equal "tag", node.name
assert_equal( { "a" => "b" }, node.attributes )
assert_equal :self, node.closing
end
def test_closing_without_attributes
node = tag("</tag>")
assert_equal "tag", node.name
assert_nil node.attributes
assert_equal :close, node.closing
end
def test_bracket_op_when_no_attributes
node = tag("</tag>")
assert_nil node["foo"]
end
def test_bracket_op_when_attributes
node = tag("<tag a=b/>")
assert_equal "b", node["a"]
end
def test_attributes_with_escaped_quotes
node = tag("<tag a='b\\'c' b=\"bob \\\"float\\\"\">")
assert_equal "b\\'c", node["a"]
assert_equal "bob \\\"float\\\"", node["b"]
end
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
end
def test_tag
assert tag("<tag>").tag?
end
def test_match_tag_as_string
assert tag("<tag>").match(:tag => "tag")
assert !tag("<tag>").match(:tag => "b")
end
def test_match_tag_as_regexp
assert tag("<tag>").match(:tag => /t.g/)
assert !tag("<tag>").match(:tag => /t[bqs]g/)
end
def test_match_attributes_as_string
t = tag("<tag a=something b=else />")
assert t.match(:attributes => {"a" => "something"})
assert t.match(:attributes => {"b" => "else"})
end
def test_match_attributes_as_regexp
t = tag("<tag a=something b=else />")
assert t.match(:attributes => {"a" => /^something$/})
assert t.match(:attributes => {"b" => /e.*e/})
assert t.match(:attributes => {"a" => /me..i/, "b" => /.ls.$/})
end
def test_match_attributes_as_number
t = tag("<tag a=15 b=3.1415 />")
assert t.match(:attributes => {"a" => 15})
assert t.match(:attributes => {"b" => 3.1415})
assert t.match(:attributes => {"a" => 15, "b" => 3.1415})
end
def test_match_attributes_exist
t = tag("<tag a=15 b=3.1415 />")
assert t.match(:attributes => {"a" => true})
assert t.match(:attributes => {"b" => true})
assert t.match(:attributes => {"a" => true, "b" => true})
end
def test_match_attributes_not_exist
t = tag("<tag a=15 b=3.1415 />")
assert t.match(:attributes => {"c" => false})
assert t.match(:attributes => {"c" => nil})
assert t.match(:attributes => {"a" => true, "c" => false})
end
def test_match_parent_success
t = tag("<tag a=15 b='hello'>", tag("<foo k='value'>"))
assert t.match(:parent => {:tag => "foo", :attributes => {"k" => /v.l/, "j" => false}})
end
def test_match_parent_fail
t = tag("<tag a=15 b='hello'>", tag("<foo k='value'>"))
assert !t.match(:parent => {:tag => /kafka/})
end
def test_match_child_success
t = tag("<tag x:k='something'>")
tag("<child v=john a=kelly>", t)
tag("<sib m=vaughn v=james>", t)
assert t.match(:child => { :tag => "sib", :attributes => {"v" => /j/}})
assert t.match(:child => { :attributes => {"a" => "kelly"}})
end
def test_match_child_fail
t = tag("<tag x:k='something'>")
tag("<child v=john a=kelly>", t)
tag("<sib m=vaughn v=james>", t)
assert !t.match(:child => { :tag => "sib", :attributes => {"v" => /r/}})
assert !t.match(:child => { :attributes => {"v" => false}})
end
def test_match_ancestor_success
t = tag("<tag x:k='something'>", tag("<parent v=john a=kelly>", tag("<grandparent m=vaughn v=james>")))
assert t.match(:ancestor => {:tag => "parent", :attributes => {"a" => /ll/}})
assert t.match(:ancestor => {:attributes => {"m" => "vaughn"}})
end
def test_match_ancestor_fail
t = tag("<tag x:k='something'>", tag("<parent v=john a=kelly>", tag("<grandparent m=vaughn v=james>")))
assert !t.match(:ancestor => {:tag => /^parent/, :attributes => {"v" => /m/}})
assert !t.match(:ancestor => {:attributes => {"v" => false}})
end
def test_match_descendant_success
tag("<grandchild m=vaughn v=james>", tag("<child v=john a=kelly>", t = tag("<tag x:k='something'>")))
assert t.match(:descendant => {:tag => "child", :attributes => {"a" => /ll/}})
assert t.match(:descendant => {:attributes => {"m" => "vaughn"}})
end
def test_match_descendant_fail
tag("<grandchild m=vaughn v=james>", tag("<child v=john a=kelly>", t = tag("<tag x:k='something'>")))
assert !t.match(:descendant => {:tag => /^child/, :attributes => {"v" => /m/}})
assert !t.match(:descendant => {:attributes => {"v" => false}})
end
def test_match_child_count
t = tag("<tag x:k='something'>")
tag("hello", t)
tag("<child v=john a=kelly>", t)
tag("<sib m=vaughn v=james>", t)
assert t.match(:children => { :count => 2 })
assert t.match(:children => { :count => 2..4 })
assert t.match(:children => { :less_than => 4 })
assert t.match(:children => { :greater_than => 1 })
assert !t.match(:children => { :count => 3 })
end
def test_conditions_as_strings
t = tag("<tag x:k='something'>")
assert t.match("tag" => "tag")
assert t.match("attributes" => { "x:k" => "something" })
assert !t.match("tag" => "gat")
assert !t.match("attributes" => { "x:j" => "something" })
end
def test_attributes_as_symbols
t = tag("<child v=john a=kelly>")
assert t.match(:attributes => { :v => /oh/ })
assert t.match(:attributes => { :a => /ll/ })
end
def test_match_sibling
t = tag("<tag x:k='something'>")
tag("hello", t)
tag("<span a=b>", t)
tag("world", t)
m = tag("<span k=r>", t)
tag("<span m=l>", t)
assert m.match(:sibling => {:tag => "span", :attributes => {:a => true}})
assert m.match(:sibling => {:tag => "span", :attributes => {:m => true}})
assert !m.match(:sibling => {:tag => "span", :attributes => {:k => true}})
end
def test_match_sibling_before
t = tag("<tag x:k='something'>")
tag("hello", t)
tag("<span a=b>", t)
tag("world", t)
m = tag("<span k=r>", t)
tag("<span m=l>", t)
assert m.match(:before => {:tag => "span", :attributes => {:m => true}})
assert !m.match(:before => {:tag => "span", :attributes => {:a => true}})
assert !m.match(:before => {:tag => "span", :attributes => {:k => true}})
end
def test_match_sibling_after
t = tag("<tag x:k='something'>")
tag("hello", t)
tag("<span a=b>", t)
tag("world", t)
m = tag("<span k=r>", t)
tag("<span m=l>", t)
assert m.match(:after => {:tag => "span", :attributes => {:a => true}})
assert !m.match(:after => {:tag => "span", :attributes => {:m => true}})
assert !m.match(:after => {:tag => "span", :attributes => {:k => true}})
end
def test_to_s
t = tag("<b x='foo'>")
tag("hello", t)
tag("<hr />", t)
assert_equal %(<b x="foo">hello<hr /></b>), t.to_s
end
private
def tag(content, parent=nil)
node = HTML::Node.parse(parent,0,0,content)
parent.children << node if parent
node
end
end

View file

@ -1,50 +0,0 @@
require 'abstract_unit'
class TextNodeTest < Test::Unit::TestCase
def setup
@node = HTML::Text.new(nil, 0, 0, "hello, howdy, aloha, annyeong")
end
def test_to_s
assert_equal "hello, howdy, aloha, annyeong", @node.to_s
end
def test_find_string
assert_equal @node, @node.find("hello, howdy, aloha, annyeong")
assert_equal false, @node.find("bogus")
end
def test_find_regexp
assert_equal @node, @node.find(/an+y/)
assert_nil @node.find(/b/)
end
def test_find_hash
assert_equal @node, @node.find(:content => /howdy/)
assert_nil @node.find(:content => /^howdy$/)
assert_equal false, @node.find(:content => "howdy")
end
def test_find_other
assert_nil @node.find(:hello)
end
def test_match_string
assert @node.match("hello, howdy, aloha, annyeong")
assert_equal false, @node.match("bogus")
end
def test_match_regexp
assert_not_nil @node, @node.match(/an+y/)
assert_nil @node.match(/b/)
end
def test_match_hash
assert_not_nil @node, @node.match(:content => "howdy")
assert_nil @node.match(:content => /^howdy$/)
end
def test_match_other
assert_nil @node.match(:hello)
end
end

View file

@ -1,131 +0,0 @@
require 'abstract_unit'
class TokenizerTest < Test::Unit::TestCase
def test_blank
tokenize ""
assert_end
end
def test_space
tokenize " "
assert_next " "
assert_end
end
def test_tag_simple_open
tokenize "<tag>"
assert_next "<tag>"
assert_end
end
def test_tag_simple_self_closing
tokenize "<tag />"
assert_next "<tag />"
assert_end
end
def test_tag_simple_closing
tokenize "</tag>"
assert_next "</tag>"
end
def test_tag_with_single_quoted_attribute
tokenize %{<tag a='hello'>x}
assert_next %{<tag a='hello'>}
end
def test_tag_with_single_quoted_attribute_with_escape
tokenize %{<tag a='hello\\''>x}
assert_next %{<tag a='hello\\''>}
end
def test_tag_with_double_quoted_attribute
tokenize %{<tag a="hello">x}
assert_next %{<tag a="hello">}
end
def test_tag_with_double_quoted_attribute_with_escape
tokenize %{<tag a="hello\\"">x}
assert_next %{<tag a="hello\\"">}
end
def test_tag_with_unquoted_attribute
tokenize %{<tag a=hello>x}
assert_next %{<tag a=hello>}
end
def test_tag_with_lt_char_in_attribute
tokenize %{<tag a="x < y">x}
assert_next %{<tag a="x < y">}
end
def test_tag_with_gt_char_in_attribute
tokenize %{<tag a="x > y">x}
assert_next %{<tag a="x > y">}
end
def test_doctype_tag
tokenize %{<!DOCTYPE "blah" "blah" "blah">\n <html>}
assert_next %{<!DOCTYPE "blah" "blah" "blah">}
assert_next %{\n }
assert_next %{<html>}
end
def test_cdata_tag
tokenize %{<![CDATA[<br>]]>}
assert_next %{<![CDATA[<br>]]>}
assert_end
end
def test_unterminated_cdata_tag
tokenize %{<content:encoded><![CDATA[ neverending...}
assert_next %{<content:encoded>}
assert_next %{<![CDATA[ neverending...}
assert_end
end
def test_less_than_with_space
tokenize %{original < hello > world}
assert_next %{original }
assert_next %{< hello > world}
end
def test_less_than_without_matching_greater_than
tokenize %{hello <span onmouseover="gotcha"\n<b>foo</b>\nbar</span>}
assert_next %{hello }
assert_next %{<span onmouseover="gotcha"\n}
assert_next %{<b>}
assert_next %{foo}
assert_next %{</b>}
assert_next %{\nbar}
assert_next %{</span>}
assert_end
end
def test_unterminated_comment
tokenize %{hello <!-- neverending...}
assert_next %{hello }
assert_next %{<!-- neverending...}
assert_end
end
private
def tokenize(text)
@tokenizer = HTML::Tokenizer.new(text)
end
def assert_next(expected, message=nil)
token = @tokenizer.next
assert_equal expected, token, message
end
def assert_sequence(*expected)
assert_next expected.shift until expected.empty?
end
def assert_end(message=nil)
assert_nil @tokenizer.next, message
end
end

View file

@ -1,113 +0,0 @@
require 'abstract_unit'
class HttpBasicAuthenticationTest < ActionController::TestCase
class DummyController < ActionController::Base
before_filter :authenticate, :only => :index
before_filter :authenticate_with_request, :only => :display
before_filter :authenticate_long_credentials, :only => :show
def index
render :text => "Hello Secret"
end
def display
render :text => 'Definitely Maybe'
end
def show
render :text => 'Only for loooooong credentials'
end
private
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == 'lifo' && password == 'world'
end
end
def authenticate_with_request
if authenticate_with_http_basic { |username, password| username == 'pretty' && password == 'please' }
@logged_in = true
else
request_http_basic_authentication("SuperSecret")
end
end
def authenticate_long_credentials
authenticate_or_request_with_http_basic do |username, password|
username == '1234567890123456789012345678901234567890' && password == '1234567890123456789012345678901234567890'
end
end
end
AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
tests DummyController
AUTH_HEADERS.each do |header|
test "successful authentication with #{header.downcase}" do
@request.env[header] = encode_credentials('lifo', 'world')
get :index
assert_response :success
assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
end
test "successful authentication with #{header.downcase} and long credentials" do
@request.env[header] = encode_credentials('1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890')
get :show
assert_response :success
assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials"
end
end
AUTH_HEADERS.each do |header|
test "unsuccessful authentication with #{header.downcase}" do
@request.env[header] = encode_credentials('h4x0r', 'world')
get :index
assert_response :unauthorized
assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
end
test "unsuccessful authentication with #{header.downcase} and long credentials" do
@request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r', 'worldworldworldworldworldworldworldworld')
get :show
assert_response :unauthorized
assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials"
end
end
test "authentication request without credential" do
get :display
assert_response :unauthorized
assert_equal "HTTP Basic: Access denied.\n", @response.body
assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
end
test "authentication request with invalid credential" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'foo')
get :display
assert_response :unauthorized
assert_equal "HTTP Basic: Access denied.\n", @response.body
assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
end
test "authentication request with valid credential" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'please')
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
private
def encode_credentials(username, password)
"Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}"
end
end

View file

@ -1,254 +0,0 @@
require 'abstract_unit'
class HttpDigestAuthenticationTest < ActionController::TestCase
class DummyDigestController < ActionController::Base
before_filter :authenticate, :only => :index
before_filter :authenticate_with_request, :only => :display
USERS = { 'lifo' => 'world', 'pretty' => 'please',
'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))}
def index
render :text => "Hello Secret"
end
def display
render :text => 'Definitely Maybe'
end
private
def authenticate
authenticate_or_request_with_http_digest("SuperSecret") do |username|
# Return the password
USERS[username]
end
end
def authenticate_with_request
if authenticate_with_http_digest("SuperSecret") { |username| USERS[username] }
@logged_in = true
else
request_http_digest_authentication("SuperSecret", "Authentication Failed")
end
end
end
AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
tests DummyDigestController
AUTH_HEADERS.each do |header|
test "successful authentication with #{header.downcase}" do
@request.env[header] = encode_credentials(:username => 'lifo', :password => 'world')
get :index
assert_response :success
assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
end
end
AUTH_HEADERS.each do |header|
test "unsuccessful authentication with #{header.downcase}" do
@request.env[header] = encode_credentials(:username => 'h4x0r', :password => 'world')
get :index
assert_response :unauthorized
assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
end
end
test "authentication request without credential" do
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
credentials = decode_credentials(@response.headers['WWW-Authenticate'])
assert_equal 'SuperSecret', credentials[:realm]
end
test "authentication request with nil credentials" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil)
get :index
assert_response :unauthorized
assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request"
assert_not_equal 'Hello Secret', @response.body, "Authentication didn't fail for request"
end
test "authentication request with invalid password" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo')
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with invalid nonce" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :nonce => "xxyyzz")
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with missing nonce should return 401" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :remove_nonce => true)
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with Basic auth credentials should return 401" do
ActionController::Base.session_options[:secret] = "session_options_secret"
@request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials('pretty', 'please')
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with invalid opaque" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :opaque => "xxyyzz")
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with invalid realm" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :realm => "NotSecret")
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with valid credential" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with valid credential and nil session" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
# session_id = "" in functional test, but is +nil+ in real life
@request.session.session_id = nil
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with request-uri that doesn't match credentials digest-uri" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
@request.env['REQUEST_URI'] = "/http_digest_authentication_test/dummy_digest/altered/uri"
get :display
assert_response :unauthorized
assert_equal "Authentication Failed", @response.body
end
test "authentication request with absolute request uri (as in webrick)" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
@request.env['REQUEST_URI'] = "http://test.host/http_digest_authentication_test/dummy_digest"
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with absolute uri in credentials (as in IE)" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest",
:username => 'pretty', :password => 'please')
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with absolute uri in both request and credentials (as in Webrick with IE)" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest",
:username => 'pretty', :password => 'please')
@request.env['REQUEST_URI'] = "http://test.host/http_digest_authentication_test/dummy_digest"
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with password stored as ha1 digest hash" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'dhh',
:password => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":")),
:password_is_ha1 => true)
get :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "authentication request with _method" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :method => :post)
@request.env['rack.methodoverride.original_method'] = 'POST'
put :display
assert_response :success
assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
test "validate_digest_response should fail with nil returning password_procedure" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil)
assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret"){nil}
end
private
def encode_credentials(options)
options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false)
password = options.delete(:password)
# Set in /initializers/session_store.rb. Used as secret in generating nonce
# to prevent tampering of timestamp
ActionController::Base.session_options[:secret] = "session_options_secret"
# Perform unauthenticated request to retrieve digest parameters to use on subsequent request
method = options.delete(:method) || 'GET'
case method.to_s.upcase
when 'GET'
get :index
when 'POST'
post :index
end
assert_response :unauthorized
remove_nonce = options.delete(:remove_nonce)
credentials = decode_credentials(@response.headers['WWW-Authenticate'])
credentials.merge!(options)
credentials.merge!(:uri => @request.env['REQUEST_URI'].to_s)
credentials.delete(:nonce) if remove_nonce
ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1])
end
def decode_credentials(header)
ActionController::HttpAuthentication::Digest.decode_credentials(@response.headers['WWW-Authenticate'])
end
end

View file

@ -1,508 +0,0 @@
require 'abstract_unit'
class SessionTest < Test::Unit::TestCase
StubApp = lambda { |env|
[200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]]
}
def setup
@session = ActionController::Integration::Session.new(StubApp)
end
def test_https_bang_works_and_sets_truth_by_default
assert !@session.https?
@session.https!
assert @session.https?
@session.https! false
assert !@session.https?
end
def test_host!
assert_not_equal "glu.ttono.us", @session.host
@session.host! "rubyonrails.com"
assert_equal "rubyonrails.com", @session.host
end
def test_follow_redirect_raises_when_no_redirect
@session.stubs(:redirect?).returns(false)
assert_raise(RuntimeError) { @session.follow_redirect! }
end
def test_request_via_redirect_uses_given_method
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
@session.expects(:put).with(path, args, headers)
@session.stubs(:redirect?).returns(false)
@session.request_via_redirect(:put, path, args, headers)
end
def test_request_via_redirect_follows_redirects
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
@session.stubs(:redirect?).returns(true, true, false)
@session.expects(:follow_redirect!).times(2)
@session.request_via_redirect(:get, path, args, headers)
end
def test_request_via_redirect_returns_status
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
@session.stubs(:redirect?).returns(false)
@session.stubs(:status).returns(200)
assert_equal 200, @session.request_via_redirect(:get, path, args, headers)
end
def test_get_via_redirect
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:get, path, args, headers)
@session.get_via_redirect(path, args, headers)
end
def test_post_via_redirect
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:post, path, args, headers)
@session.post_via_redirect(path, args, headers)
end
def test_put_via_redirect
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:put, path, args, headers)
@session.put_via_redirect(path, args, headers)
end
def test_delete_via_redirect
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:delete, path, args, headers)
@session.delete_via_redirect(path, args, headers)
end
def test_url_for_with_controller
options = {:action => 'show'}
mock_controller = mock()
mock_controller.expects(:url_for).with(options).returns('/show')
@session.stubs(:controller).returns(mock_controller)
assert_equal '/show', @session.url_for(options)
end
def test_url_for_without_controller
options = {:action => 'show'}
mock_rewriter = mock()
mock_rewriter.expects(:rewrite).with(options).returns('/show')
@session.stubs(:generic_url_rewriter).returns(mock_rewriter)
@session.stubs(:controller).returns(nil)
assert_equal '/show', @session.url_for(options)
end
def test_redirect_bool_with_status_in_300s
@session.stubs(:status).returns 301
assert @session.redirect?
end
def test_redirect_bool_with_status_in_200s
@session.stubs(:status).returns 200
assert !@session.redirect?
end
def test_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:get,path,params,headers)
@session.get(path,params,headers)
end
def test_post
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:post,path,params,headers)
@session.post(path,params,headers)
end
def test_put
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:put,path,params,headers)
@session.put(path,params,headers)
end
def test_delete
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:delete,path,params,headers)
@session.delete(path,params,headers)
end
def test_head
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:head,path,params,headers)
@session.head(path,params,headers)
end
def test_xml_http_request_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
"X-Requested-With" => "XMLHttpRequest",
"Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:get,path,params,headers_after_xhr)
@session.xml_http_request(:get,path,params,headers)
end
def test_xml_http_request_post
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
"X-Requested-With" => "XMLHttpRequest",
"Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:post,path,params,headers_after_xhr)
@session.xml_http_request(:post,path,params,headers)
end
def test_xml_http_request_put
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
"X-Requested-With" => "XMLHttpRequest",
"Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:put,path,params,headers_after_xhr)
@session.xml_http_request(:put,path,params,headers)
end
def test_xml_http_request_delete
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
"X-Requested-With" => "XMLHttpRequest",
"Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:delete,path,params,headers_after_xhr)
@session.xml_http_request(:delete,path,params,headers)
end
def test_xml_http_request_head
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
"X-Requested-With" => "XMLHttpRequest",
"Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:head,path,params,headers_after_xhr)
@session.xml_http_request(:head,path,params,headers)
end
def test_xml_http_request_override_accept
path = "/index"; params = "blah"; headers = {:location => 'blah', "Accept" => "application/xml"}
headers_after_xhr = headers.merge(
"X-Requested-With" => "XMLHttpRequest"
)
@session.expects(:process).with(:post,path,params,headers_after_xhr)
@session.xml_http_request(:post,path,params,headers)
end
end
class IntegrationTestTest < Test::Unit::TestCase
def setup
@test = ::ActionController::IntegrationTest.new(:default_test)
@test.class.stubs(:fixture_table_names).returns([])
@session = @test.open_session
end
def test_opens_new_session
@test.class.expects(:fixture_table_names).times(2).returns(['foo'])
session1 = @test.open_session { |sess| }
session2 = @test.open_session # implicit session
assert_equal ::ActionController::Integration::Session, session1.class
assert_equal ::ActionController::Integration::Session, session2.class
assert_not_equal session1, session2
end
# RSpec mixes Matchers (which has a #method_missing) into
# IntegrationTest's superclass. Make sure IntegrationTest does not
# try to delegate these methods to the session object.
def test_does_not_prevent_method_missing_passing_up_to_ancestors
mixin = Module.new do
def method_missing(name, *args)
name.to_s == 'foo' ? 'pass' : super
end
end
@test.class.superclass.__send__(:include, mixin)
begin
assert_equal 'pass', @test.foo
ensure
# leave other tests as unaffected as possible
mixin.__send__(:remove_method, :method_missing)
end
end
end
# Tests that integration tests don't call Controller test methods for processing.
# Integration tests have their own setup and teardown.
class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest
def self.fixture_table_names
[]
end
def test_integration_methods_called
reset!
@integration_session.stubs(:generic_url_rewriter)
@integration_session.stubs(:process)
%w( get post head put delete ).each do |verb|
assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') }
end
end
end
class IntegrationProcessTest < ActionController::IntegrationTest
class IntegrationController < ActionController::Base
def get
respond_to do |format|
format.html { render :text => "OK", :status => 200 }
format.js { render :text => "JS OK", :status => 200 }
end
end
def get_with_params
render :text => "foo: #{params[:foo]}", :status => 200
end
def post_with_multiparameter_params
render :text => "foo(1i): #{params[:"foo(1i)"]}, foo(2i): #{params[:"foo(2i)"]}", :status => 200
end
def multipart_post_with_multiparameter_params
render :text => "foo(1i): #{params[:"foo(1i)"]}, foo(2i): #{params[:"foo(2i)"]}, filesize: #{params[:file].size}", :status => 200
end
def multipart_post_with_nested_params
render :text => "foo: #{params[:foo][0]}, #{params[:foo][1]}; [filesize: #{params[:file_list][0][:content].size}, filesize: #{params[:file_list][1][:content].size}]", :status => 200
end
def multipart_post_with_multiparameter_complex_params
render :text => "foo(1i): #{params[:"foo(1i)"]}, foo(2i): #{params[:"foo(2i)"]}, [filesize: #{params[:file_list][0][:content].size}, filesize: #{params[:file_list][1][:content].size}]", :status => 200
end
def post
render :text => "Created", :status => 201
end
def cookie_monster
cookies["cookie_1"] = nil
cookies["cookie_3"] = "chocolate"
render :text => "Gone", :status => 410
end
def redirect
redirect_to :action => "get"
end
end
FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
def test_get
with_test_route_set do
get '/get'
assert_equal 200, status
assert_equal "OK", status_message
assert_response 200
assert_response :success
assert_response :ok
assert_equal({}, cookies)
assert_equal "OK", body
assert_equal "OK", response.body
assert_kind_of HTML::Document, html_document
assert_equal 1, request_count
end
end
def test_post
with_test_route_set do
post '/post'
assert_equal 201, status
assert_equal "Created", status_message
assert_response 201
assert_response :success
assert_response :created
assert_equal({}, cookies)
assert_equal "Created", body
assert_equal "Created", response.body
assert_kind_of HTML::Document, html_document
assert_equal 1, request_count
end
end
def test_cookie_monster
with_test_route_set do
self.cookies['cookie_1'] = "sugar"
self.cookies['cookie_2'] = "oatmeal"
get '/cookie_monster'
assert_equal 410, status
assert_equal "Gone", status_message
assert_response 410
assert_response :gone
assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies)
assert_equal "Gone", response.body
end
end
def test_redirect
with_test_route_set do
get '/redirect'
assert_equal 302, status
assert_equal "Found", status_message
assert_response 302
assert_response :redirect
assert_response :found
assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body
assert_kind_of HTML::Document, html_document
assert_equal 1, request_count
follow_redirect!
assert_response :success
assert_equal "/get", path
end
end
def test_xml_http_request_get
with_test_route_set do
xhr :get, '/get'
assert_equal 200, status
assert_equal "OK", status_message
assert_response 200
assert_response :success
assert_response :ok
assert_equal "JS OK", response.body
end
end
def test_get_with_query_string
with_test_route_set do
get '/get_with_params?foo=bar'
assert_equal '/get_with_params?foo=bar', request.env["REQUEST_URI"]
assert_equal '/get_with_params?foo=bar', request.request_uri
assert_equal "", request.env["QUERY_STRING"]
assert_equal 'foo=bar', request.query_string
assert_equal 'bar', request.parameters['foo']
assert_equal 200, status
assert_equal "foo: bar", response.body
end
end
def test_get_with_parameters
with_test_route_set do
get '/get_with_params', :foo => "bar"
assert_equal '/get_with_params', request.env["REQUEST_URI"]
assert_equal '/get_with_params', request.request_uri
assert_equal 'foo=bar', request.env["QUERY_STRING"]
assert_equal 'foo=bar', request.query_string
assert_equal 'bar', request.parameters['foo']
assert_equal 200, status
assert_equal "foo: bar", response.body
end
end
def test_post_with_multiparameter_attribute_parameters
with_test_route_set do
post '/post_with_multiparameter_params', :"foo(1i)" => "bar", :"foo(2i)" => "baz"
assert_equal 200, status
assert_equal "foo(1i): bar, foo(2i): baz", response.body
end
end
def test_multipart_post_with_multiparameter_attribute_parameters
with_test_route_set do
post '/multipart_post_with_multiparameter_params', :"foo(1i)" => "bar", :"foo(2i)" => "baz", :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
assert_equal 200, status
assert_equal "foo(1i): bar, foo(2i): baz, filesize: 159528", response.body
end
end
def test_multipart_post_with_nested_params
with_test_route_set do
post '/multipart_post_with_nested_params', :"foo" => ['a', 'b'], :file_list => [{:content => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")}, {:content => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")}]
assert_equal 200, status
assert_equal "foo: a, b; [filesize: 159528, filesize: 159528]", response.body
end
end
def test_multipart_post_with_multiparameter_complex_attribute_parameters
with_test_route_set do
post '/multipart_post_with_multiparameter_complex_params', :"foo(1i)" => "bar", :"foo(2i)" => "baz", :file_list => [{:content => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")}, {:content => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")}]
assert_equal 200, status
assert_equal "foo(1i): bar, foo(2i): baz, [filesize: 159528, filesize: 159528]", response.body
end
end
def test_head
with_test_route_set do
head '/get'
assert_equal 200, status
assert_equal "", body
head '/post'
assert_equal 201, status
assert_equal "", body
end
end
private
def with_test_route_set
with_routing do |set|
set.draw do |map|
map.with_options :controller => "IntegrationProcessTest::Integration" do |c|
c.connect "/:action"
end
end
yield
end
end
end
class MetalTest < ActionController::IntegrationTest
class Poller
def self.call(env)
if env["PATH_INFO"] =~ /^\/success/
[200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]]
else
[404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []]
end
end
end
def setup
@integration_session = ActionController::Integration::Session.new(Poller)
end
def test_successful_get
get "/success"
assert_response 200
assert_response :success
assert_response :ok
assert_equal "Hello World!", response.body
end
def test_failed_get
get "/failure"
assert_response 404
assert_response :not_found
assert_equal '', response.body
end
end
class StringSubclassBodyTest < ActionController::IntegrationTest
class SafeString < String
end
class SafeStringMiddleware
def self.call(env)
[200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, [SafeString.new("Hello World!")]]
end
end
def setup
@integration_session = ActionController::Integration::Session.new(SafeStringMiddleware)
end
def test_string_subclass_body
get '/'
assert_equal 'Hello World!', response.body
end
end

View file

@ -1,215 +0,0 @@
require 'abstract_unit'
# The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited
# method has access to the view_paths array when looking for a layout to automatically assign.
old_load_paths = ActionController::Base.view_paths
ActionView::Template::register_template_handler :mab,
lambda { |template| template.source.inspect }
ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ]
class LayoutTest < ActionController::Base
def self.controller_path; 'views' end
self.view_paths = ActionController::Base.view_paths.dup
end
# Restore view_paths to previous value
ActionController::Base.view_paths = old_load_paths
class ProductController < LayoutTest
end
class ItemController < LayoutTest
end
class ThirdPartyTemplateLibraryController < LayoutTest
end
module ControllerNameSpace
end
class ControllerNameSpace::NestedController < LayoutTest
end
class MultipleExtensions < LayoutTest
end
class LayoutAutoDiscoveryTest < ActionController::TestCase
def setup
@request.host = "www.nextangle.com"
end
def test_application_layout_is_default_when_no_controller_match
@controller = ProductController.new
get :hello
assert_equal 'layout_test.rhtml hello.rhtml', @response.body
end
def test_controller_name_layout_name_match
@controller = ItemController.new
get :hello
assert_equal 'item.rhtml hello.rhtml', @response.body
end
def test_third_party_template_library_auto_discovers_layout
@controller = ThirdPartyTemplateLibraryController.new
get :hello
assert_equal 'layouts/third_party_template_library.mab', @controller.active_layout.to_s
assert_equal 'layouts/third_party_template_library', @response.layout
assert_response :success
assert_equal 'Mab', @response.body
end
def test_namespaced_controllers_auto_detect_layouts
@controller = ControllerNameSpace::NestedController.new
get :hello
assert_equal 'layouts/controller_name_space/nested', @controller.active_layout.to_s
assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
end
def test_namespaced_controllers_auto_detect_layouts
@controller = MultipleExtensions.new
get :hello
assert_equal 'layouts/multiple_extensions.html.erb', @controller.active_layout.to_s
assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip
end
end
class DefaultLayoutController < LayoutTest
end
class AbsolutePathLayoutController < LayoutTest
layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml')
end
class AbsolutePathWithoutLayoutsController < LayoutTest
# Absolute layout path without 'layouts' in it.
layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/abs_path_layout.rhtml')
end
class HasOwnLayoutController < LayoutTest
layout 'item'
end
class PrependsViewPathController < LayoutTest
def hello
prepend_view_path File.dirname(__FILE__) + '/../fixtures/layout_tests/alt/'
render :layout => 'alt'
end
end
class SetsLayoutInRenderController < LayoutTest
def hello
render :layout => 'third_party_template_library'
end
end
class RendersNoLayoutController < LayoutTest
def hello
render :layout => false
end
end
class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
get :hello
assert_equal 'layouts/layout_test', @response.layout
end
def test_layout_set_when_set_in_controller
@controller = HasOwnLayoutController.new
get :hello
assert_equal 'layouts/item', @response.layout
end
def test_layout_set_when_using_render
@controller = SetsLayoutInRenderController.new
get :hello
assert_equal 'layouts/third_party_template_library', @response.layout
end
def test_layout_is_not_set_when_none_rendered
@controller = RendersNoLayoutController.new
get :hello
assert_nil @response.layout
end
def test_exempt_from_layout_honored_by_render_template
ActionController::Base.exempt_from_layout :rhtml
@controller = RenderWithTemplateOptionController.new
get :hello
assert_equal "alt/hello.rhtml", @response.body.strip
ensure
ActionController::Base.exempt_from_layout.delete(/\.rhtml$/)
end
def test_layout_is_picked_from_the_controller_instances_view_path
@controller = PrependsViewPathController.new
get :hello
assert_equal 'layouts/alt', @response.layout
end
def test_absolute_pathed_layout
@controller = AbsolutePathLayoutController.new
get :hello
assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip
end
def test_absolute_pathed_layout_without_layouts_in_path
@controller = AbsolutePathWithoutLayoutsController.new
get :hello
assert_equal "abs_path_layout.rhtml hello.rhtml", @response.body.strip
end
end
class RenderWithTemplateOptionController < LayoutTest
def hello
render :template => 'alt/hello'
end
end
class SetsNonExistentLayoutFile < LayoutTest
layout "nofile.rhtml"
end
class LayoutExceptionRaised < ActionController::TestCase
def test_exception_raised_when_layout_file_not_found
@controller = SetsNonExistentLayoutFile.new
get :hello
assert_kind_of ActionView::MissingTemplate, @response.template.instance_eval { @exception }
end
end
class LayoutStatusIsRendered < LayoutTest
def hello
render :status => 401
end
end
class LayoutStatusIsRenderedTest < ActionController::TestCase
def test_layout_status_is_rendered
@controller = LayoutStatusIsRendered.new
get :hello
assert_response 401
end
end
unless RUBY_PLATFORM =~ /(:?mswin|mingw|bccwin)/
class LayoutSymlinkedTest < LayoutTest
layout "symlinked/symlinked_layout"
end
class LayoutSymlinkedIsRenderedTest < ActionController::TestCase
def test_symlinked_layout_is_rendered
@controller = LayoutSymlinkedTest.new
get :hello
assert_response 200
assert_equal "layouts/symlinked/symlinked_layout", @response.layout
end
end
end

View file

@ -1,24 +0,0 @@
require 'abstract_unit'
class LocalizedController < ActionController::Base
def hello_world
end
end
class LocalizedTemplatesTest < ActionController::TestCase
tests LocalizedController
teardown { I18n.locale = :en }
def test_localized_template_is_used
I18n.locale = :de
get :hello_world
assert_equal "Gutten Tag", @response.body
end
def test_default_locale_template_is_used_when_locale_is_missing
I18n.locale = :dk
get :hello_world
assert_equal "Hello World", @response.body
end
end

View file

@ -1,46 +0,0 @@
require 'abstract_unit'
class LoggingController < ActionController::Base
def show
render :nothing => true
end
end
class LoggingTest < ActionController::TestCase
tests LoggingController
class MockLogger
attr_reader :logged
def method_missing(method, *args)
@logged ||= []
@logged << args.first
end
end
setup :set_logger
def test_logging_without_parameters
get :show
assert_equal 2, logs.size
assert_nil logs.detect {|l| l =~ /Parameters/ }
end
def test_logging_with_parameters
get :show, :id => 10
assert_equal 3, logs.size
params = logs.detect {|l| l =~ /Parameters/ }
assert_equal 'Parameters: {"id"=>"10"}', params
end
private
def set_logger
@controller.logger = MockLogger.new
end
def logs
@logs ||= @controller.logger.logged.compact.map {|l| l.strip}
end
end

View file

@ -1,90 +0,0 @@
require 'abstract_unit'
class MiddlewareStackTest < ActiveSupport::TestCase
class FooMiddleware; end
class BarMiddleware; end
class BazMiddleware; end
def setup
@stack = ActionController::MiddlewareStack.new
@stack.use FooMiddleware
@stack.use BarMiddleware
end
test "use should push middleware as class onto the stack" do
assert_difference "@stack.size" do
@stack.use BazMiddleware
end
assert_equal BazMiddleware, @stack.last.klass
end
test "use should push middleware as a string onto the stack" do
assert_difference "@stack.size" do
@stack.use "MiddlewareStackTest::BazMiddleware"
end
assert_equal BazMiddleware, @stack.last.klass
end
test "use should push middleware as a symbol onto the stack" do
assert_difference "@stack.size" do
@stack.use :"MiddlewareStackTest::BazMiddleware"
end
assert_equal BazMiddleware, @stack.last.klass
end
test "use should push middleware class with arguments onto the stack" do
assert_difference "@stack.size" do
@stack.use BazMiddleware, true, :foo => "bar"
end
assert_equal BazMiddleware, @stack.last.klass
assert_equal([true, {:foo => "bar"}], @stack.last.args)
end
test "insert inserts middleware at the integer index" do
@stack.insert(1, BazMiddleware)
assert_equal BazMiddleware, @stack[1].klass
end
test "insert_after inserts middleware after the integer index" do
@stack.insert_after(1, BazMiddleware)
assert_equal BazMiddleware, @stack[2].klass
end
test "insert_before inserts middleware before another middleware class" do
@stack.insert_before(BarMiddleware, BazMiddleware)
assert_equal BazMiddleware, @stack[1].klass
end
test "insert_after inserts middleware after another middleware class" do
@stack.insert_after(BarMiddleware, BazMiddleware)
assert_equal BazMiddleware, @stack[2].klass
end
test "swaps one middleware out for another" do
assert_equal FooMiddleware, @stack[0].klass
@stack.swap(FooMiddleware, BazMiddleware)
assert_equal BazMiddleware, @stack[0].klass
end
test "active returns all only enabled middleware" do
assert_no_difference "@stack.active.size" do
assert_difference "@stack.size" do
@stack.use BazMiddleware, :if => lambda { false }
end
end
end
test "lazy evaluates middleware class" do
assert_difference "@stack.size" do
@stack.use lambda { BazMiddleware }
end
assert_equal BazMiddleware, @stack.last.klass
end
test "lazy evaluates middleware arguments" do
assert_difference "@stack.size" do
@stack.use BazMiddleware, lambda { :foo }
end
assert_equal [:foo], @stack.last.send(:build_args)
end
end

View file

@ -1,536 +0,0 @@
require 'abstract_unit'
class RespondToController < ActionController::Base
layout :set_layout
def html_xml_or_rss
respond_to do |type|
type.html { render :text => "HTML" }
type.xml { render :text => "XML" }
type.rss { render :text => "RSS" }
type.all { render :text => "Nothing" }
end
end
def js_or_html
respond_to do |type|
type.html { render :text => "HTML" }
type.js { render :text => "JS" }
type.all { render :text => "Nothing" }
end
end
def json_or_yaml
respond_to do |type|
type.json { render :text => "JSON" }
type.yaml { render :text => "YAML" }
end
end
def html_or_xml
respond_to do |type|
type.html { render :text => "HTML" }
type.xml { render :text => "XML" }
type.all { render :text => "Nothing" }
end
end
def forced_xml
request.format = :xml
respond_to do |type|
type.html { render :text => "HTML" }
type.xml { render :text => "XML" }
end
end
def just_xml
respond_to do |type|
type.xml { render :text => "XML" }
end
end
def using_defaults
respond_to do |type|
type.html
type.js
type.xml
end
end
def using_defaults_with_type_list
respond_to(:html, :js, :xml)
end
def made_for_content_type
respond_to do |type|
type.rss { render :text => "RSS" }
type.atom { render :text => "ATOM" }
type.all { render :text => "Nothing" }
end
end
def custom_type_handling
respond_to do |type|
type.html { render :text => "HTML" }
type.custom("application/crazy-xml") { render :text => "Crazy XML" }
type.all { render :text => "Nothing" }
end
end
def custom_constant_handling
Mime::Type.register("text/x-mobile", :mobile)
respond_to do |type|
type.html { render :text => "HTML" }
type.mobile { render :text => "Mobile" }
end
ensure
Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) }
end
def custom_constant_handling_without_block
Mime::Type.register("text/x-mobile", :mobile)
respond_to do |type|
type.html { render :text => "HTML" }
type.mobile
end
ensure
Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) }
end
def handle_any
respond_to do |type|
type.html { render :text => "HTML" }
type.any(:js, :xml) { render :text => "Either JS or XML" }
end
end
def handle_any_any
respond_to do |type|
type.html { render :text => 'HTML' }
type.any { render :text => 'Whatever you ask for, I got it' }
end
end
def all_types_with_layout
respond_to do |type|
type.html
type.js
end
end
def iphone_with_html_response_type
Mime::Type.register_alias("text/html", :iphone)
request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone"
respond_to do |type|
type.html { @type = "Firefox" }
type.iphone { @type = "iPhone" }
end
ensure
Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
end
def iphone_with_html_response_type_without_layout
Mime::Type.register_alias("text/html", :iphone)
request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
respond_to do |type|
type.html { @type = "Firefox"; render :action => "iphone_with_html_response_type" }
type.iphone { @type = "iPhone" ; render :action => "iphone_with_html_response_type" }
end
ensure
Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
end
def rescue_action(e)
raise
end
protected
def set_layout
if ["all_types_with_layout", "iphone_with_html_response_type"].include?(action_name)
"respond_to/layouts/standard"
elsif action_name == "iphone_with_html_response_type_without_layout"
"respond_to/layouts/missing"
end
end
end
class MimeControllerTest < ActionController::TestCase
tests RespondToController
def setup
ActionController::Base.use_accept_header = true
@request.host = "www.example.com"
end
def teardown
ActionController::Base.use_accept_header = false
end
def test_html
@request.accept = "text/html"
get :js_or_html
assert_equal 'HTML', @response.body
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_response 406
end
def test_all
@request.accept = "*/*"
get :js_or_html
assert_equal 'HTML', @response.body # js is not part of all
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_equal 'XML', @response.body
end
def test_xml
@request.accept = "application/xml"
get :html_xml_or_rss
assert_equal 'XML', @response.body
end
def test_js_or_html
@request.accept = "text/javascript, text/html"
get :js_or_html
assert_equal 'JS', @response.body
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_response 406
end
def test_json_or_yaml
get :json_or_yaml
assert_equal 'JSON', @response.body
get :json_or_yaml, :format => 'json'
assert_equal 'JSON', @response.body
get :json_or_yaml, :format => 'yaml'
assert_equal 'YAML', @response.body
{ 'YAML' => %w(text/yaml),
'JSON' => %w(application/json text/x-json)
}.each do |body, content_types|
content_types.each do |content_type|
@request.accept = content_type
get :json_or_yaml
assert_equal body, @response.body
end
end
end
def test_js_or_anything
@request.accept = "text/javascript, */*"
get :js_or_html
assert_equal 'JS', @response.body
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_equal 'XML', @response.body
end
def test_using_defaults
@request.accept = "*/*"
get :using_defaults
assert_equal "text/html", @response.content_type
assert_equal 'Hello world!', @response.body
@request.accept = "text/javascript"
get :using_defaults
assert_equal "text/javascript", @response.content_type
assert_equal '$("body").visualEffect("highlight");', @response.body
@request.accept = "application/xml"
get :using_defaults
assert_equal "application/xml", @response.content_type
assert_equal "<p>Hello world!</p>\n", @response.body
end
def test_using_defaults_with_type_list
@request.accept = "*/*"
get :using_defaults_with_type_list
assert_equal "text/html", @response.content_type
assert_equal 'Hello world!', @response.body
@request.accept = "text/javascript"
get :using_defaults_with_type_list
assert_equal "text/javascript", @response.content_type
assert_equal '$("body").visualEffect("highlight");', @response.body
@request.accept = "application/xml"
get :using_defaults_with_type_list
assert_equal "application/xml", @response.content_type
assert_equal "<p>Hello world!</p>\n", @response.body
end
def test_with_atom_content_type
@request.env["CONTENT_TYPE"] = "application/atom+xml"
get :made_for_content_type
assert_equal "ATOM", @response.body
end
def test_with_rss_content_type
@request.env["CONTENT_TYPE"] = "application/rss+xml"
get :made_for_content_type
assert_equal "RSS", @response.body
end
def test_synonyms
@request.accept = "application/javascript"
get :js_or_html
assert_equal 'JS', @response.body
@request.accept = "application/x-xml"
get :html_xml_or_rss
assert_equal "XML", @response.body
end
def test_custom_types
@request.accept = "application/crazy-xml"
get :custom_type_handling
assert_equal "application/crazy-xml", @response.content_type
assert_equal 'Crazy XML', @response.body
@request.accept = "text/html"
get :custom_type_handling
assert_equal "text/html", @response.content_type
assert_equal 'HTML', @response.body
end
def test_xhtml_alias
@request.accept = "application/xhtml+xml,application/xml"
get :html_or_xml
assert_equal 'HTML', @response.body
end
def test_firefox_simulation
@request.accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
get :html_or_xml
assert_equal 'HTML', @response.body
end
def test_handle_any
@request.accept = "*/*"
get :handle_any
assert_equal 'HTML', @response.body
@request.accept = "text/javascript"
get :handle_any
assert_equal 'Either JS or XML', @response.body
@request.accept = "text/xml"
get :handle_any
assert_equal 'Either JS or XML', @response.body
end
def test_handle_any_any
@request.accept = "*/*"
get :handle_any_any
assert_equal 'HTML', @response.body
end
def test_handle_any_any_parameter_format
get :handle_any_any, {:format=>'html'}
assert_equal 'HTML', @response.body
end
def test_handle_any_any_explicit_html
@request.accept = "text/html"
get :handle_any_any
assert_equal 'HTML', @response.body
end
def test_handle_any_any_javascript
@request.accept = "text/javascript"
get :handle_any_any
assert_equal 'Whatever you ask for, I got it', @response.body
end
def test_handle_any_any_xml
@request.accept = "text/xml"
get :handle_any_any
assert_equal 'Whatever you ask for, I got it', @response.body
end
def test_rjs_type_skips_layout
@request.accept = "text/javascript"
get :all_types_with_layout
assert_equal 'RJS for all_types_with_layout', @response.body
end
def test_html_type_with_layout
@request.accept = "text/html"
get :all_types_with_layout
assert_equal '<html><div id="html">HTML for all_types_with_layout</div></html>', @response.body
end
def test_xhr
xhr :get, :js_or_html
assert_equal 'JS', @response.body
xhr :get, :using_defaults
assert_equal '$("body").visualEffect("highlight");', @response.body
end
def test_custom_constant
get :custom_constant_handling, :format => "mobile"
assert_equal "text/x-mobile", @response.content_type
assert_equal "Mobile", @response.body
end
def test_custom_constant_handling_without_block
get :custom_constant_handling_without_block, :format => "mobile"
assert_equal "text/x-mobile", @response.content_type
assert_equal "Mobile", @response.body
end
def test_forced_format
get :html_xml_or_rss
assert_equal "HTML", @response.body
get :html_xml_or_rss, :format => "html"
assert_equal "HTML", @response.body
get :html_xml_or_rss, :format => "xml"
assert_equal "XML", @response.body
get :html_xml_or_rss, :format => "rss"
assert_equal "RSS", @response.body
end
def test_internally_forced_format
get :forced_xml
assert_equal "XML", @response.body
get :forced_xml, :format => "html"
assert_equal "XML", @response.body
end
def test_extension_synonyms
get :html_xml_or_rss, :format => "xhtml"
assert_equal "HTML", @response.body
end
def test_render_action_for_html
@controller.instance_eval do
def render(*args)
unless args.empty?
@action = args.first[:action]
end
response.body = "#{@action} - #{@template.template_format}"
end
end
get :using_defaults
assert_equal "using_defaults - html", @response.body
get :using_defaults, :format => "xml"
assert_equal "using_defaults - xml", @response.body
end
def test_format_with_custom_response_type
get :iphone_with_html_response_type
assert_equal '<html><div id="html">Hello future from Firefox!</div></html>', @response.body
get :iphone_with_html_response_type, :format => "iphone"
assert_equal "text/html", @response.content_type
assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body
end
def test_format_with_custom_response_type_and_request_headers
@request.accept = "text/iphone"
get :iphone_with_html_response_type
assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body
assert_equal "text/html", @response.content_type
end
def test_format_with_custom_response_type_and_request_headers_with_only_one_layout_present
get :iphone_with_html_response_type_without_layout
assert_equal '<html><div id="html_missing">Hello future from Firefox!</div></html>', @response.body
@request.accept = "text/iphone"
assert_raise(ActionView::MissingTemplate) { get :iphone_with_html_response_type_without_layout }
end
end
class AbstractPostController < ActionController::Base
self.view_paths = File.dirname(__FILE__) + "/../fixtures/post_test/"
end
# For testing layouts which are set automatically
class PostController < AbstractPostController
around_filter :with_iphone
def index
respond_to do |type|
type.html
type.iphone
end
end
protected
def with_iphone
Mime::Type.register_alias("text/html", :iphone)
request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
yield
ensure
Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
end
end
class SuperPostController < PostController
def index
respond_to do |type|
type.html
type.iphone
end
end
end
class MimeControllerLayoutsTest < ActionController::TestCase
tests PostController
def setup
@request.host = "www.example.com"
end
def test_missing_layout_renders_properly
get :index
assert_equal '<html><div id="html">Hello Firefox</div></html>', @response.body
@request.accept = "text/iphone"
get :index
assert_equal 'Hello iPhone', @response.body
end
def test_format_with_inherited_layouts
@controller = SuperPostController.new
get :index
assert_equal 'Super Firefox', @response.body
@request.accept = "text/iphone"
get :index
assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body
end
end

View file

@ -1,93 +0,0 @@
require 'abstract_unit'
class MimeTypeTest < Test::Unit::TestCase
Mime::Type.register "image/png", :png
Mime::Type.register "application/pdf", :pdf
def test_parse_single
Mime::LOOKUP.keys.each do |mime_type|
assert_equal [Mime::Type.lookup(mime_type)], Mime::Type.parse(mime_type)
end
end
def test_parse_without_q
accept = "text/xml,application/xhtml+xml,text/yaml,application/xml,text/html,image/png,text/plain,application/pdf,*/*"
expect = [Mime::HTML, Mime::XML, Mime::YAML, Mime::PNG, Mime::TEXT, Mime::PDF, Mime::ALL]
assert_equal expect, Mime::Type.parse(accept)
end
def test_parse_with_q
accept = "text/xml,application/xhtml+xml,text/yaml; q=0.3,application/xml,text/html; q=0.8,image/png,text/plain; q=0.5,application/pdf,*/*; q=0.2"
expect = [Mime::HTML, Mime::XML, Mime::PNG, Mime::PDF, Mime::TEXT, Mime::YAML, Mime::ALL]
assert_equal expect, Mime::Type.parse(accept)
end
# Accept header send with user HTTP_USER_AGENT: Sunrise/0.42j (Windows XP)
def test_parse_crappy_broken_acceptlines
accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5"
expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL]
assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
end
# Accept header send with user HTTP_USER_AGENT: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1)
def test_parse_crappy_broken_acceptlines2
accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*"
expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL ]
assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
end
def test_custom_type
Mime::Type.register("image/gif", :gif)
assert_nothing_raised do
Mime::GIF
assert_equal Mime::GIF, Mime::SET.last
end
ensure
Mime.module_eval { remove_const :GIF if const_defined?(:GIF) }
end
def test_type_should_be_equal_to_symbol
assert_equal Mime::HTML, 'application/xhtml+xml'
assert_equal Mime::HTML, :html
end
def test_type_convenience_methods
# Don't test Mime::ALL, since it Mime::ALL#html? == true
types = Mime::SET.to_a.map(&:to_sym).uniq - [:all]
# 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.send("#{type}?"), "#{mime.inspect} is not #{type}?"
invalid_types = types - [type]
invalid_types.delete(:html) if Mime::Type.html_types.include?(type)
invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
end
end
def test_mime_all_is_html
assert Mime::ALL.all?, "Mime::ALL is not all?"
assert Mime::ALL.html?, "Mime::ALL is not html?"
end
def test_verifiable_mime_types
all_types = Mime::SET.to_a.map(&:to_sym)
all_types.uniq!
# Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) }
verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type }
assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" }
assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
end
def test_regexp_matcher
assert Mime::JS =~ "text/javascript"
assert Mime::JS =~ "application/javascript"
assert Mime::JS !~ "text/html"
assert !(Mime::JS !~ "text/javascript")
assert !(Mime::JS !~ "application/javascript")
assert Mime::HTML =~ 'application/xhtml+xml'
end
end

View file

@ -1,19 +0,0 @@
require 'abstract_unit'
class OutputEscapingTest < ActiveSupport::TestCase
test "escape_html shouldn't die when passed nil" do
assert ERB::Util.h(nil).blank?
end
test "escapeHTML should escape strings" do
assert_equal "&lt;&gt;&quot;", ERB::Util.h("<>\"")
end
test "escapeHTML shouldn't touch explicitly safe strings" do
# TODO this seems easier to compose and reason about, but
# this should be verified
assert_equal "<", ERB::Util.h("<".html_safe)
end
end

View file

@ -1,297 +0,0 @@
require 'abstract_unit'
class Article
attr_reader :id
def save; @id = 1 end
def new_record?; @id.nil? end
def name
model = self.class.name.downcase
@id.nil? ? "new #{model}" : "#{model} ##{@id}"
end
end
class Response < Article
def post_id; 1 end
end
class Tag < Article
def response_id; 1 end
end
class Tax
attr_reader :id
def save; @id = 1 end
def new_record?; @id.nil? end
def name
model = self.class.name.downcase
@id.nil? ? "new #{model}" : "#{model} ##{@id}"
end
end
class Fax < Tax
def store_id; 1 end
end
# TODO: test nested models
class Response::Nested < Response; end
class PolymorphicRoutesTest < ActiveSupport::TestCase
include ActionController::PolymorphicRoutes
def setup
@article = Article.new
@response = Response.new
@tax = Tax.new
@fax = Fax.new
end
def test_with_record
@article.save
expects(:article_url).with(@article)
polymorphic_url(@article)
end
def test_with_new_record
expects(:articles_url).with()
@article.expects(:new_record?).returns(true)
polymorphic_url(@article)
end
def test_with_record_and_action
expects(:new_article_url).with()
@article.expects(:new_record?).never
polymorphic_url(@article, :action => 'new')
end
def test_url_helper_prefixed_with_new
expects(:new_article_url).with()
new_polymorphic_url(@article)
end
def test_url_helper_prefixed_with_edit
@article.save
expects(:edit_article_url).with(@article)
edit_polymorphic_url(@article)
end
def test_url_helper_prefixed_with_edit_with_url_options
@article.save
expects(:edit_article_url).with(@article, :param1 => '10')
edit_polymorphic_url(@article, :param1 => '10')
end
def test_url_helper_with_url_options
@article.save
expects(:article_url).with(@article, :param1 => '10')
polymorphic_url(@article, :param1 => '10')
end
def test_formatted_url_helper_is_deprecated
expects(:articles_url).with(:format => :pdf)
assert_deprecated do
formatted_polymorphic_url([@article, :pdf])
end
end
def test_format_option
@article.save
expects(:article_url).with(@article, :format => :pdf)
polymorphic_url(@article, :format => :pdf)
end
def test_format_option_with_url_options
@article.save
expects(:article_url).with(@article, :format => :pdf, :param1 => '10')
polymorphic_url(@article, :format => :pdf, :param1 => '10')
end
def test_id_and_format_option
@article.save
expects(:article_url).with(:id => @article, :format => :pdf)
polymorphic_url(:id => @article, :format => :pdf)
end
def test_with_nested
@response.save
expects(:article_response_url).with(@article, @response)
polymorphic_url([@article, @response])
end
def test_with_nested_unsaved
expects(:article_responses_url).with(@article)
polymorphic_url([@article, @response])
end
def test_new_with_array_and_namespace
expects(:new_admin_article_url).with()
polymorphic_url([:admin, @article], :action => 'new')
end
def test_unsaved_with_array_and_namespace
expects(:admin_articles_url).with()
polymorphic_url([:admin, @article])
end
def test_nested_unsaved_with_array_and_namespace
@article.save
expects(:admin_article_url).with(@article)
polymorphic_url([:admin, @article])
expects(:admin_article_responses_url).with(@article)
polymorphic_url([:admin, @article, @response])
end
def test_nested_with_array_and_namespace
@response.save
expects(:admin_article_response_url).with(@article, @response)
polymorphic_url([:admin, @article, @response])
# a ridiculously long named route tests correct ordering of namespaces and nesting:
@tag = Tag.new
@tag.save
expects(:site_admin_article_response_tag_url).with(@article, @response, @tag)
polymorphic_url([:site, :admin, @article, @response, @tag])
end
def test_nesting_with_array_ending_in_singleton_resource
expects(:article_response_url).with(@article)
polymorphic_url([@article, :response])
end
def test_nesting_with_array_containing_singleton_resource
@tag = Tag.new
@tag.save
expects(:article_response_tag_url).with(@article, @tag)
polymorphic_url([@article, :response, @tag])
end
def test_nesting_with_array_containing_namespace_and_singleton_resource
@tag = Tag.new
@tag.save
expects(:admin_article_response_tag_url).with(@article, @tag)
polymorphic_url([:admin, @article, :response, @tag])
end
def test_nesting_with_array_containing_singleton_resource_and_format
@tag = Tag.new
@tag.save
expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
polymorphic_url([@article, :response, @tag], :format => :pdf)
end
def test_nesting_with_array_containing_singleton_resource_and_format_option
@tag = Tag.new
@tag.save
expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
polymorphic_url([@article, :response, @tag], :format => :pdf)
end
def test_nesting_with_array_containing_nil
expects(:article_response_url).with(@article)
polymorphic_url([@article, nil, :response])
end
def test_with_array_containing_single_object
@article.save
expects(:article_url).with(@article)
polymorphic_url([nil, @article])
end
def test_with_array_containing_single_name
@article.save
expects(:articles_url)
polymorphic_url([:articles])
end
# TODO: Needs to be updated to correctly know about whether the object is in a hash or not
def xtest_with_hash
expects(:article_url).with(@article)
@article.save
polymorphic_url(:id => @article)
end
def test_polymorphic_path_accepts_options
expects(:new_article_path).with()
polymorphic_path(@article, :action => :new)
end
def test_polymorphic_path_does_not_modify_arguments
expects(:admin_article_responses_url).with(@article)
path = [:admin, @article, @response]
assert_no_difference 'path.size' do
polymorphic_url(path)
end
end
# Tests for names where .plural.singular doesn't round-trip
def test_with_irregular_plural_record
@tax.save
expects(:taxis_url).with(@tax)
polymorphic_url(@tax)
end
def test_with_irregular_plural_new_record
expects(:taxes_url).with()
@tax.expects(:new_record?).returns(true)
polymorphic_url(@tax)
end
def test_with_irregular_plural_record_and_action
expects(:new_taxis_url).with()
@tax.expects(:new_record?).never
polymorphic_url(@tax, :action => 'new')
end
def test_irregular_plural_url_helper_prefixed_with_new
expects(:new_taxis_url).with()
new_polymorphic_url(@tax)
end
def test_irregular_plural_url_helper_prefixed_with_edit
@tax.save
expects(:edit_taxis_url).with(@tax)
edit_polymorphic_url(@tax)
end
def test_with_nested_irregular_plurals
@fax.save
expects(:taxis_faxis_url).with(@tax, @fax)
polymorphic_url([@tax, @fax])
end
def test_with_nested_unsaved_irregular_plurals
expects(:taxis_faxes_url).with(@tax)
polymorphic_url([@tax, @fax])
end
def test_new_with_irregular_plural_array_and_namespace
expects(:new_admin_taxis_url).with()
polymorphic_url([:admin, @tax], :action => 'new')
end
def test_unsaved_with_irregular_plural_array_and_namespace
expects(:admin_taxes_url).with()
polymorphic_url([:admin, @tax])
end
def test_nesting_with_irregular_plurals_and_array_ending_in_singleton_resource
expects(:taxis_faxis_url).with(@tax)
polymorphic_url([@tax, :faxis])
end
def test_with_array_containing_single_irregular_plural_object
@tax.save
expects(:taxis_url).with(@tax)
polymorphic_url([nil, @tax])
end
def test_with_array_containing_single_name_irregular_plural
@tax.save
expects(:taxes_url)
polymorphic_url([:taxes])
end
def test_with_array_containing_symbols
expects(:new_article_url).with()
polymorphic_url([:new, :article])
end
end

View file

@ -1,308 +0,0 @@
require 'abstract_unit'
class BaseRackTest < ActiveSupport::TestCase
def setup
@env = {
"HTTP_MAX_FORWARDS" => "10",
"SERVER_NAME" => "glu.ttono.us",
"FCGI_ROLE" => "RESPONDER",
"AUTH_TYPE" => "Basic",
"HTTP_X_FORWARDED_HOST" => "glu.ttono.us",
"HTTP_ACCEPT_CHARSET" => "UTF-8",
"HTTP_ACCEPT_ENCODING" => "gzip, deflate",
"HTTP_CACHE_CONTROL" => "no-cache, max-age=0",
"HTTP_PRAGMA" => "no-cache",
"HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)",
"PATH_INFO" => "/homepage/",
"HTTP_ACCEPT_LANGUAGE" => "en",
"HTTP_NEGOTIATE" => "trans",
"HTTP_HOST" => "glu.ttono.us:8007",
"HTTP_REFERER" => "http://www.google.com/search?q=glu.ttono.us",
"HTTP_FROM" => "googlebot",
"SERVER_PROTOCOL" => "HTTP/1.1",
"REDIRECT_URI" => "/dispatch.fcgi",
"SCRIPT_NAME" => "/dispatch.fcgi",
"SERVER_ADDR" => "207.7.108.53",
"REMOTE_ADDR" => "207.7.108.53",
"REMOTE_HOST" => "google.com",
"REMOTE_IDENT" => "kevin",
"REMOTE_USER" => "kevin",
"SERVER_SOFTWARE" => "lighttpd/1.4.5",
"HTTP_COOKIE" => "_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes",
"HTTP_X_FORWARDED_SERVER" => "glu.ttono.us",
"REQUEST_URI" => "/admin",
"DOCUMENT_ROOT" => "/home/kevinc/sites/typo/public",
"PATH_TRANSLATED" => "/home/kevinc/sites/typo/public/homepage/",
"SERVER_PORT" => "8007",
"QUERY_STRING" => "",
"REMOTE_PORT" => "63137",
"GATEWAY_INTERFACE" => "CGI/1.1",
"HTTP_X_FORWARDED_FOR" => "65.88.180.234",
"HTTP_ACCEPT" => "*/*",
"SCRIPT_FILENAME" => "/home/kevinc/sites/typo/public/dispatch.fcgi",
"REDIRECT_STATUS" => "200",
"REQUEST_METHOD" => "GET"
}
@request = ActionController::Request.new(@env)
# some Nokia phone browsers omit the space after the semicolon separator.
# some developers have grown accustomed to using comma in cookie values.
@alt_cookie_fmt_request = ActionController::Request.new(@env.merge({"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"}))
end
def default_test; end
private
def set_content_data(data)
@request.env['REQUEST_METHOD'] = 'POST'
@request.env['CONTENT_LENGTH'] = data.length
@request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8'
@request.env['rack.input'] = StringIO.new(data)
end
end
class RackRequestTest < BaseRackTest
def test_proxy_request
assert_equal 'glu.ttono.us', @request.host_with_port
end
def test_http_host
@env.delete "HTTP_X_FORWARDED_HOST"
@env['HTTP_HOST'] = "rubyonrails.org:8080"
assert_equal "rubyonrails.org", @request.host
assert_equal "rubyonrails.org:8080", @request.host_with_port
@env['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org"
assert_equal "www.secondhost.org", @request.host
end
def test_http_host_with_default_port_overrides_server_port
@env.delete "HTTP_X_FORWARDED_HOST"
@env['HTTP_HOST'] = "rubyonrails.org"
assert_equal "rubyonrails.org", @request.host_with_port
end
def test_host_with_port_defaults_to_server_name_if_no_host_headers
@env.delete "HTTP_X_FORWARDED_HOST"
@env.delete "HTTP_HOST"
assert_equal "glu.ttono.us:8007", @request.host_with_port
end
def test_host_with_port_falls_back_to_server_addr_if_necessary
@env.delete "HTTP_X_FORWARDED_HOST"
@env.delete "HTTP_HOST"
@env.delete "SERVER_NAME"
assert_equal "207.7.108.53", @request.host
assert_equal 8007, @request.port
assert_equal "207.7.108.53:8007", @request.host_with_port
end
def test_host_with_port_if_http_standard_port_is_specified
@env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:80"
assert_equal "glu.ttono.us", @request.host_with_port
end
def test_host_with_port_if_https_standard_port_is_specified
@env['HTTP_X_FORWARDED_PROTO'] = "https"
@env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:443"
assert_equal "glu.ttono.us", @request.host_with_port
end
def test_host_if_ipv6_reference
@env.delete "HTTP_X_FORWARDED_HOST"
@env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]"
assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host
end
def test_host_if_ipv6_reference_with_port
@env.delete "HTTP_X_FORWARDED_HOST"
@env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]:8008"
assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host
end
def test_cgi_environment_variables
assert_equal "Basic", @request.auth_type
assert_equal 0, @request.content_length
assert_equal nil, @request.content_type
assert_equal "CGI/1.1", @request.gateway_interface
assert_equal "*/*", @request.accept
assert_equal "UTF-8", @request.accept_charset
assert_equal "gzip, deflate", @request.accept_encoding
assert_equal "en", @request.accept_language
assert_equal "no-cache, max-age=0", @request.cache_control
assert_equal "googlebot", @request.from
assert_equal "glu.ttono.us", @request.host
assert_equal "trans", @request.negotiate
assert_equal "no-cache", @request.pragma
assert_equal "http://www.google.com/search?q=glu.ttono.us", @request.referer
assert_equal "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", @request.user_agent
assert_equal "/homepage/", @request.path_info
assert_equal "/home/kevinc/sites/typo/public/homepage/", @request.path_translated
assert_equal "", @request.query_string
assert_equal "207.7.108.53", @request.remote_addr
assert_equal "google.com", @request.remote_host
assert_equal "kevin", @request.remote_ident
assert_equal "kevin", @request.remote_user
assert_equal :get, @request.request_method
assert_equal "/dispatch.fcgi", @request.script_name
assert_equal "glu.ttono.us", @request.server_name
assert_equal 8007, @request.server_port
assert_equal "HTTP/1.1", @request.server_protocol
assert_equal "lighttpd", @request.server_software
end
def test_cookie_syntax_resilience
cookies = @request.cookies
assert_equal "c84ace84796670c052c6ceb2451fb0f2", cookies["_session_id"], cookies.inspect
assert_equal "yes", cookies["is_admin"], cookies.inspect
alt_cookies = @alt_cookie_fmt_request.cookies
#assert_equal "c84ace847,96670c052c6ceb2451fb0f2", alt_cookies["_session_id"], alt_cookies.inspect
assert_equal "yes", alt_cookies["is_admin"], alt_cookies.inspect
end
end
class RackRequestParamsParsingTest < BaseRackTest
def test_doesnt_break_when_content_type_has_charset
set_content_data 'flamenco=love'
assert_equal({"flamenco"=> "love"}, @request.request_parameters)
end
def test_doesnt_interpret_request_uri_as_query_string_when_missing
@request.env['REQUEST_URI'] = 'foo'
assert_equal({}, @request.query_parameters)
end
end
class RackRequestContentTypeTest < BaseRackTest
def test_html_content_type_verification
@request.env['CONTENT_TYPE'] = Mime::HTML.to_s
assert @request.content_type.verify_request?
end
def test_xml_content_type_verification
@request.env['CONTENT_TYPE'] = Mime::XML.to_s
assert !@request.content_type.verify_request?
end
end
class RackRequestNeedsRewoundTest < BaseRackTest
def test_body_should_be_rewound
data = 'foo'
@env['rack.input'] = StringIO.new(data)
@env['CONTENT_LENGTH'] = data.length
@env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8'
# Read the request body by parsing params.
request = ActionController::Request.new(@env)
request.request_parameters
# Should have rewound the body.
assert_equal 0, request.body.pos
end
end
class RackResponseTest < BaseRackTest
def setup
super
@response = ActionController::Response.new
end
def test_simple_output
@response.body = "Hello, World!"
@response.prepare!
status, headers, body = @response.to_a
assert_equal 200, status
assert_equal({
"Content-Type" => "text/html; charset=utf-8",
"Cache-Control" => "private, max-age=0, must-revalidate",
"ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"',
"Content-Length" => "13"
}, headers)
parts = []
body.each { |part| parts << part }
assert_equal ["Hello, World!"], parts
end
def test_utf8_output
@response.body = [1090, 1077, 1089, 1090].pack("U*")
@response.prepare!
status, headers, body = @response.to_a
assert_equal 200, status
assert_equal({
"Content-Type" => "text/html; charset=utf-8",
"Cache-Control" => "private, max-age=0, must-revalidate",
"ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"',
"Content-Length" => "8"
}, headers)
end
def test_streaming_block
@response.body = Proc.new do |response, output|
5.times { |n| output.write(n) }
end
@response.prepare!
status, headers, body = @response.to_a
assert_equal 200, status
assert_equal({
"Content-Type" => "text/html; charset=utf-8",
"Cache-Control" => "no-cache"
}, headers)
parts = []
body.each { |part| parts << part }
assert_equal ["0", "1", "2", "3", "4"], parts
end
def test_streaming_block_with_flush_is_deprecated
@response.body = Proc.new do |response, output|
5.times do |n|
output.write(n)
output.flush
end
end
assert_deprecated(/output.flush is no longer needed/) do
@response.prepare!
status, headers, body = @response.to_a
parts = []
body.each { |part| parts << part }
end
end
end
class RackResponseHeadersTest < BaseRackTest
def setup
super
@response = ActionController::Response.new
@response.status = "200 OK"
end
def test_content_type
[204, 304].each do |c|
@response.status = c.to_s
assert !response_headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
end
[200, 302, 404, 500].each do |c|
@response.status = c.to_s
assert response_headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
end
end
def test_status
assert !response_headers.has_key?('Status')
end
private
def response_headers
@response.prepare!
@response.to_a[1]
end
end

View file

@ -1,139 +0,0 @@
require 'abstract_unit'
class Comment
attr_reader :id
def save; @id = 1 end
def new_record?; @id.nil? end
def name
@id.nil? ? 'new comment' : "comment ##{@id}"
end
end
class Comment::Nested < Comment; end
class Test::Unit::TestCase
protected
def comments_url
'http://www.example.com/comments'
end
def comment_url(comment)
"http://www.example.com/comments/#{comment.id}"
end
end
class RecordIdentifierTest < Test::Unit::TestCase
include ActionController::RecordIdentifier
def setup
@klass = Comment
@record = @klass.new
@singular = 'comment'
@plural = 'comments'
end
def test_dom_id_with_new_record
assert_equal "new_#{@singular}", dom_id(@record)
end
def test_dom_id_with_new_record_and_prefix
assert_equal "custom_prefix_#{@singular}", dom_id(@record, :custom_prefix)
end
def test_dom_id_with_saved_record
@record.save
assert_equal "#{@singular}_1", dom_id(@record)
end
def test_dom_id_with_prefix
@record.save
assert_equal "edit_#{@singular}_1", dom_id(@record, :edit)
end
def test_partial_path
expected = "#{@plural}/#{@singular}"
assert_equal expected, partial_path(@record)
assert_equal expected, partial_path(Comment)
end
def test_partial_path_with_namespaced_controller_path
expected = "admin/#{@plural}/#{@singular}"
assert_equal expected, partial_path(@record, "admin/posts")
assert_equal expected, partial_path(@klass, "admin/posts")
end
def test_partial_path_with_not_namespaced_controller_path
expected = "#{@plural}/#{@singular}"
assert_equal expected, partial_path(@record, "posts")
assert_equal expected, partial_path(@klass, "posts")
end
def test_dom_class
assert_equal @singular, dom_class(@record)
end
def test_dom_class_with_prefix
assert_equal "custom_prefix_#{@singular}", dom_class(@record, :custom_prefix)
end
def test_singular_class_name
assert_equal @singular, singular_class_name(@record)
end
def test_singular_class_name_for_class
assert_equal @singular, singular_class_name(@klass)
end
def test_plural_class_name
assert_equal @plural, plural_class_name(@record)
end
def test_plural_class_name_for_class
assert_equal @plural, plural_class_name(@klass)
end
private
def method_missing(method, *args)
RecordIdentifier.send(method, *args)
end
end
class NestedRecordIdentifierTest < RecordIdentifierTest
def setup
@klass = Comment::Nested
@record = @klass.new
@singular = 'comment_nested'
@plural = 'comment_nesteds'
end
def test_partial_path
expected = "comment/nesteds/nested"
assert_equal expected, partial_path(@record)
assert_equal expected, partial_path(Comment::Nested)
end
def test_partial_path_with_namespaced_controller_path
expected = "admin/comment/nesteds/nested"
assert_equal expected, partial_path(@record, "admin/posts")
assert_equal expected, partial_path(@klass, "admin/posts")
end
def test_partial_path_with_deeper_namespaced_controller_path
expected = "deeper/admin/comment/nesteds/nested"
assert_equal expected, partial_path(@record, "deeper/admin/posts")
assert_equal expected, partial_path(@klass, "deeper/admin/posts")
end
def test_partial_path_with_even_deeper_namespaced_controller_path
expected = "even/more/deeper/admin/comment/nesteds/nested"
assert_equal expected, partial_path(@record, "even/more/deeper/admin/posts")
assert_equal expected, partial_path(@klass, "even/more/deeper/admin/posts")
end
def test_partial_path_with_not_namespaced_controller_path
expected = "comment/nesteds/nested"
assert_equal expected, partial_path(@record, "posts")
assert_equal expected, partial_path(@klass, "posts")
end
end

View file

@ -1,285 +0,0 @@
require 'abstract_unit'
class WorkshopsController < ActionController::Base
end
class Workshop
attr_accessor :id, :new_record
def initialize(id, new_record)
@id, @new_record = id, new_record
end
def new_record?
@new_record
end
def to_s
id.to_s
end
end
class RedirectController < ActionController::Base
def simple_redirect
redirect_to :action => "hello_world"
end
def redirect_with_status
redirect_to({:action => "hello_world", :status => 301})
end
def redirect_with_status_hash
redirect_to({:action => "hello_world"}, {:status => 301})
end
def url_redirect_with_status
redirect_to("http://www.example.com", :status => :moved_permanently)
end
def url_redirect_with_status_hash
redirect_to("http://www.example.com", {:status => 301})
end
def relative_url_redirect_with_status
redirect_to("/things/stuff", :status => :found)
end
def relative_url_redirect_with_status_hash
redirect_to("/things/stuff", {:status => 301})
end
def redirect_to_back_with_status
redirect_to :back, :status => 307
end
def host_redirect
redirect_to :action => "other_host", :only_path => false, :host => 'other.test.host'
end
def module_redirect
redirect_to :controller => 'module_test/module_redirect', :action => "hello_world"
end
def redirect_with_assigns
@hello = "world"
redirect_to :action => "hello_world"
end
def redirect_to_url
redirect_to "http://www.rubyonrails.org/"
end
def redirect_to_url_with_unescaped_query_string
redirect_to "http://dev.rubyonrails.org/query?status=new"
end
def redirect_to_url_with_complex_scheme
redirect_to "x-test+scheme.complex:redirect"
end
def redirect_to_back
redirect_to :back
end
def redirect_to_existing_record
redirect_to Workshop.new(5, false)
end
def redirect_to_new_record
redirect_to Workshop.new(5, true)
end
def redirect_to_nil
redirect_to nil
end
def rescue_errors(e) raise e end
def rescue_action(e) raise end
protected
def dashbord_url(id, message)
url_for :action => "dashboard", :params => { "id" => id, "message" => message }
end
end
class RedirectTest < ActionController::TestCase
tests RedirectController
def test_simple_redirect
get :simple_redirect
assert_response :redirect
assert_equal "http://test.host/redirect/hello_world", redirect_to_url
end
def test_redirect_with_no_status
get :simple_redirect
assert_response 302
assert_equal "http://test.host/redirect/hello_world", redirect_to_url
end
def test_redirect_with_status
get :redirect_with_status
assert_response 301
assert_equal "http://test.host/redirect/hello_world", redirect_to_url
end
def test_redirect_with_status_hash
get :redirect_with_status_hash
assert_response 301
assert_equal "http://test.host/redirect/hello_world", redirect_to_url
end
def test_url_redirect_with_status
get :url_redirect_with_status
assert_response 301
assert_equal "http://www.example.com", redirect_to_url
end
def test_url_redirect_with_status_hash
get :url_redirect_with_status_hash
assert_response 301
assert_equal "http://www.example.com", redirect_to_url
end
def test_relative_url_redirect_with_status
get :relative_url_redirect_with_status
assert_response 302
assert_equal "http://test.host/things/stuff", redirect_to_url
end
def test_relative_url_redirect_with_status_hash
get :relative_url_redirect_with_status_hash
assert_response 301
assert_equal "http://test.host/things/stuff", redirect_to_url
end
def test_redirect_to_back_with_status
@request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
get :redirect_to_back_with_status
assert_response 307
assert_equal "http://www.example.com/coming/from", redirect_to_url
end
def test_simple_redirect_using_options
get :host_redirect
assert_response :redirect
assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host'
end
def test_module_redirect
get :module_redirect
assert_response :redirect
assert_redirected_to "http://test.host/module_test/module_redirect/hello_world"
end
def test_module_redirect_using_options
get :module_redirect
assert_response :redirect
assert_redirected_to :controller => 'module_test/module_redirect', :action => 'hello_world'
end
def test_redirect_with_assigns
get :redirect_with_assigns
assert_response :redirect
assert_equal "world", assigns["hello"]
end
def test_redirect_to_url
get :redirect_to_url
assert_response :redirect
assert_redirected_to "http://www.rubyonrails.org/"
end
def test_redirect_to_url_with_unescaped_query_string
get :redirect_to_url_with_unescaped_query_string
assert_response :redirect
assert_redirected_to "http://dev.rubyonrails.org/query?status=new"
end
def test_redirect_to_url_with_complex_scheme
get :redirect_to_url_with_complex_scheme
assert_response :redirect
assert_equal "x-test+scheme.complex:redirect", redirect_to_url
end
def test_redirect_to_back
@request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
get :redirect_to_back
assert_response :redirect
assert_equal "http://www.example.com/coming/from", redirect_to_url
end
def test_redirect_to_back_with_no_referer
assert_raise(ActionController::RedirectBackError) {
@request.env["HTTP_REFERER"] = nil
get :redirect_to_back
}
end
def test_redirect_to_record
ActionController::Routing::Routes.draw do |map|
map.resources :workshops
map.connect ':controller/:action/:id'
end
get :redirect_to_existing_record
assert_equal "http://test.host/workshops/5", redirect_to_url
assert_redirected_to Workshop.new(5, false)
get :redirect_to_new_record
assert_equal "http://test.host/workshops", redirect_to_url
assert_redirected_to Workshop.new(5, true)
end
def test_redirect_with_partial_params
get :module_redirect
assert_deprecated(/test_redirect_with_partial_params/) do
assert_redirected_to :action => 'hello_world'
end
end
def test_redirect_to_nil
assert_raise(ActionController::ActionControllerError) do
get :redirect_to_nil
end
end
end
module ModuleTest
class ModuleRedirectController < ::RedirectController
def module_redirect
redirect_to :controller => '/redirect', :action => "hello_world"
end
end
class ModuleRedirectTest < ActionController::TestCase
tests ModuleRedirectController
def test_simple_redirect
get :simple_redirect
assert_response :redirect
assert_equal "http://test.host/module_test/module_redirect/hello_world", redirect_to_url
end
def test_simple_redirect_using_options
get :host_redirect
assert_response :redirect
assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host'
end
def test_module_redirect
get :module_redirect
assert_response :redirect
assert_equal "http://test.host/redirect/hello_world", redirect_to_url
end
def test_module_redirect_using_options
get :module_redirect
assert_response :redirect
assert_redirected_to :controller => '/redirect', :action => "hello_world"
end
end
end

View file

@ -1,124 +0,0 @@
require 'abstract_unit'
class ReloaderTests < ActiveSupport::TestCase
Reloader = ActionController::Reloader
Dispatcher = ActionController::Dispatcher
class MyBody < Array
def initialize(&block)
@on_close = block
end
def foo
"foo"
end
def bar
"bar"
end
def close
@on_close.call if @on_close
end
end
def setup
@lock = Mutex.new
end
def test_it_reloads_the_application_before_yielding
Dispatcher.expects(:reload_application)
Reloader.run(@lock) do
[200, { "Content-Type" => "text/html" }, [""]]
end
end
def test_it_locks_before_yielding
lock = DummyMutex.new
Dispatcher.expects(:reload_application)
Reloader.run(lock) do
assert lock.locked?
[200, { "Content-Type" => "text/html" }, [""]]
end
assert lock.locked?
end
def test_it_unlocks_upon_calling_close_on_body
lock = DummyMutex.new
Dispatcher.expects(:reload_application)
headers, status, body = Reloader.run(lock) do
[200, { "Content-Type" => "text/html" }, [""]]
end
body.close
assert !lock.locked?
end
def test_it_unlocks_if_app_object_raises_exception
lock = DummyMutex.new
Dispatcher.expects(:reload_application)
assert_raise(RuntimeError) do
Reloader.run(lock) do
raise "oh no!"
end
end
assert !lock.locked?
end
def test_returned_body_object_always_responds_to_close
status, headers, body = Reloader.run(@lock) do
[200, { "Content-Type" => "text/html" }, [""]]
end
assert body.respond_to?(:close)
end
def test_returned_body_object_behaves_like_underlying_object
status, headers, body = Reloader.run(@lock) do
b = MyBody.new
b << "hello"
b << "world"
[200, { "Content-Type" => "text/html" }, b]
end
assert_equal 2, body.size
assert_equal "hello", body[0]
assert_equal "world", body[1]
assert_equal "foo", body.foo
assert_equal "bar", body.bar
end
def test_it_calls_close_on_underlying_object_when_close_is_called_on_body
close_called = false
status, headers, body = Reloader.run(@lock) do
b = MyBody.new do
close_called = true
end
[200, { "Content-Type" => "text/html" }, b]
end
body.close
assert close_called
end
def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object
status, headers, body = Reloader.run(@lock) do
[200, { "Content-Type" => "text/html" }, MyBody.new]
end
assert body.respond_to?(:size)
assert body.respond_to?(:each)
assert body.respond_to?(:foo)
assert body.respond_to?(:bar)
end
def test_it_doesnt_clean_up_the_application_after_call
Dispatcher.expects(:cleanup_application).never
status, headers, body = Reloader.run(@lock) do
[200, { "Content-Type" => "text/html" }, MyBody.new]
end
end
def test_it_cleans_up_the_application_when_close_is_called_on_body
Dispatcher.expects(:cleanup_application)
status, headers, body = Reloader.run(@lock) do
[200, { "Content-Type" => "text/html" }, MyBody.new]
end
body.close
end
end

File diff suppressed because it is too large Load diff

View file

@ -1,65 +0,0 @@
require 'abstract_unit'
class JsonParamsParsingTest < ActionController::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters
end
def parse
self.class.last_request_parameters = request.request_parameters
head :ok
end
end
def teardown
TestController.last_request_parameters = nil
end
test "parses json params for application json" do
assert_parses(
{"person" => {"name" => "David"}},
"{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/json' }
)
end
test "parses json params for application jsonrequest" do
assert_parses(
{"person" => {"name" => "David"}},
"{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/jsonrequest' }
)
end
test "logs error if parsing unsuccessful" do
with_test_routing do
begin
$stderr = StringIO.new
json = "[\"person]\": {\"name\": \"David\"}}"
post "/parse", json, {'CONTENT_TYPE' => 'application/json'}
assert_response :error
$stderr.rewind && err = $stderr.read
assert err =~ /Error occurred while parsing request parameters/
ensure
$stderr = STDERR
end
end
end
private
def assert_parses(expected, actual, headers = {})
with_test_routing do
post "/parse", actual, headers
assert_response :ok
assert_equal(expected, TestController.last_request_parameters)
end
end
def with_test_routing
with_routing do |set|
set.draw do |map|
map.connect ':action', :controller => "json_params_parsing_test/test"
end
yield
end
end
end

View file

@ -1,177 +0,0 @@
require 'abstract_unit'
class MultipartParamsParsingTest < ActionController::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters
end
def parse
self.class.last_request_parameters = request.request_parameters
head :ok
end
def read
render :text => "File: #{params[:uploaded_data].read}"
end
def read_complex
render :text => "File: #{params[:level0][:level1][0][:file_data].read}"
end
end
FIXTURE_PATH = File.dirname(__FILE__) + '/../../fixtures/multipart'
def teardown
TestController.last_request_parameters = nil
end
test "parses single parameter" do
assert_equal({ 'foo' => 'bar' }, parse_multipart('single_parameter'))
end
test "parses bracketed parameters" do
assert_equal({ 'foo' => { 'baz' => 'bar'}}, parse_multipart('bracketed_param'))
end
test "parses text file" do
params = parse_multipart('text_file')
assert_equal %w(file foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
assert_kind_of Tempfile, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
assert_equal 'contents', file.read
end
test "parses boundary problem file" do
params = parse_multipart('boundary_problem_file')
assert_equal %w(file foo), params.keys.sort
file = params['file']
foo = params['foo']
assert_kind_of Tempfile, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
assert_equal 'bar', foo
end
test "parses large text file" do
params = parse_multipart('large_text_file')
assert_equal %w(file foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
assert_kind_of Tempfile, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
assert ('a' * 20480) == file.read
end
test "parses binary file" do
params = parse_multipart('binary_file')
assert_equal %w(file flowers foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
assert_kind_of Tempfile, file
assert_equal 'file.csv', file.original_filename
assert_nil file.content_type
assert_equal 'contents', file.read
file = params['flowers']
assert_kind_of Tempfile, file
assert_equal 'flowers.jpg', file.original_filename
assert_equal "image/jpeg", file.content_type
assert_equal 19512, file.size
end
test "parses mixed files" do
params = parse_multipart('mixed_files')
assert_equal %w(files foo), params.keys.sort
assert_equal 'bar', params['foo']
# Ruby CGI doesn't handle multipart/mixed for us.
files = params['files']
assert_kind_of Tempfile, files
files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
assert_equal 19756, files.size
end
test "does not create tempfile if no file has been selected" do
params = parse_multipart('none')
assert_equal %w(submit-name), params.keys.sort
assert_equal 'Larry', params['submit-name']
assert_equal nil, params['files']
end
test "parses empty upload file" do
params = parse_multipart('empty')
assert_equal %w(files submit-name), params.keys.sort
assert_equal 'Larry', params['submit-name']
assert params['files']
assert_equal "", params['files'].read
end
test "uploads and reads binary file" do
with_test_routing do
fixture = FIXTURE_PATH + "/mona_lisa.jpg"
params = { :uploaded_data => fixture_file_upload(fixture, "image/jpg") }
post '/read', params
expected_length = 'File: '.length + File.size(fixture)
assert_equal expected_length, response.content_length
end
end
test "uploads and reads file" do
with_test_routing do
post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
assert_equal "File: Hello", response.body
end
end
test "uploads and reads file in complex parameter" do
with_test_routing do
post '/read_complex',
:level0 => {
:level1 => [ { :file_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain") }
]
}
assert_equal "File: Hello", response.body
end
end
private
def fixture(name)
File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
{ "rack.input" => file.read,
"CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x",
"CONTENT_LENGTH" => file.stat.size.to_s }
end
end
def parse_multipart(name)
with_test_routing do
headers = fixture(name)
post "/parse", headers.delete("rack.input"), headers
assert_response :ok
TestController.last_request_parameters
end
end
def with_test_routing
with_routing do |set|
set.draw do |map|
map.connect ':action', :controller => "multipart_params_parsing_test/test"
end
yield
end
end
end

View file

@ -1,120 +0,0 @@
require 'abstract_unit'
class QueryStringParsingTest < ActionController::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_query_parameters
end
def parse
self.class.last_query_parameters = request.query_parameters
head :ok
end
end
def teardown
TestController.last_query_parameters = nil
end
test "query string" do
assert_parses(
{"action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"},
"action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
)
end
test "deep query string" do
assert_parses(
{'x' => {'y' => {'z' => '10'}}},
"x[y][z]=10"
)
end
test "deep query string with array" do
assert_parses({'x' => {'y' => {'z' => ['10']}}}, 'x[y][z][]=10')
assert_parses({'x' => {'y' => {'z' => ['10', '5']}}}, 'x[y][z][]=10&x[y][z][]=5')
end
test "deep query string with array of hash" do
assert_parses({'x' => {'y' => [{'z' => '10'}]}}, 'x[y][][z]=10')
assert_parses({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, 'x[y][][z]=10&x[y][][w]=10')
assert_parses({'x' => {'y' => [{'z' => '10', 'v' => {'w' => '10'}}]}}, 'x[y][][z]=10&x[y][][v][w]=10')
end
test "deep query string with array of hashes with one pair" do
assert_parses({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, 'x[y][][z]=10&x[y][][z]=20')
end
test "deep query string with array of hashes with multiple pairs" do
assert_parses(
{'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}},
'x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b'
)
end
test "query string with nil" do
assert_parses(
{ "action" => "create_customer", "full_name" => ''},
"action=create_customer&full_name="
)
end
test "query string with array" do
assert_parses(
{ "action" => "create_customer", "selected" => ["1", "2", "3"]},
"action=create_customer&selected[]=1&selected[]=2&selected[]=3"
)
end
test "query string with amps" do
assert_parses(
{ "action" => "create_customer", "name" => "Don't & Does"},
"action=create_customer&name=Don%27t+%26+Does"
)
end
test "query string with many equal" do
assert_parses(
{ "action" => "create_customer", "full_name" => "abc=def=ghi"},
"action=create_customer&full_name=abc=def=ghi"
)
end
test "query string without equal" do
assert_parses({ "action" => nil }, "action")
end
test "query string with empty key" do
assert_parses(
{ "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
"action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save"
)
end
test "query string with many ampersands" do
assert_parses(
{ "action" => "create_customer", "full_name" => "David Heinemeier Hansson"},
"&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
)
end
test "unbalanced query string with array" do
assert_parses(
{'location' => ["1", "2"], 'age_group' => ["2"]},
"location[]=1&location[]=2&age_group[]=2"
)
end
private
def assert_parses(expected, actual)
with_routing do |set|
set.draw do |map|
map.connect ':action', :controller => "query_string_parsing_test/test"
end
get "/parse", actual
assert_response :ok
assert_equal(expected, TestController.last_query_parameters)
end
end
end

View file

@ -1,35 +0,0 @@
require 'abstract_unit'
require 'stringio'
class ActionController::TestRequestTest < ActiveSupport::TestCase
def setup
@request = ActionController::TestRequest.new
end
def test_test_request_has_session_options_initialized
assert @request.session_options
end
Rack::Session::Abstract::ID::DEFAULT_OPTIONS.each_key do |option|
test "test_rack_default_session_options_#{option}_exists_in_session_options_and_is_default" do
assert_equal(Rack::Session::Abstract::ID::DEFAULT_OPTIONS[option],
@request.session_options[option],
"Missing rack session default option #{option} in request.session_options")
end
test "test_rack_default_session_options_#{option}_exists_in_session_options" do
assert(@request.session_options.has_key?(option),
"Missing rack session option #{option} in request.session_options")
end
end
def test_session_id_exists_by_default
assert_not_nil(@request.session_options[:id])
end
def test_session_id_different_on_each_call
prev_id =
assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id])
end
end

View file

@ -1,146 +0,0 @@
require 'abstract_unit'
class UrlEncodedParamsParsingTest < ActionController::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters, :last_request_type
end
def parse
self.class.last_request_parameters = request.request_parameters
head :ok
end
end
def teardown
TestController.last_request_parameters = nil
end
test "parses unbalanced query string with array" do
assert_parses(
{'location' => ["1", "2"], 'age_group' => ["2"]},
"location[]=1&location[]=2&age_group[]=2"
)
end
test "parses nested hash" do
query = [
"note[viewers][viewer][][type]=User",
"note[viewers][viewer][][id]=1",
"note[viewers][viewer][][type]=Group",
"note[viewers][viewer][][id]=2"
].join("&")
expected = { "note" => { "viewers"=>{"viewer"=>[{ "id"=>"1", "type"=>"User"}, {"type"=>"Group", "id"=>"2"} ]} } }
assert_parses(expected, query)
end
test "parses more complex nesting" do
query = [
"customers[boston][first][name]=David",
"customers[boston][first][url]=http://David",
"customers[boston][second][name]=Allan",
"customers[boston][second][url]=http://Allan",
"something_else=blah",
"something_nil=",
"something_empty=",
"products[first]=Apple Computer",
"products[second]=Pc",
"=Save"
].join("&")
expected = {
"customers" => {
"boston" => {
"first" => {
"name" => "David",
"url" => "http://David"
},
"second" => {
"name" => "Allan",
"url" => "http://Allan"
}
}
},
"something_else" => "blah",
"something_empty" => "",
"something_nil" => "",
"products" => {
"first" => "Apple Computer",
"second" => "Pc"
}
}
assert_parses expected, query
end
test "parses params with array" do
query = "selected[]=1&selected[]=2&selected[]=3"
expected = { "selected" => [ "1", "2", "3" ] }
assert_parses expected, query
end
test "parses params with nil key" do
query = "=&test2=value1"
expected = { "test2" => "value1" }
assert_parses expected, query
end
test "parses params with array prefix and hashes" do
query = "a[][b][c]=d"
expected = {"a" => [{"b" => {"c" => "d"}}]}
assert_parses expected, query
end
test "parses params with complex nesting" do
query = "a[][b][c][][d][]=e"
expected = {"a" => [{"b" => {"c" => [{"d" => ["e"]}]}}]}
assert_parses expected, query
end
test "parses params with file path" do
query = [
"customers[boston][first][name]=David",
"something_else=blah",
"logo=#{File.expand_path(__FILE__)}"
].join("&")
expected = {
"customers" => {
"boston" => {
"first" => {
"name" => "David"
}
}
},
"something_else" => "blah",
"logo" => File.expand_path(__FILE__),
}
assert_parses expected, query
end
test "parses params with Safari 2 trailing null character" do
query = "selected[]=1&selected[]=2&selected[]=3\0"
expected = { "selected" => [ "1", "2", "3" ] }
assert_parses expected, query
end
private
def with_test_routing
with_routing do |set|
set.draw do |map|
map.connect ':action', :controller => "url_encoded_params_parsing_test/test"
end
yield
end
end
def assert_parses(expected, actual)
with_test_routing do
post "/parse", actual
assert_response :ok
assert_equal(expected, TestController.last_request_parameters)
end
end
end

View file

@ -1,103 +0,0 @@
require 'abstract_unit'
class XmlParamsParsingTest < ActionController::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters
end
def parse
self.class.last_request_parameters = request.request_parameters
head :ok
end
end
def teardown
TestController.last_request_parameters = nil
end
test "parses hash params" do
with_test_routing do
xml = "<person><name>David</name></person>"
post "/parse", xml, default_headers
assert_response :ok
assert_equal({"person" => {"name" => "David"}}, TestController.last_request_parameters)
end
end
test "parses single file" do
with_test_routing do
xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></person>"
post "/parse", xml, default_headers
assert_response :ok
person = TestController.last_request_parameters
assert_equal "image/jpg", person['person']['avatar'].content_type
assert_equal "me.jpg", person['person']['avatar'].original_filename
assert_equal "ABC", person['person']['avatar'].read
end
end
test "logs 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
assert_response :error
$stderr.rewind && err = $stderr.read
assert err =~ /Error occurred while parsing request parameters/
ensure
$stderr = STDERR
end
end
end
test "parses multiple files" do
xml = <<-end_body
<person>
<name>David</name>
<avatars>
<avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar>
<avatar type='file' name='you.gif' content_type='image/gif'>#{ActiveSupport::Base64.encode64('DEF')}</avatar>
</avatars>
</person>
end_body
with_test_routing do
post "/parse", xml, default_headers
assert_response :ok
end
person = TestController.last_request_parameters
assert_equal "image/jpg", person['person']['avatars']['avatar'].first.content_type
assert_equal "me.jpg", person['person']['avatars']['avatar'].first.original_filename
assert_equal "ABC", person['person']['avatars']['avatar'].first.read
assert_equal "image/gif", person['person']['avatars']['avatar'].last.content_type
assert_equal "you.gif", person['person']['avatars']['avatar'].last.original_filename
assert_equal "DEF", person['person']['avatars']['avatar'].last.read
end
private
def with_test_routing
with_routing do |set|
set.draw do |map|
map.connect ':action', :controller => "xml_params_parsing_test/test"
end
yield
end
end
def default_headers
{'CONTENT_TYPE' => 'application/xml'}
end
end
class LegacyXmlParamsParsingTest < XmlParamsParsingTest
private
def default_headers
{'HTTP_X_POST_DATA_FORMAT' => 'xml'}
end
end

View file

@ -1,265 +0,0 @@
require 'abstract_unit'
require 'digest/sha1'
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
end
# common controller actions
module RequestForgeryProtectionActions
def index
render :inline => "<%= form_tag('/') {} %>"
end
def show_button
render :inline => "<%= button_to('New', '/') {} %>"
end
def remote_form
render :inline => "<% form_remote_tag(:url => '/') {} %>"
end
def unsafe
render :text => 'pwn'
end
def rescue_action(e) raise e end
end
# sample controllers
class RequestForgeryProtectionController < ActionController::Base
include RequestForgeryProtectionActions
protect_from_forgery :only => :index
end
class FreeCookieController < RequestForgeryProtectionController
self.allow_forgery_protection = false
def index
render :inline => "<%= form_tag('/') {} %>"
end
def show_button
render :inline => "<%= button_to('New', '/') {} %>"
end
end
class CustomAuthenticityParamController < RequestForgeryProtectionController
def form_authenticity_param
'foobar'
end
end
# common test methods
module RequestForgeryProtectionTests
def teardown
ActionController::Base.request_forgery_protection_token = nil
end
def test_should_render_form_with_token_tag
get :index
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
end
def test_should_render_button_to_with_token_tag
get :show_button
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
end
def test_should_render_remote_form_with_only_one_token_parameter
get :remote_form
assert_equal 1, @response.body.scan(@token).size
end
def test_should_allow_get
get :index
assert_response :success
end
def test_should_allow_post_without_token_on_unsafe_action
post :unsafe
assert_response :success
end
def test_should_not_allow_html_post_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html }
end
def test_should_not_allow_html_put_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html }
end
def test_should_not_allow_html_delete_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html }
end
def test_should_allow_api_formatted_post_without_token
assert_nothing_raised do
post :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_put_without_token
assert_nothing_raised do
put :index, :format => 'xml'
end
end
def test_should_allow_api_formatted_delete_without_token
assert_nothing_raised do
delete :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token
assert_raise(ActionController::InvalidAuthenticityToken) do
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
post :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token
assert_raise(ActionController::InvalidAuthenticityToken) do
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
put :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token
assert_raise(ActionController::InvalidAuthenticityToken) do
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
delete :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token
assert_raise(ActionController::InvalidAuthenticityToken) do
@request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
post :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token
assert_raise(ActionController::InvalidAuthenticityToken) do
@request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
put :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token
assert_raise(ActionController::InvalidAuthenticityToken) do
@request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
delete :index, :format => 'xml'
end
end
def test_should_allow_xhr_post_without_token
assert_nothing_raised { xhr :post, :index }
end
def test_should_allow_xhr_put_without_token
assert_nothing_raised { xhr :put, :index }
end
def test_should_allow_xhr_delete_without_token
assert_nothing_raised { xhr :delete, :index }
end
def test_should_allow_xhr_post_with_encoded_form_content_type_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_nothing_raised { xhr :post, :index }
end
def test_should_allow_post_with_token
post :index, :authenticity_token => @token
assert_response :success
end
def test_should_allow_put_with_token
put :index, :authenticity_token => @token
assert_response :success
end
def test_should_allow_delete_with_token
delete :index, :authenticity_token => @token
assert_response :success
end
def test_should_allow_post_with_xml
@request.env['CONTENT_TYPE'] = Mime::XML.to_s
post :index, :format => 'xml'
assert_response :success
end
def test_should_allow_put_with_xml
@request.env['CONTENT_TYPE'] = Mime::XML.to_s
put :index, :format => 'xml'
assert_response :success
end
def test_should_allow_delete_with_xml
@request.env['CONTENT_TYPE'] = Mime::XML.to_s
delete :index, :format => 'xml'
assert_response :success
end
end
# OK let's get our test on
class RequestForgeryProtectionControllerTest < ActionController::TestCase
include RequestForgeryProtectionTests
def setup
@controller = RequestForgeryProtectionController.new
@request = ActionController::TestRequest.new
@request.format = :html
@response = ActionController::TestResponse.new
@token = "cf50faa3fe97702ca1ae"
ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
ActionController::Base.request_forgery_protection_token = :authenticity_token
end
end
class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@token = "cf50faa3fe97702ca1ae"
ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
end
def test_should_not_render_form_with_token_tag
get :index
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
end
def test_should_not_render_button_to_with_token_tag
get :show_button
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
end
def test_should_allow_all_methods_without_token
[:post, :put, :delete].each do |method|
assert_nothing_raised { send(method, :index)}
end
end
end
class CustomAuthenticityParamControllerTest < ActionController::TestCase
def setup
ActionController::Base.request_forgery_protection_token = :authenticity_token
end
def test_should_allow_custom_token
post :index, :authenticity_token => 'foobar'
assert_response :ok
end
end

View file

@ -1,395 +0,0 @@
require 'abstract_unit'
class RequestTest < ActiveSupport::TestCase
def setup
ActionController::Base.relative_url_root = nil
end
def teardown
ActionController::Base.relative_url_root = nil
end
def test_remote_ip
request = stub_request 'REMOTE_ADDR' => '1.2.3.4'
assert_equal '1.2.3.4', request.remote_ip
request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6'
assert_equal '1.2.3.4', request.remote_ip
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
request = stub_request 'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.16.0.1,3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '127.0.0.1,3.4.5.6'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1'
assert_equal 'unknown', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4'
assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1',
'HTTP_CLIENT_IP' => '2.2.2.2'
e = assert_raise(ActionController::ActionControllerError) {
request.remote_ip
}
assert_match /IP spoofing attack/, e.message
assert_match /HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message
assert_match /HTTP_CLIENT_IP="2.2.2.2"/, e.message
# turn IP Spoofing detection off.
# This is useful for sites that are aimed at non-IP clients. The typical
# example is WAP. Since the cellular network is not IP based, it's a
# leap of faith to assume that their proxies are ever going to set the
# HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly.
ActionController::Base.ip_spoofing_check = false
request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1',
'HTTP_CLIENT_IP' => '2.2.2.2'
assert_equal '2.2.2.2', request.remote_ip
ActionController::Base.ip_spoofing_check = true
request = stub_request 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, 9.9.9.9'
assert_equal '9.9.9.9', request.remote_ip
end
def test_domains
request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org'
assert_equal "rubyonrails.org", request.domain
request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
assert_equal "rubyonrails.co.uk", request.domain(2)
request = stub_request 'HTTP_HOST' => "192.168.1.200"
assert_nil request.domain
request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"
assert_nil request.domain
request = stub_request 'HTTP_HOST' => "192.168.1.200.com"
assert_equal "200.com", request.domain
end
def test_subdomains
request = stub_request 'HTTP_HOST' => "www.rubyonrails.org"
assert_equal %w( www ), request.subdomains
request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
assert_equal %w( www ), request.subdomains(2)
request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"
assert_equal %w( dev www ), request.subdomains(2)
request = stub_request 'HTTP_HOST' => "foobar.foobar.com"
assert_equal %w( foobar ), request.subdomains
request = stub_request 'HTTP_HOST' => "192.168.1.200"
assert_equal [], request.subdomains
request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"
assert_equal [], request.subdomains
request = stub_request 'HTTP_HOST' => "192.168.1.200.com"
assert_equal %w( 192 168 1 ), request.subdomains
request = stub_request 'HTTP_HOST' => nil
assert_equal [], request.subdomains
end
def test_port_string
request = stub_request 'HTTP_HOST' => 'www.example.org:80'
assert_equal "", request.port_string
request = stub_request 'HTTP_HOST' => 'www.example.org:8080'
assert_equal ":8080", request.port_string
end
def test_request_uri
request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri?mapped=1"
assert_equal "/path/of/some/uri?mapped=1", request.request_uri
assert_equal "/path/of/some/uri", request.path
request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri"
assert_equal "/path/of/some/uri", request.request_uri
assert_equal "/path/of/some/uri", request.path
request = stub_request 'REQUEST_URI' => "/path/of/some/uri"
assert_equal "/path/of/some/uri", request.request_uri
assert_equal "/path/of/some/uri", request.path
request = stub_request 'REQUEST_URI' => "/"
assert_equal "/", request.request_uri
assert_equal "/", request.path
request = stub_request 'REQUEST_URI' => "/?m=b"
assert_equal "/?m=b", request.request_uri
assert_equal "/", request.path
request = stub_request 'REQUEST_URI' => "/", 'SCRIPT_NAME' => '/dispatch.cgi'
assert_equal "/", request.request_uri
assert_equal "/", request.path
ActionController::Base.relative_url_root = "/hieraki"
request = stub_request 'REQUEST_URI' => "/hieraki/", 'SCRIPT_NAME' => "/hieraki/dispatch.cgi"
assert_equal "/hieraki/", request.request_uri
assert_equal "/", request.path
ActionController::Base.relative_url_root = nil
ActionController::Base.relative_url_root = "/collaboration/hieraki"
request = stub_request 'REQUEST_URI' => "/collaboration/hieraki/books/edit/2",
'SCRIPT_NAME' => "/collaboration/hieraki/dispatch.cgi"
assert_equal "/collaboration/hieraki/books/edit/2", request.request_uri
assert_equal "/books/edit/2", request.path
ActionController::Base.relative_url_root = nil
# The following tests are for when REQUEST_URI is not supplied (as in IIS)
request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1",
'SCRIPT_NAME' => nil,
'REQUEST_URI' => nil
assert_equal "/path/of/some/uri?mapped=1", request.request_uri
assert_equal "/path/of/some/uri", request.path
ActionController::Base.relative_url_root = '/path'
request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1",
'SCRIPT_NAME' => "/path/dispatch.rb",
'REQUEST_URI' => nil
assert_equal "/path/of/some/uri?mapped=1", request.request_uri
assert_equal "/of/some/uri", request.path
ActionController::Base.relative_url_root = nil
request = stub_request 'PATH_INFO' => "/path/of/some/uri",
'SCRIPT_NAME' => nil,
'REQUEST_URI' => nil
assert_equal "/path/of/some/uri", request.request_uri
assert_equal "/path/of/some/uri", request.path
request = stub_request 'PATH_INFO' => '/', 'REQUEST_URI' => nil
assert_equal "/", request.request_uri
assert_equal "/", request.path
request = stub_request 'PATH_INFO' => '/?m=b', 'REQUEST_URI' => nil
assert_equal "/?m=b", request.request_uri
assert_equal "/", request.path
request = stub_request 'PATH_INFO' => "/",
'SCRIPT_NAME' => "/dispatch.cgi",
'REQUEST_URI' => nil
assert_equal "/", request.request_uri
assert_equal "/", request.path
ActionController::Base.relative_url_root = '/hieraki'
request = stub_request 'PATH_INFO' => "/hieraki/",
'SCRIPT_NAME' => "/hieraki/dispatch.cgi",
'REQUEST_URI' => nil
assert_equal "/hieraki/", request.request_uri
assert_equal "/", request.path
ActionController::Base.relative_url_root = nil
request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi'
ActionController::Base.relative_url_root = '/hieraki'
assert_equal "/dispatch.cgi", request.path
ActionController::Base.relative_url_root = nil
request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi'
ActionController::Base.relative_url_root = '/foo'
assert_equal "/hieraki/dispatch.cgi", request.path
ActionController::Base.relative_url_root = nil
# This test ensures that Rails uses REQUEST_URI over PATH_INFO
ActionController::Base.relative_url_root = nil
request = stub_request 'REQUEST_URI' => "/some/path",
'PATH_INFO' => "/another/path",
'SCRIPT_NAME' => "/dispatch.cgi"
assert_equal "/some/path", request.request_uri
assert_equal "/some/path", request.path
end
def test_host_with_default_port
request = stub_request 'HTTP_HOST' => 'rubyonrails.org:80'
assert_equal "rubyonrails.org", request.host_with_port
end
def test_host_with_non_default_port
request = stub_request 'HTTP_HOST' => 'rubyonrails.org:81'
assert_equal "rubyonrails.org:81", request.host_with_port
end
def test_server_software
request = stub_request
assert_equal nil, request.server_software
request = stub_request 'SERVER_SOFTWARE' => 'Apache3.422'
assert_equal 'apache', request.server_software
request = stub_request 'SERVER_SOFTWARE' => 'lighttpd(1.1.4)'
assert_equal 'lighttpd', request.server_software
end
def test_xml_http_request
request = stub_request
assert !request.xml_http_request?
assert !request.xhr?
request = stub_request 'HTTP_X_REQUESTED_WITH' => 'DefinitelyNotAjax1.0'
assert !request.xml_http_request?
assert !request.xhr?
request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'
assert request.xml_http_request?
assert request.xhr?
end
def test_reports_ssl
request = stub_request
assert !request.ssl?
request = stub_request 'HTTPS' => 'on'
assert request.ssl?
end
def test_reports_ssl_when_proxied_via_lighttpd
request = stub_request
assert !request.ssl?
request = stub_request 'HTTP_X_FORWARDED_PROTO' => 'https'
assert request.ssl?
end
def test_symbolized_request_methods
[:get, :post, :put, :delete].each do |method|
request = stub_request 'REQUEST_METHOD' => method.to_s.upcase
assert_equal method, request.method
end
end
def test_invalid_http_method_raises_exception
assert_raise(ActionController::UnknownHttpMethod) do
request = stub_request 'REQUEST_METHOD' => 'RANDOM_METHOD'
request.request_method
end
end
def test_allow_method_hacking_on_post
[:get, :head, :options, :put, :post, :delete].each do |method|
request = stub_request 'REQUEST_METHOD' => method.to_s.upcase
assert_equal(method == :head ? :get : method, request.method)
end
end
def test_restrict_method_hacking
[:get, :put, :delete].each do |method|
request = stub_request 'REQUEST_METHOD' => method.to_s.upcase,
'action_controller.request.request_parameters' => { :_method => 'put' }
assert_equal method, request.method
end
end
def test_head_masquerading_as_get
request = stub_request 'REQUEST_METHOD' => 'HEAD'
assert_equal :get, request.method
assert request.get?
assert request.head?
end
def test_xml_format
request = stub_request
request.expects(:parameters).at_least_once.returns({ :format => 'xml' })
assert_equal Mime::XML, request.format
end
def test_xhtml_format
request = stub_request
request.expects(:parameters).at_least_once.returns({ :format => 'xhtml' })
assert_equal Mime::HTML, request.format
end
def test_txt_format
request = stub_request
request.expects(:parameters).at_least_once.returns({ :format => 'txt' })
assert_equal Mime::TEXT, request.format
end
def test_xml_http_request
ActionController::Base.use_accept_header, old =
false, ActionController::Base.use_accept_header
request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'
request.expects(:parameters).at_least_once.returns({})
assert request.xhr?
assert_equal Mime::JS, request.format
ensure
ActionController::Base.use_accept_header = old
end
def test_content_type
request = stub_request 'CONTENT_TYPE' => 'text/html'
assert_equal Mime::HTML, request.content_type
end
def test_can_override_format_with_parameter
request = stub_request
request.expects(:parameters).at_least_once.returns({ :format => :txt })
assert !request.format.xml?
request = stub_request
request.expects(:parameters).at_least_once.returns({ :format => :xml })
assert request.format.xml?
end
def test_content_no_type
request = stub_request
assert_equal nil, request.content_type
end
def test_content_type_xml
request = stub_request 'CONTENT_TYPE' => 'application/xml'
assert_equal Mime::XML, request.content_type
end
def test_content_type_with_charset
request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8'
assert_equal Mime::XML, request.content_type
end
def test_user_agent
request = stub_request 'HTTP_USER_AGENT' => 'TestAgent'
assert_equal 'TestAgent', request.user_agent
end
def test_parameters
request = stub_request
request.stubs(:request_parameters).returns({ "foo" => 1 })
request.stubs(:query_parameters).returns({ "bar" => 2 })
assert_equal({"foo" => 1, "bar" => 2}, request.parameters)
assert_equal({"foo" => 1}, request.request_parameters)
assert_equal({"bar" => 2}, request.query_parameters)
end
protected
def stub_request(env={})
ActionController::Request.new(env)
end
end

View file

@ -1,541 +0,0 @@
require 'abstract_unit'
class RescueController < ActionController::Base
class NotAuthorized < StandardError
end
class NotAuthorizedToRescueAsString < StandardError
end
class RecordInvalid < StandardError
end
class RecordInvalidToRescueAsString < StandardError
end
class NotAllowed < StandardError
end
class NotAllowedToRescueAsString < StandardError
end
class InvalidRequest < StandardError
end
class InvalidRequestToRescueAsString < StandardError
end
class BadGateway < StandardError
end
class BadGatewayToRescueAsString < StandardError
end
class ResourceUnavailable < StandardError
end
class ResourceUnavailableToRescueAsString < StandardError
end
# We use a fully-qualified name in some strings, and a relative constant
# name in some other to test correct handling of both cases.
rescue_from NotAuthorized, :with => :deny_access
rescue_from 'RescueController::NotAuthorizedToRescueAsString', :with => :deny_access
rescue_from RecordInvalid, :with => :show_errors
rescue_from 'RescueController::RecordInvalidToRescueAsString', :with => :show_errors
rescue_from NotAllowed, :with => proc { head :forbidden }
rescue_from 'RescueController::NotAllowedToRescueAsString', :with => proc { head :forbidden }
rescue_from InvalidRequest, :with => proc { |exception| render :text => exception.message }
rescue_from 'InvalidRequestToRescueAsString', :with => proc { |exception| render :text => exception.message }
rescue_from BadGateway do
head :status => 502
end
rescue_from 'BadGatewayToRescueAsString' do
head :status => 502
end
rescue_from ResourceUnavailable do |exception|
render :text => exception.message
end
rescue_from 'ResourceUnavailableToRescueAsString' do |exception|
render :text => exception.message
end
# This is a Dispatcher exception and should be in ApplicationController.
rescue_from ActionController::RoutingError do
render :text => 'no way'
end
before_filter(:only => :before_filter_raises) { raise 'umm nice' }
def before_filter_raises
end
def raises
render :text => 'already rendered'
raise "don't panic!"
end
def method_not_allowed
raise ActionController::MethodNotAllowed.new(:get, :head, :put)
end
def not_implemented
raise ActionController::NotImplemented.new(:get, :put)
end
def not_authorized
raise NotAuthorized
end
def not_authorized_raise_as_string
raise NotAuthorizedToRescueAsString
end
def not_allowed
raise NotAllowed
end
def not_allowed_raise_as_string
raise NotAllowedToRescueAsString
end
def invalid_request
raise InvalidRequest
end
def invalid_request_raise_as_string
raise InvalidRequestToRescueAsString
end
def record_invalid
raise RecordInvalid
end
def record_invalid_raise_as_string
raise RecordInvalidToRescueAsString
end
def bad_gateway
raise BadGateway
end
def bad_gateway_raise_as_string
raise BadGatewayToRescueAsString
end
def resource_unavailable
raise ResourceUnavailable
end
def resource_unavailable_raise_as_string
raise ResourceUnavailableToRescueAsString
end
def missing_template
end
protected
def deny_access
head :forbidden
end
def show_errors(exception)
head :unprocessable_entity
end
end
class RescueControllerTest < ActionController::TestCase
FIXTURE_PUBLIC = "#{File.dirname(__FILE__)}/../fixtures".freeze
setup :set_all_requests_local
setup :populate_exception_object
def set_all_requests_local
RescueController.consider_all_requests_local = true
@request.remote_addr = '1.2.3.4'
@request.host = 'example.com'
end
def populate_exception_object
begin
raise 'foo'
rescue => @exception
end
end
def test_rescue_exceptions_raised_by_filters
with_rails_root FIXTURE_PUBLIC do
with_all_requests_local false do
get :before_filter_raises
end
end
assert_response :internal_server_error
end
def test_rescue_action_locally_if_all_requests_local
@controller.expects(:local_request?).never
@controller.expects(:rescue_action_locally).with(@exception)
@controller.expects(:rescue_action_in_public).never
with_all_requests_local do
@controller.send :rescue_action, @exception
end
end
def test_rescue_action_locally_if_remote_addr_is_localhost
@controller.expects(:local_request?).returns(true)
@controller.expects(:rescue_action_locally).with(@exception)
@controller.expects(:rescue_action_in_public).never
with_all_requests_local false do
@controller.send :rescue_action, @exception
end
end
def test_rescue_action_in_public_otherwise
@controller.expects(:local_request?).returns(false)
@controller.expects(:rescue_action_locally).never
@controller.expects(:rescue_action_in_public).with(@exception)
with_all_requests_local false do
@controller.send :rescue_action, @exception
end
end
def test_rescue_action_in_public_with_localized_error_file
# Change locale
old_locale = I18n.locale
I18n.locale = :da
with_rails_root FIXTURE_PUBLIC do
with_all_requests_local false do
get :raises
end
end
assert_response :internal_server_error
body = File.read("#{FIXTURE_PUBLIC}/public/500.da.html")
assert_equal body, @response.body
ensure
I18n.locale = old_locale
end
def test_rescue_action_in_public_with_error_file
with_rails_root FIXTURE_PUBLIC do
with_all_requests_local false do
get :raises
end
end
assert_response :internal_server_error
body = File.read("#{FIXTURE_PUBLIC}/public/500.html")
assert_equal body, @response.body
end
def test_rescue_action_in_public_without_error_file
with_rails_root '/tmp' do
with_all_requests_local false do
get :raises
end
end
assert_response :internal_server_error
assert_equal ' ', @response.body
end
def test_rescue_unknown_action_in_public_with_error_file
with_rails_root FIXTURE_PUBLIC do
with_all_requests_local false do
get :foobar_doesnt_exist
end
end
assert_response :not_found
body = File.read("#{FIXTURE_PUBLIC}/public/404.html")
assert_equal body, @response.body
end
def test_rescue_unknown_action_in_public_without_error_file
with_rails_root '/tmp' do
with_all_requests_local false do
get :foobar_doesnt_exist
end
end
assert_response :not_found
assert_equal ' ', @response.body
end
def test_rescue_missing_template_in_public
with_rails_root FIXTURE_PUBLIC do
with_all_requests_local true do
get :missing_template
end
end
assert_response :internal_server_error
assert @response.body.include?('missing_template'), "Response should include the template name."
end
def test_rescue_action_locally
get :raises
assert_response :internal_server_error
assert_template 'diagnostics.erb'
assert @response.body.include?('RescueController#raises'), "Response should include controller and action."
assert @response.body.include?("don't panic"), "Response should include exception message."
end
def test_local_request_when_remote_addr_is_localhost
@controller.expects(:request).returns(@request).at_least(10)
['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|
with_remote_addr ip_address do
assert @controller.send(:local_request?)
end
end
end
def test_local_request_when_remote_addr_isnt_locahost
@controller.expects(:request).returns(@request).at_least(4)
with_remote_addr '1.2.3.4' do
assert !@controller.send(:local_request?)
end
with_remote_addr '2002::102:304' do
assert !@controller.send(:local_request?)
end
end
def test_rescue_responses
responses = ActionController::Base.rescue_responses
assert_equal ActionController::Rescue::DEFAULT_RESCUE_RESPONSE, responses.default
assert_equal ActionController::Rescue::DEFAULT_RESCUE_RESPONSE, responses[Exception.new]
assert_equal :not_found, responses[ActionController::RoutingError.name]
assert_equal :not_found, responses[ActionController::UnknownAction.name]
assert_equal :not_found, responses['ActiveRecord::RecordNotFound']
assert_equal :conflict, responses['ActiveRecord::StaleObjectError']
assert_equal :unprocessable_entity, responses['ActiveRecord::RecordInvalid']
assert_equal :unprocessable_entity, responses['ActiveRecord::RecordNotSaved']
assert_equal :method_not_allowed, responses['ActionController::MethodNotAllowed']
assert_equal :not_implemented, responses['ActionController::NotImplemented']
end
def test_rescue_templates
templates = ActionController::Base.rescue_templates
assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates.default
assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates[Exception.new]
assert_equal 'missing_template', templates[ActionView::MissingTemplate.name]
assert_equal 'routing_error', templates[ActionController::RoutingError.name]
assert_equal 'unknown_action', templates[ActionController::UnknownAction.name]
assert_equal 'template_error', templates[ActionView::TemplateError.name]
end
def test_not_implemented
with_all_requests_local false do
with_rails_public_path(".") do
head :not_implemented
end
end
assert_response :not_implemented
assert_equal "GET, PUT", @response.headers['Allow']
end
def test_method_not_allowed
with_all_requests_local false do
with_rails_public_path(".") do
get :method_not_allowed
end
end
assert_response :method_not_allowed
assert_equal "GET, HEAD, PUT", @response.headers['Allow']
end
def test_rescue_handler
get :not_authorized
assert_response :forbidden
end
def test_rescue_handler_string
get :not_authorized_raise_as_string
assert_response :forbidden
end
def test_rescue_handler_with_argument
@controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) }
get :record_invalid
end
def test_rescue_handler_with_argument_as_string
@controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) }
get :record_invalid_raise_as_string
end
def test_proc_rescue_handler
get :not_allowed
assert_response :forbidden
end
def test_proc_rescue_handler_as_string
get :not_allowed_raise_as_string
assert_response :forbidden
end
def test_proc_rescue_handle_with_argument
get :invalid_request
assert_equal "RescueController::InvalidRequest", @response.body
end
def test_proc_rescue_handle_with_argument_as_string
get :invalid_request_raise_as_string
assert_equal "RescueController::InvalidRequestToRescueAsString", @response.body
end
def test_block_rescue_handler
get :bad_gateway
assert_response 502
end
def test_block_rescue_handler_as_string
get :bad_gateway_raise_as_string
assert_response 502
end
def test_block_rescue_handler_with_argument
get :resource_unavailable
assert_equal "RescueController::ResourceUnavailable", @response.body
end
def test_block_rescue_handler_with_argument_as_string
get :resource_unavailable_raise_as_string
assert_equal "RescueController::ResourceUnavailableToRescueAsString", @response.body
end
def test_rescue_dispatcher_exceptions
env = @request.env
env["action_controller.rescue.request"] = @request
env["action_controller.rescue.response"] = @response
RescueController.call_with_exception(env, ActionController::RoutingError.new("Route not found"))
assert_equal "no way", @response.body
end
def test_rescue_dispatcher_exceptions_without_request_set
@request.env['REQUEST_URI'] = '/no_way'
response = RescueController.call_with_exception(@request.env, ActionController::RoutingError.new("Route not found"))
assert_kind_of ActionController::Response, response
assert_equal "no way", response.body
end
protected
def with_all_requests_local(local = true)
old_local, ActionController::Base.consider_all_requests_local =
ActionController::Base.consider_all_requests_local, local
yield
ensure
ActionController::Base.consider_all_requests_local = old_local
end
def with_remote_addr(addr)
old_remote_addr, @request.remote_addr = @request.remote_addr, addr
yield
ensure
@request.remote_addr = old_remote_addr
end
def with_rails_public_path(rails_root)
old_rails = Object.const_get(:Rails) rescue nil
mod = Object.const_set(:Rails, Module.new)
(class << mod; self; end).instance_eval do
define_method(:public_path) { "#{rails_root}/public" }
end
yield
ensure
Object.module_eval { remove_const(:Rails) } if defined?(Rails)
Object.const_set(:Rails, old_rails) if old_rails
end
def with_rails_root(path = nil,&block)
old_rails_root = RAILS_ROOT if defined?(RAILS_ROOT)
if path
silence_warnings { Object.const_set(:RAILS_ROOT, path) }
else
Object.remove_const(:RAILS_ROOT) rescue nil
end
with_rails_public_path(path, &block)
ensure
if old_rails_root
silence_warnings { Object.const_set(:RAILS_ROOT, old_rails_root) }
else
Object.remove_const(:RAILS_ROOT) rescue nil
end
end
end
class ExceptionInheritanceRescueController < ActionController::Base
class ParentException < StandardError
end
class ChildException < ParentException
end
class GrandchildException < ChildException
end
rescue_from ChildException, :with => lambda { head :ok }
rescue_from ParentException, :with => lambda { head :created }
rescue_from GrandchildException, :with => lambda { head :no_content }
def raise_parent_exception
raise ParentException
end
def raise_child_exception
raise ChildException
end
def raise_grandchild_exception
raise GrandchildException
end
end
class ExceptionInheritanceRescueControllerTest < ActionController::TestCase
def test_bottom_first
get :raise_grandchild_exception
assert_response :no_content
end
def test_inheritance_works
get :raise_child_exception
assert_response :created
end
end
class ControllerInheritanceRescueController < ExceptionInheritanceRescueController
class FirstExceptionInChildController < StandardError
end
class SecondExceptionInChildController < StandardError
end
rescue_from FirstExceptionInChildController, 'SecondExceptionInChildController', :with => lambda { head :gone }
def raise_first_exception_in_child_controller
raise FirstExceptionInChildController
end
def raise_second_exception_in_child_controller
raise SecondExceptionInChildController
end
end
class ControllerInheritanceRescueControllerTest < ActionController::TestCase
def test_first_exception_in_child_controller
get :raise_first_exception_in_child_controller
assert_response :gone
end
def test_second_exception_in_child_controller
get :raise_second_exception_in_child_controller
assert_response :gone
end
def test_exception_in_parent_controller
get :raise_parent_exception
assert_response :created
end
end

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,628 +0,0 @@
#--
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
# Under MIT and/or CC By license.
#++
require 'abstract_unit'
require 'controller/fake_controllers'
class SelectorTest < Test::Unit::TestCase
#
# Basic selector: element, id, class, attributes.
#
def test_element
parse(%Q{<div id="1"></div><p></p><div id="2"></div>})
# Match element by name.
select("div")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Not case sensitive.
select("DIV")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Universal match (all elements).
select("*")
assert_equal 3, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal nil, @matches[1].attributes["id"]
assert_equal "2", @matches[2].attributes["id"]
end
def test_identifier
parse(%Q{<div id="1"></div><p></p><div id="2"></div>})
# Match element by ID.
select("div#1")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match element by ID, substitute value.
select("div#?", 2)
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Element name does not match ID.
select("p#?", 2)
assert_equal 0, @matches.size
# Use regular expression.
select("#?", /\d/)
assert_equal 2, @matches.size
end
def test_class_name
parse(%Q{<div id="1" class=" foo "></div><p id="2" class=" foo bar "></p><div id="3" class="bar"></div>})
# Match element with specified class.
select("div.foo")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match any element with specified class.
select("*.foo")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Match elements with other class.
select("*.bar")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Match only element with both class names.
select("*.bar.foo")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
end
def test_attribute
parse(%Q{<div id="1"></div><p id="2" title="" bar="foo"></p><div id="3" title="foo"></div>})
# Match element with attribute.
select("div[title]")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Match any element with attribute.
select("*[title]")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Match element with attribute value.
select("*[title=foo]")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Match element with attribute and attribute value.
select("[bar=foo][title]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Not case sensitive.
select("[BAR=foo][TiTle]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
end
def test_attribute_quoted
parse(%Q{<div id="1" title="foo"></div><div id="2" title="bar"></div><div id="3" title=" bar "></div>})
# Match without quotes.
select("[title = bar]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match with single quotes.
select("[title = 'bar' ]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match with double quotes.
select("[title = \"bar\" ]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match with spaces.
select("[title = \" bar \" ]")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
end
def test_attribute_equality
parse(%Q{<div id="1" title="foo bar"></div><div id="2" title="barbaz"></div>})
# Match (fail) complete value.
select("[title=bar]")
assert_equal 0, @matches.size
# Match space-separate word.
select("[title~=foo]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("[title~=bar]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match beginning of value.
select("[title^=ba]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match end of value.
select("[title$=ar]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match text in value.
select("[title*=bar]")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Match first space separated word.
select("[title|=foo]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("[title|=bar]")
assert_equal 0, @matches.size
end
#
# Selector composition: groups, sibling, children
#
def test_selector_group
parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>})
# Simple group selector.
select("h1,h3")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("h1 , h3")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Complex group selector.
parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>})
select("h1 a, h3 a")
assert_equal 2, @matches.size
assert_equal "foo", @matches[0].attributes["href"]
assert_equal "baz", @matches[1].attributes["href"]
# And now for the three selector challenge.
parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>})
select("h1 a, h2 a, h3 a")
assert_equal 3, @matches.size
assert_equal "foo", @matches[0].attributes["href"]
assert_equal "bar", @matches[1].attributes["href"]
assert_equal "baz", @matches[2].attributes["href"]
end
def test_sibling_selector
parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>})
# Test next sibling.
select("h1+*")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select("h1+h2")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select("h1+h3")
assert_equal 0, @matches.size
select("*+h3")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Test any sibling.
select("h1~*")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("h2~*")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
end
def test_children_selector
parse(%Q{<div><p id="1"><span id="2"></span></p></div><div><p id="3"><span id="4" class="foo"></span></p></div>})
# Test child selector.
select("div>p")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("div>span")
assert_equal 0, @matches.size
select("div>p#3")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
select("div>p>span")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
# Test descendant selector.
select("div p")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("div span")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
select("div *#3")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
select("div *#4")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
# This is here because it failed before when whitespaces
# were not properly stripped.
select("div .foo")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
end
#
# Pseudo selectors: root, nth-child, empty, content, etc
#
def test_root_selector
parse(%Q{<div id="1"><div id="2"></div></div>})
# Can only find element if it's root.
select(":root")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("#1:root")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("#2:root")
assert_equal 0, @matches.size
# Opposite for nth-child.
select("#1:nth-child(1)")
assert_equal 0, @matches.size
end
def test_nth_child_odd_even
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Test odd nth children.
select("tr:nth-child(odd)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Test even nth children.
select("tr:nth-child(even)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
end
def test_nth_child_a_is_zero
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Test the third child.
select("tr:nth-child(0n+3)")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Same but an can be omitted when zero.
select("tr:nth-child(3)")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Second element (but not every second element).
select("tr:nth-child(0n+2)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Before first and past last returns nothing.:
assert_raise(ArgumentError) { select("tr:nth-child(-1)") }
select("tr:nth-child(0)")
assert_equal 0, @matches.size
select("tr:nth-child(5)")
assert_equal 0, @matches.size
end
def test_nth_child_a_is_one
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# a is group of one, pick every element in group.
select("tr:nth-child(1n+0)")
assert_equal 4, @matches.size
# Same but a can be omitted when one.
select("tr:nth-child(n+0)")
assert_equal 4, @matches.size
# Same but b can be omitted when zero.
select("tr:nth-child(n)")
assert_equal 4, @matches.size
end
def test_nth_child_b_is_zero
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# If b is zero, pick the n-th element (here each one).
select("tr:nth-child(n+0)")
assert_equal 4, @matches.size
# If b is zero, pick the n-th element (here every second).
select("tr:nth-child(2n+0)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# If a and b are both zero, no element selected.
select("tr:nth-child(0n+0)")
assert_equal 0, @matches.size
select("tr:nth-child(0)")
assert_equal 0, @matches.size
end
def test_nth_child_a_is_negative
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Since a is -1, picks the first three elements.
select("tr:nth-child(-n+3)")
assert_equal 3, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
assert_equal "3", @matches[2].attributes["id"]
# Since a is -2, picks the first in every second of first four elements.
select("tr:nth-child(-2n+3)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Since a is -2, picks the first in every second of first three elements.
select("tr:nth-child(-2n+2)")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
end
def test_nth_child_b_is_negative
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Select last of four.
select("tr:nth-child(4n-1)")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
# Select first of four.
select("tr:nth-child(4n-4)")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Select last of every second.
select("tr:nth-child(2n-1)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
# Select nothing since an+b always < 0
select("tr:nth-child(-1n-1)")
assert_equal 0, @matches.size
end
def test_nth_child_substitution_values
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Test with ?n?.
select("tr:nth-child(?n?)", 2, 1)
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("tr:nth-child(?n?)", 2, 2)
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
select("tr:nth-child(?n?)", 4, 2)
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Test with ? (b only).
select("tr:nth-child(?)", 3)
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
select("tr:nth-child(?)", 5)
assert_equal 0, @matches.size
end
def test_nth_last_child
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Last two elements.
select("tr:nth-last-child(-n+2)")
assert_equal 2, @matches.size
assert_equal "3", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
# All old elements counting from last one.
select("tr:nth-last-child(odd)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
end
def test_nth_of_type
parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# First two elements.
select("tr:nth-of-type(-n+2)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# All old elements counting from last one.
select("tr:nth-last-of-type(odd)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
end
def test_first_and_last
parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# First child.
select("tr:first-child")
assert_equal 0, @matches.size
select(":first-child")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
# First of type.
select("tr:first-of-type")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("thead:first-of-type")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
select("div:first-of-type")
assert_equal 0, @matches.size
# Last child.
select("tr:last-child")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
# Last of type.
select("tr:last-of-type")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
select("thead:last-of-type")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
select("div:last-of-type")
assert_equal 0, @matches.size
end
def test_first_and_last
# Only child.
parse(%Q{<table><tr></tr></table>})
select("table:only-child")
assert_equal 0, @matches.size
select("tr:only-child")
assert_equal 1, @matches.size
assert_equal "tr", @matches[0].name
parse(%Q{<table><tr></tr><tr></tr></table>})
select("tr:only-child")
assert_equal 0, @matches.size
# Only of type.
parse(%Q{<table><thead></thead><tr></tr><tr></tr></table>})
select("thead:only-of-type")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
select("td:only-of-type")
assert_equal 0, @matches.size
end
def test_empty
parse(%Q{<table><tr></tr></table>})
select("table:empty")
assert_equal 0, @matches.size
select("tr:empty")
assert_equal 1, @matches.size
parse(%Q{<div> </div>})
select("div:empty")
assert_equal 1, @matches.size
end
def test_content
parse(%Q{<div> </div>})
select("div:content()")
assert_equal 1, @matches.size
parse(%Q{<div>something </div>})
select("div:content()")
assert_equal 0, @matches.size
select("div:content(something)")
assert_equal 1, @matches.size
select("div:content( 'something' )")
assert_equal 1, @matches.size
select("div:content( \"something\" )")
assert_equal 1, @matches.size
select("div:content(?)", "something")
assert_equal 1, @matches.size
select("div:content(?)", /something/)
assert_equal 1, @matches.size
end
#
# Test negation.
#
def test_element_negation
parse(%Q{<p></p><div></div>})
select("*")
assert_equal 2, @matches.size
select("*:not(p)")
assert_equal 1, @matches.size
assert_equal "div", @matches[0].name
select("*:not(div)")
assert_equal 1, @matches.size
assert_equal "p", @matches[0].name
select("*:not(span)")
assert_equal 2, @matches.size
end
def test_id_negation
parse(%Q{<p id="1"></p><p id="2"></p>})
select("p")
assert_equal 2, @matches.size
select(":not(#1)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select(":not(#2)")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
end
def test_class_name_negation
parse(%Q{<p class="foo"></p><p class="bar"></p>})
select("p")
assert_equal 2, @matches.size
select(":not(.foo)")
assert_equal 1, @matches.size
assert_equal "bar", @matches[0].attributes["class"]
select(":not(.bar)")
assert_equal 1, @matches.size
assert_equal "foo", @matches[0].attributes["class"]
end
def test_attribute_negation
parse(%Q{<p title="foo"></p><p title="bar"></p>})
select("p")
assert_equal 2, @matches.size
select(":not([title=foo])")
assert_equal 1, @matches.size
assert_equal "bar", @matches[0].attributes["title"]
select(":not([title=bar])")
assert_equal 1, @matches.size
assert_equal "foo", @matches[0].attributes["title"]
end
def test_pseudo_class_negation
parse(%Q{<div><p id="1"></p><p id="2"></p></div>})
select("p")
assert_equal 2, @matches.size
select("p:not(:first-child)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select("p:not(:nth-child(2))")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
end
def test_negation_details
parse(%Q{<p id="1"></p><p id="2"></p><p id="3"></p>})
assert_raise(ArgumentError) { select(":not(") }
assert_raise(ArgumentError) { select(":not(:not())") }
select("p:not(#1):not(#3)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
end
def test_select_from_element
parse(%Q{<div><p id="1"></p><p id="2"></p></div>})
select("div")
@matches = @matches[0].select("p")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
end
protected
def parse(html)
@html = HTML::Document.new(html).root
end
def select(*selector)
@matches = HTML.selector(*selector).select(@html)
end
end

View file

@ -1,171 +0,0 @@
# encoding: utf-8
require 'abstract_unit'
module TestFileUtils
def file_name() File.basename(__FILE__) end
def file_path() File.expand_path(__FILE__) end
def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end
end
class SendFileController < ActionController::Base
include TestFileUtils
layout "layouts/standard" # to make sure layouts don't interfere
attr_writer :options
def options() @options ||= {} end
def file() send_file(file_path, options) end
def data() send_data(file_data, options) end
def multibyte_text_data() send_data("Кирилица\n祝您好運", options) end
def rescue_action(e) raise end
end
class SendFileTest < ActionController::TestCase
tests SendFileController
include TestFileUtils
Mime::Type.register "image/png", :png unless defined? Mime::PNG
def setup
@controller = SendFileController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_file_nostream
@controller.options = { :stream => false }
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
assert_kind_of String, response.body
assert_equal file_data, response.body
end
def test_file_stream
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
assert_kind_of Proc, response.body
require 'stringio'
output = StringIO.new
output.binmode
output.string.force_encoding(file_data.encoding) if output.string.respond_to?(:force_encoding)
assert_nothing_raised { response.body.call(response, output) }
assert_equal file_data, output.string
end
def test_file_url_based_filename
@controller.options = { :url_based_filename => true }
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
assert_equal "attachment", response.headers["Content-Disposition"]
end
def test_x_sendfile_header
@controller.options = { :x_sendfile => true }
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
assert_equal @controller.file_path, response.headers['X-Sendfile']
assert response.body.blank?
assert !response.etag?, response.headers.inspect
end
def test_data
response = nil
assert_nothing_raised { response = process('data') }
assert_not_nil response
assert_kind_of String, response.body
assert_equal file_data, response.body
end
def test_headers_after_send_shouldnt_include_charset
response = process('data')
assert_equal "application/octet-stream", response.content_type
response = process('file')
assert_equal "application/octet-stream", response.content_type
end
# Test that send_file_headers! is setting the correct HTTP headers.
def test_send_file_headers!
options = {
:length => 1,
:type => Mime::PNG,
:disposition => 'disposition',
:filename => 'filename'
}
# Do it a few times: the resulting headers should be identical
# no matter how many times you send with the same options.
# Test resolving Ticket #458.
@controller.headers = {}
@controller.send(:send_file_headers!, options)
@controller.send(:send_file_headers!, options)
@controller.send(:send_file_headers!, options)
h = @controller.headers
assert_equal '1', h['Content-Length']
assert_equal 'image/png', h['Content-Type']
assert_equal 'disposition; filename="filename"', h['Content-Disposition']
assert_equal 'binary', h['Content-Transfer-Encoding']
# test overriding Cache-Control: no-cache header to fix IE open/save dialog
@controller.headers = { 'Cache-Control' => 'no-cache' }
@controller.send(:send_file_headers!, options)
h = @controller.headers
assert_equal 'private', h['Cache-Control']
end
def test_send_file_headers_with_mime_lookup_with_symbol
options = {
:length => 1,
:type => :png
}
@controller.headers = {}
@controller.send(:send_file_headers!, options)
headers = @controller.headers
assert_equal 'image/png', headers['Content-Type']
end
def test_send_file_headers_with_bad_symbol
options = {
:length => 1,
:type => :this_type_is_not_registered
}
@controller.headers = {}
assert_raise(ArgumentError){ @controller.send(:send_file_headers!, options) }
end
%w(file data).each do |method|
define_method "test_send_#{method}_status" do
@controller.options = { :stream => false, :status => 500 }
assert_nothing_raised { assert_not_nil process(method) }
assert_equal '500 Internal Server Error', @response.status
end
define_method "test_default_send_#{method}_status" do
@controller.options = { :stream => false }
assert_nothing_raised { assert_not_nil process(method) }
assert_equal ActionController::Base::DEFAULT_RENDER_STATUS_CODE, @response.status
end
end
def test_send_data_content_length_header
@controller.headers = {}
@controller.options = { :type => :text, :filename => 'file_with_utf8_text' }
process('multibyte_text_data')
assert_equal '29', @controller.headers['Content-Length']
end
end

View file

@ -1,294 +0,0 @@
require 'abstract_unit'
require 'stringio'
class CookieStoreTest < ActionController::IntegrationTest
SessionKey = '_myapp_session'
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
DispatcherApp = ActionController::Dispatcher.new
CookieStoreApp = ActionController::Session::CookieStore.new(DispatcherApp, :key => SessionKey, :secret => SessionSecret)
Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1')
SignedBar = "BAh7BjoIZm9vIghiYXI%3D--fef868465920f415f2c0652d6910d3af288a0367"
class TestController < ActionController::Base
def no_session_access
head :ok
end
def persistent_session_id
render :text => session[:session_id]
end
def set_session_value
session[:foo] = "bar"
render :text => Rack::Utils.escape(Verifier.generate(session.to_hash))
end
def get_session_value
render :text => "foo: #{session[:foo].inspect}"
end
def get_session_id
render :text => "foo: #{session[:foo].inspect}; id: #{request.session_options[:id]}"
end
def get_session_id_only
render :text => "id: #{request.session_options[:id]}"
end
def call_session_clear
session.clear
head :ok
end
def call_reset_session
reset_session
head :ok
end
def raise_data_overflow
session[:foo] = 'bye!' * 1024
head :ok
end
def set_session_value_and_cookie
cookies["foo"] = "bar"
session[:foo] = "bar"
render :text => Rack::Utils.escape(Verifier.generate(session.to_hash))
end
def rescue_action(e) raise end
end
def setup
@integration_session = open_session(CookieStoreApp)
end
def test_raises_argument_error_if_missing_session_key
assert_raise(ArgumentError, nil.inspect) {
ActionController::Session::CookieStore.new(nil,
:key => nil, :secret => SessionSecret)
}
assert_raise(ArgumentError, ''.inspect) {
ActionController::Session::CookieStore.new(nil,
:key => '', :secret => SessionSecret)
}
end
def test_raises_argument_error_if_missing_secret
assert_raise(ArgumentError, nil.inspect) {
ActionController::Session::CookieStore.new(nil,
:key => SessionKey, :secret => nil)
}
assert_raise(ArgumentError, ''.inspect) {
ActionController::Session::CookieStore.new(nil,
:key => SessionKey, :secret => '')
}
end
def test_raises_argument_error_if_secret_is_probably_insecure
assert_raise(ArgumentError, "password".inspect) {
ActionController::Session::CookieStore.new(nil,
:key => SessionKey, :secret => "password")
}
assert_raise(ArgumentError, "secret".inspect) {
ActionController::Session::CookieStore.new(nil,
:key => SessionKey, :secret => "secret")
}
assert_raise(ArgumentError, "12345678901234567890123456789".inspect) {
ActionController::Session::CookieStore.new(nil,
:key => SessionKey, :secret => "12345678901234567890123456789")
}
end
def test_setting_session_value
with_test_route_set do
get '/set_session_value'
assert_response :success
assert_equal ["_myapp_session=#{response.body}; path=/; HttpOnly"],
headers['Set-Cookie']
end
end
def test_getting_session_value
with_test_route_set do
cookies[SessionKey] = SignedBar
get '/get_session_value'
assert_response :success
assert_equal 'foo: "bar"', response.body
end
end
def test_getting_session_id
with_test_route_set do
cookies[SessionKey] = SignedBar
get '/persistent_session_id'
assert_response :success
assert_equal response.body.size, 32
session_id = response.body
get '/get_session_id'
assert_response :success
assert_equal "foo: \"bar\"; id: #{session_id}", response.body
get '/get_session_id_only'
assert_response :success
assert_equal "id: #{session_id}", response.body, "should be able to read session id without accessing the session hash"
end
end
def test_disregards_tampered_sessions
with_test_route_set do
cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--123456780"
get '/get_session_value'
assert_response :success
assert_equal 'foo: nil', response.body
end
end
def test_close_raises_when_data_overflows
with_test_route_set do
assert_raise(ActionController::Session::CookieStore::CookieOverflow) {
get '/raise_data_overflow'
}
end
end
def test_doesnt_write_session_cookie_if_session_is_not_accessed
with_test_route_set do
get '/no_session_access'
assert_response :success
assert_equal nil, headers['Set-Cookie']
end
end
def test_doesnt_write_session_cookie_if_session_is_unchanged
with_test_route_set do
cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--" +
"fef868465920f415f2c0652d6910d3af288a0367"
get '/no_session_access'
assert_response :success
assert_equal nil, headers['Set-Cookie']
end
end
def test_setting_session_value_after_session_reset
with_test_route_set do
get '/set_session_value'
assert_response :success
session_payload = response.body
assert_equal ["_myapp_session=#{response.body}; path=/; HttpOnly"],
headers['Set-Cookie']
get '/call_reset_session'
assert_response :success
assert_not_equal [], headers['Set-Cookie']
assert_not_equal session_payload, cookies[SessionKey]
get '/get_session_value'
assert_response :success
assert_equal 'foo: nil', response.body
end
end
def test_setting_session_value_after_session_clear
with_test_route_set do
get '/set_session_value'
assert_response :success
session_payload = response.body
assert_equal ["_myapp_session=#{response.body}; path=/; HttpOnly"],
headers['Set-Cookie']
get '/call_session_clear'
assert_response :success
get '/get_session_value'
assert_response :success
assert_equal 'foo: nil', response.body
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 headers['Set-Cookie'], "should only create session on write, not read"
end
end
# {:foo=>#<SessionAutoloadTest::Foo bar:"baz">, :session_id=>"ce8b0752a6ab7c7af3cdb8a80e6b9e46"}
SignedSerializedCookie = "BAh7BzoIZm9vbzodU2Vzc2lvbkF1dG9sb2FkVGVzdDo6Rm9vBjoJQGJhciIIYmF6Og9zZXNzaW9uX2lkIiVjZThiMDc1MmE2YWI3YzdhZjNjZGI4YTgwZTZiOWU0Ng==--2bf3af1ae8bd4e52b9ac2099258ace0c380e601c"
def test_deserializes_unloaded_classes_on_get_id
with_test_route_set do
with_autoload_path "session_autoload_test" do
cookies[SessionKey] = SignedSerializedCookie
get '/get_session_id_only'
assert_response :success
assert_equal 'id: ce8b0752a6ab7c7af3cdb8a80e6b9e46', response.body, "should auto-load unloaded class"
end
end
end
def test_deserializes_unloaded_classes_on_get_value
with_test_route_set do
with_autoload_path "session_autoload_test" do
cookies[SessionKey] = SignedSerializedCookie
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_persistent_session_id
with_test_route_set do
cookies[SessionKey] = SignedBar
get '/persistent_session_id'
assert_response :success
assert_equal response.body.size, 32
session_id = response.body
get '/persistent_session_id'
assert_equal session_id, response.body
reset!
get '/persistent_session_id'
assert_not_equal session_id, response.body
end
end
def test_setting_session_value_and_cookie
with_test_route_set do
get '/set_session_value_and_cookie'
assert_response :success
assert_equal({"_myapp_session" => response.body, "foo" => "bar"}, cookies)
end
end
private
def with_test_route_set
with_routing do |set|
set.draw do |map|
map.with_options :controller => "cookie_store_test/test" do |c|
c.connect "/:action"
end
end
yield
end
end
def unmarshal_session(cookie_string)
session = Rack::Utils.parse_query(cookie_string, ';,').inject({}) {|h,(k,v)|
h[k] = Array === v ? v.first : v
h
}[SessionKey]
verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1')
verifier.verify(session)
end
end

View file

@ -1,190 +0,0 @@
require 'abstract_unit'
# You need to start a memcached server inorder to run these tests
class MemCacheStoreTest < ActionController::IntegrationTest
class TestController < ActionController::Base
def no_session_access
head :ok
end
def set_session_value
session[:foo] = "bar"
head :ok
end
def 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
begin
DispatcherApp = ActionController::Dispatcher.new
MemCacheStoreApp = ActionController::Session::MemCacheStore.new(
DispatcherApp, :key => '_session_id')
def setup
@integration_session = open_session(MemCacheStoreApp)
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_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_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']
cookies["_session_id"] = session_id # 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 memcached"
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_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_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_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_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_equal nil, cookies['_session_id']
end
end
rescue LoadError, RuntimeError
$stderr.puts "Skipping MemCacheStoreTest tests. Start memcached and try again."
end
private
def with_test_route_set
with_routing do |set|
set.draw do |map|
map.with_options :controller => "mem_cache_store_test/test" do |c|
c.connect "/:action"
end
end
yield
end
end
end

View file

@ -1,58 +0,0 @@
require 'abstract_unit'
require 'stringio'
class ActionController::TestSessionTest < ActiveSupport::TestCase
def test_calling_delete_without_parameters_raises_deprecation_warning_and_calls_to_clear_test_session
assert_deprecated(/use clear instead/){ ActionController::TestSession.new.delete }
end
def test_calling_update_without_parameters_raises_deprecation_warning_and_calls_to_clear_test_session
assert_deprecated(/use replace instead/){ ActionController::TestSession.new.update }
end
def test_calling_close_raises_deprecation_warning
assert_deprecated(/sessions should no longer be closed/){ ActionController::TestSession.new.close }
end
def test_defaults
session = ActionController::TestSession.new
assert_equal({}, session.data)
assert_equal('', session.session_id)
end
def test_ctor_allows_setting
session = ActionController::TestSession.new({:one => 'one', :two => 'two'})
assert_equal('one', session[:one])
assert_equal('two', session[:two])
end
def test_setting_session_item_sets_item
session = ActionController::TestSession.new
session[:key] = 'value'
assert_equal('value', session[:key])
end
def test_calling_delete_removes_item_and_returns_its_value
session = ActionController::TestSession.new
session[:key] = 'value'
assert_equal('value', session[:key])
assert_equal('value', session.delete(:key))
assert_nil(session[:key])
end
def test_calling_update_with_params_passes_to_attributes
session = ActionController::TestSession.new()
session.update('key' => 'value')
assert_equal('value', session[:key])
end
def test_clear_emptys_session
params = {:one => 'one', :two => 'two'}
session = ActionController::TestSession.new({:one => 'one', :two => 'two'})
session.clear
assert_nil(session[:one])
assert_nil(session[:two])
end
end

View file

@ -1,700 +0,0 @@
require 'abstract_unit'
require 'controller/fake_controllers'
class TestTest < ActionController::TestCase
class TestController < ActionController::Base
def no_op
render :text => 'dummy'
end
def set_flash
flash["test"] = ">#{flash["test"]}<"
render :text => 'ignore me'
end
def set_flash_now
flash.now["test_now"] = ">#{flash["test_now"]}<"
render :text => 'ignore me'
end
def set_session
session['string'] = 'A wonder'
session[:symbol] = 'it works'
render :text => 'Success'
end
def reset_the_session
reset_session
render :text => 'ignore me'
end
def render_raw_post
raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
render :text => request.raw_post
end
def render_body
render :text => request.body.read
end
def test_params
render :text => params.inspect
end
def test_uri
render :text => request.request_uri
end
def test_query_string
render :text => request.query_string
end
def test_html_output
render :text => <<HTML
<html>
<body>
<a href="/"><img src="/images/button.png" /></a>
<div id="foo">
<ul>
<li class="item">hello</li>
<li class="item">goodbye</li>
</ul>
</div>
<div id="bar">
<form action="/somewhere">
Name: <input type="text" name="person[name]" id="person_name" />
</form>
</div>
</body>
</html>
HTML
end
def test_xml_output
response.content_type = "application/xml"
render :text => <<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<area>area is an empty tag in HTML, raising an error if not in xml mode</area>
</root>
XML
end
def test_only_one_param
render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
end
def test_remote_addr
render :text => (request.remote_addr || "not specified")
end
def test_file_upload
render :text => params[:file].size
end
def test_send_file
send_file(File.expand_path(__FILE__))
end
def redirect_to_same_controller
redirect_to :controller => 'test', :action => 'test_uri', :id => 5
end
def redirect_to_different_controller
redirect_to :controller => 'fail', :id => 5
end
def create
head :created, :location => 'created resource'
end
private
def rescue_action(e)
raise e
end
def generate_url(opts)
url_for(opts.merge(:action => "test_uri"))
end
end
def setup
@controller = TestController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionController::Routing.use_controllers! %w(content admin/user test_test/test)
ActionController::Routing::Routes.load_routes!
end
def teardown
ActionController::Routing::Routes.reload
end
def test_raw_post_handling
params = {:page => {:name => 'page name'}, 'some key' => 123}
post :render_raw_post, params.dup
assert_equal params.to_query, @response.body
end
def test_body_stream
params = { :page => { :name => 'page name' }, 'some key' => 123 }
post :render_body, params.dup
assert_equal params.to_query, @response.body
end
def test_process_without_flash
process :set_flash
assert_equal '><', flash['test']
end
def test_process_with_flash
process :set_flash, nil, nil, { "test" => "value" }
assert_equal '>value<', flash['test']
end
def test_process_with_flash_now
process :set_flash_now, nil, nil, { "test_now" => "value_now" }
assert_equal '>value_now<', flash['test_now']
end
def test_process_with_session
process :set_session
assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access"
assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access"
assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
end
def test_process_with_session_arg
process :no_op, nil, { 'string' => 'value1', :symbol => 'value2' }
assert_equal 'value1', session['string']
assert_equal 'value1', session[:string]
assert_equal 'value2', session['symbol']
assert_equal 'value2', session[:symbol]
end
def test_session_is_cleared_from_controller_after_reset_session
process :set_session
process :reset_the_session
assert_equal Hash.new, @controller.session.to_hash
end
def test_session_is_cleared_from_response_after_reset_session
process :set_session
process :reset_the_session
assert_equal Hash.new, @response.session.to_hash
end
def test_session_is_cleared_from_request_after_reset_session
process :set_session
process :reset_the_session
assert_equal Hash.new, @request.session.to_hash
end
def test_process_with_request_uri_with_no_params
process :test_uri
assert_equal "/test_test/test/test_uri", @response.body
end
def test_process_with_request_uri_with_params
process :test_uri, :id => 7
assert_equal "/test_test/test/test_uri/7", @response.body
end
def test_process_with_request_uri_with_params_with_explicit_uri
@request.set_REQUEST_URI "/explicit/uri"
process :test_uri, :id => 7
assert_equal "/explicit/uri", @response.body
end
def test_process_with_query_string
process :test_query_string, :q => 'test'
assert_equal "q=test", @response.body
end
def test_process_with_query_string_with_explicit_uri
@request.set_REQUEST_URI "/explicit/uri?q=test?extra=question"
process :test_query_string
assert_equal "q=test?extra=question", @response.body
end
def test_multiple_calls
process :test_only_one_param, :left => true
assert_equal "OK", @response.body
process :test_only_one_param, :right => true
assert_equal "OK", @response.body
end
def test_assert_tag_tag
process :test_html_output
# there is a 'form' tag
assert_tag :tag => 'form'
# there is not an 'hr' tag
assert_no_tag :tag => 'hr'
end
def test_assert_tag_attributes
process :test_html_output
# there is a tag with an 'id' of 'bar'
assert_tag :attributes => { :id => "bar" }
# there is no tag with a 'name' of 'baz'
assert_no_tag :attributes => { :name => "baz" }
end
def test_assert_tag_parent
process :test_html_output
# there is a tag with a parent 'form' tag
assert_tag :parent => { :tag => "form" }
# there is no tag with a parent of 'input'
assert_no_tag :parent => { :tag => "input" }
end
def test_assert_tag_child
process :test_html_output
# there is a tag with a child 'input' tag
assert_tag :child => { :tag => "input" }
# there is no tag with a child 'strong' tag
assert_no_tag :child => { :tag => "strong" }
end
def test_assert_tag_ancestor
process :test_html_output
# there is a 'li' tag with an ancestor having an id of 'foo'
assert_tag :ancestor => { :attributes => { :id => "foo" } }, :tag => "li"
# there is no tag of any kind with an ancestor having an href matching 'foo'
assert_no_tag :ancestor => { :attributes => { :href => /foo/ } }
end
def test_assert_tag_descendant
process :test_html_output
# there is a tag with a descendant 'li' tag
assert_tag :descendant => { :tag => "li" }
# there is no tag with a descendant 'html' tag
assert_no_tag :descendant => { :tag => "html" }
end
def test_assert_tag_sibling
process :test_html_output
# there is a tag with a sibling of class 'item'
assert_tag :sibling => { :attributes => { :class => "item" } }
# there is no tag with a sibling 'ul' tag
assert_no_tag :sibling => { :tag => "ul" }
end
def test_assert_tag_after
process :test_html_output
# there is a tag following a sibling 'div' tag
assert_tag :after => { :tag => "div" }
# there is no tag following a sibling tag with id 'bar'
assert_no_tag :after => { :attributes => { :id => "bar" } }
end
def test_assert_tag_before
process :test_html_output
# there is a tag preceding a tag with id 'bar'
assert_tag :before => { :attributes => { :id => "bar" } }
# there is no tag preceding a 'form' tag
assert_no_tag :before => { :tag => "form" }
end
def test_assert_tag_children_count
process :test_html_output
# there is a tag with 2 children
assert_tag :children => { :count => 2 }
# in particular, there is a <ul> tag with two children (a nameless pair of <li>s)
assert_tag :tag => 'ul', :children => { :count => 2 }
# there is no tag with 4 children
assert_no_tag :children => { :count => 4 }
end
def test_assert_tag_children_less_than
process :test_html_output
# there is a tag with less than 5 children
assert_tag :children => { :less_than => 5 }
# there is no 'ul' tag with less than 2 children
assert_no_tag :children => { :less_than => 2 }, :tag => "ul"
end
def test_assert_tag_children_greater_than
process :test_html_output
# there is a 'body' tag with more than 1 children
assert_tag :children => { :greater_than => 1 }, :tag => "body"
# there is no tag with more than 10 children
assert_no_tag :children => { :greater_than => 10 }
end
def test_assert_tag_children_only
process :test_html_output
# there is a tag containing only one child with an id of 'foo'
assert_tag :children => { :count => 1,
:only => { :attributes => { :id => "foo" } } }
# there is no tag containing only one 'li' child
assert_no_tag :children => { :count => 1, :only => { :tag => "li" } }
end
def test_assert_tag_content
process :test_html_output
# the output contains the string "Name"
assert_tag :content => /Name/
# the output does not contain the string "test"
assert_no_tag :content => /test/
end
def test_assert_tag_multiple
process :test_html_output
# there is a 'div', id='bar', with an immediate child whose 'action'
# attribute matches the regexp /somewhere/.
assert_tag :tag => "div", :attributes => { :id => "bar" },
:child => { :attributes => { :action => /somewhere/ } }
# there is no 'div', id='foo', with a 'ul' child with more than
# 2 "li" children.
assert_no_tag :tag => "div", :attributes => { :id => "foo" },
:child => {
:tag => "ul",
:children => { :greater_than => 2,
:only => { :tag => "li" } } }
end
def test_assert_tag_children_without_content
process :test_html_output
# there is a form tag with an 'input' child which is a self closing tag
assert_tag :tag => "form",
:children => { :count => 1,
:only => { :tag => "input" } }
# the body tag has an 'a' child which in turn has an 'img' child
assert_tag :tag => "body",
:children => { :count => 1,
:only => { :tag => "a",
:children => { :count => 1,
:only => { :tag => "img" } } } }
end
def test_should_not_impose_childless_html_tags_in_xml
process :test_xml_output
begin
$stderr = StringIO.new
assert_select 'area' #This will cause a warning if content is processed as HTML
$stderr.rewind && err = $stderr.read
ensure
$stderr = STDERR
end
assert err.empty?
end
def test_assert_tag_attribute_matching
@response.body = '<input type="text" name="my_name">'
assert_tag :tag => 'input',
:attributes => { :name => /my/, :type => 'text' }
assert_no_tag :tag => 'input',
:attributes => { :name => 'my', :type => 'text' }
assert_no_tag :tag => 'input',
:attributes => { :name => /^my$/, :type => 'text' }
end
def test_assert_tag_content_matching
@response.body = "<p>hello world</p>"
assert_tag :tag => "p", :content => "hello world"
assert_tag :tag => "p", :content => /hello/
assert_no_tag :tag => "p", :content => "hello"
end
def test_assert_generates
assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action"}
assert_generates 'controller/action/5', {:controller => "controller", :action => "action", :id => "5", :name => "bob"}, {}, {:name => "bob"}
assert_generates 'controller/action/7', {:id => "7", :name => "bob"}, {:controller => "controller", :action => "action"}, {:name => "bob"}
assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action", :name => "bob"}, {}
end
def test_assert_routing
assert_routing 'content', :controller => 'content', :action => 'index'
end
def test_assert_routing_with_method
with_routing do |set|
set.draw { |map| map.resources(:content) }
assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
end
end
def test_assert_routing_in_module
assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
end
def test_params_passing
get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
parsed_params = eval(@response.body)
assert_equal(
{'controller' => 'test_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
parsed_params
)
end
def test_id_converted_to_string
get :test_params, :id => 20, :foo => Object.new
assert_kind_of String, @request.path_parameters['id']
end
def test_array_path_parameter_handled_properly
with_routing do |set|
set.draw do |map|
map.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params'
map.connect ':controller/:action/:id'
end
get :test_params, :path => ['hello', 'world']
assert_equal ['hello', 'world'], @request.path_parameters['path']
assert_equal 'hello/world', @request.path_parameters['path'].to_s
end
end
def test_assert_realistic_path_parameters
get :test_params, :id => 20, :foo => Object.new
# All elements of path_parameters should use string keys
@request.path_parameters.keys.each do |key|
assert_kind_of String, key
end
end
def test_with_routing_places_routes_back
assert ActionController::Routing::Routes
routes_id = ActionController::Routing::Routes.object_id
begin
with_routing { raise 'fail' }
fail 'Should not be here.'
rescue RuntimeError
end
assert ActionController::Routing::Routes
assert_equal routes_id, ActionController::Routing::Routes.object_id
end
def test_remote_addr
get :test_remote_addr
assert_equal "0.0.0.0", @response.body
@request.remote_addr = "192.0.0.1"
get :test_remote_addr
assert_equal "192.0.0.1", @response.body
end
def test_header_properly_reset_after_remote_http_request
xhr :get, :test_params
assert_nil @request.env['HTTP_X_REQUESTED_WITH']
end
def test_header_properly_reset_after_get_request
get :test_params
@request.recycle!
assert_nil @request.instance_variable_get("@request_method")
end
def test_params_reset_after_post_request
post :no_op, :foo => "bar"
assert_equal "bar", @request.params[:foo]
@request.recycle!
post :no_op
assert @request.params[:foo].blank?
end
%w(controller response request).each do |variable|
%w(get post put delete head process).each do |method|
define_method("test_#{variable}_missing_for_#{method}_raises_error") do
remove_instance_variable "@#{variable}"
begin
send(method, :test_remote_addr)
assert false, "expected RuntimeError, got nothing"
rescue RuntimeError => error
assert true
assert_match %r{@#{variable} is nil}, error.message
rescue => error
assert false, "expected RuntimeError, got #{error.class}"
end
end
end
end
FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
if RUBY_VERSION < '1.9'
READ_BINARY = 'rb'
READ_PLAIN = 'r'
else
READ_BINARY = 'rb:binary'
READ_PLAIN = 'r:binary'
end
def test_test_uploaded_file
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
content_type = 'image/png'
expected = File.read(path)
expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding)
file = ActionController::TestUploadedFile.new(path, content_type)
assert_equal filename, file.original_filename
assert_equal content_type, file.content_type
assert_equal file.path, file.local_path
assert_equal expected, file.read
new_content_type = "new content_type"
file.content_type = new_content_type
assert_equal new_content_type, file.content_type
end
def test_test_uploaded_file_with_binary
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
content_type = 'image/png'
binary_uploaded_file = ActionController::TestUploadedFile.new(path, content_type, :binary)
assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read
plain_uploaded_file = ActionController::TestUploadedFile.new(path, content_type)
assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
end
def test_fixture_file_upload_with_binary
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
content_type = 'image/jpg'
binary_file_upload = fixture_file_upload(path, content_type, :binary)
assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
plain_file_upload = fixture_file_upload(path, content_type)
assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
end
def test_fixture_file_upload
post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
assert_equal '159528', @response.body
end
def test_test_uploaded_file_exception_when_file_doesnt_exist
assert_raise(RuntimeError) { ActionController::TestUploadedFile.new('non_existent_file') }
end
def test_redirect_url_only_cares_about_location_header
get :create
assert_response :created
# Redirect url doesn't care that it wasn't a :redirect response.
assert_equal 'created resource', @response.redirect_url
assert_equal @response.redirect_url, redirect_to_url
# Must be a :redirect response.
assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to 'created resource'
end
end
def test_binary_content_works_with_send_file
get :test_send_file
assert_nothing_raised(NoMethodError) { @response.binary_content }
end
protected
def with_foo_routing
with_routing do |set|
set.draw do |map|
map.generate_url 'foo', :controller => 'test'
map.connect ':controller/:action/:id'
end
yield set
end
end
end
class CleanBacktraceTest < ActionController::TestCase
def test_should_reraise_the_same_object
exception = ActiveSupport::TestCase::Assertion.new('message')
clean_backtrace { raise exception }
rescue Exception => caught
assert_equal exception.object_id, caught.object_id
assert_equal exception.message, caught.message
end
def test_should_clean_assertion_lines_from_backtrace
path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller")
exception = ActiveSupport::TestCase::Assertion.new('message')
exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
clean_backtrace { raise exception }
rescue Exception => caught
assert_equal ["#{path}/abc"], caught.backtrace
end
def test_should_only_clean_assertion_failure_errors
clean_backtrace do
raise "can't touch this", [File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/assertions/abc")]
end
rescue => caught
assert !caught.backtrace.empty?
end
end
class InferringClassNameTest < ActionController::TestCase
def test_determine_controller_class
assert_equal ContentController, determine_class("ContentControllerTest")
end
def test_determine_controller_class_with_nonsense_name
assert_nil determine_class("HelloGoodBye")
end
def test_determine_controller_class_with_sensible_name_where_no_controller_exists
assert_nil determine_class("NoControllerWithThisNameTest")
end
private
def determine_class(name)
ActionController::TestCase.determine_default_controller_class(name)
end
end
class CrazyNameTest < ActionController::TestCase
tests ContentController
def test_controller_class_can_be_set_manually_not_just_inferred
assert_equal ContentController, self.class.controller_class
end
end
class NamedRoutesControllerTest < ActionController::TestCase
tests ContentController
def test_should_be_able_to_use_named_routes_before_a_request_is_done
with_routing do |set|
set.draw { |map| map.resources :contents }
assert_equal 'http://test.host/contents/new', new_content_url
assert_equal 'http://test.host/contents/1', content_url(:id => 1)
end
end
end

View file

@ -1,26 +0,0 @@
require 'abstract_unit'
# class TranslatingController < ActionController::Base
# end
class TranslationControllerTest < Test::Unit::TestCase
def setup
@controller = ActionController::Base.new
end
def test_action_controller_base_responds_to_translate
assert @controller.respond_to?(:translate)
end
def test_action_controller_base_responds_to_t
assert @controller.respond_to?(:t)
end
def test_action_controller_base_responds_to_localize
assert @controller.respond_to?(:localize)
end
def test_action_controller_base_responds_to_l
assert @controller.respond_to?(:l)
end
end

View file

@ -1,395 +0,0 @@
require 'abstract_unit'
ActionController::UrlRewriter
class UrlRewriterTests < ActionController::TestCase
def setup
@request = ActionController::TestRequest.new
@params = {}
@rewriter = ActionController::UrlRewriter.new(@request, @params)
end
def test_port
assert_equal('http://test.host:1271/c/a/i',
@rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :port => 1271)
)
end
def test_protocol_with_and_without_separator
assert_equal('https://test.host/c/a/i',
@rewriter.rewrite(:protocol => 'https', :controller => 'c', :action => 'a', :id => 'i')
)
assert_equal('https://test.host/c/a/i',
@rewriter.rewrite(:protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i')
)
end
def test_user_name_and_password
assert_equal(
'http://david:secret@test.host/c/a/i',
@rewriter.rewrite(:user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i')
)
end
def test_user_name_and_password_with_escape_codes
assert_equal(
'http://openid.aol.com%2Fnextangler:one+two%3F@test.host/c/a/i',
@rewriter.rewrite(:user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i')
)
end
def test_anchor
assert_equal(
'http://test.host/c/a/i#anchor',
@rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor')
)
end
def test_anchor_should_call_to_param
assert_equal(
'http://test.host/c/a/i#anchor',
@rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor'))
)
end
def test_anchor_should_be_cgi_escaped
assert_equal(
'http://test.host/c/a/i#anc%2Fhor',
@rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor'))
)
end
def test_overwrite_params
@params[:controller] = 'hi'
@params[:action] = 'bye'
@params[:id] = '2'
assert_deprecated /overwrite_params/ do
assert_equal '/hi/hi/2', @rewriter.rewrite(:only_path => true, :overwrite_params => {:action => 'hi'})
u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:action => 'hi'})
assert_match %r(/hi/hi/2$), u
end
end
def test_overwrite_removes_original
@params[:controller] = 'search'
@params[:action] = 'list'
@params[:list_page] = 1
assert_deprecated /overwrite_params/ do
assert_equal '/search/list?list_page=2', @rewriter.rewrite(:only_path => true, :overwrite_params => {"list_page" => 2})
u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:list_page => 2})
assert_equal 'http://test.host/search/list?list_page=2', u
end
end
def test_to_str
@params[:controller] = 'hi'
@params[:action] = 'bye'
@request.parameters[:id] = '2'
assert_equal 'http://, test.host, /, hi, bye, {"id"=>"2"}', @rewriter.to_str
end
def test_trailing_slash
options = {:controller => 'foo', :action => 'bar', :id => '3', :only_path => true}
assert_equal '/foo/bar/3', @rewriter.rewrite(options)
assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(options.merge({:query => 'string'}))
options.update({:trailing_slash => true})
assert_equal '/foo/bar/3/', @rewriter.rewrite(options)
options.update({:query => 'string'})
assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(options)
end
end
class UrlWriterTests < ActionController::TestCase
class W
include ActionController::UrlWriter
end
def teardown
W.default_url_options.clear
end
def add_host!
W.default_url_options[:host] = 'www.basecamphq.com'
end
def test_exception_is_thrown_without_host
assert_raise RuntimeError do
W.new.url_for :controller => 'c', :action => 'a', :id => 'i'
end
end
def test_anchor
assert_equal('/c/a#anchor',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => 'anchor')
)
end
def test_anchor_should_call_to_param
assert_equal('/c/a#anchor',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor'))
)
end
def test_anchor_should_escape_unsafe_pchar
assert_equal('/c/a#%23anchor',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('#anchor'))
)
end
def test_anchor_should_not_escape_safe_pchar
assert_equal('/c/a#name=user&email=user@domain.com',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('name=user&email=user@domain.com'))
)
end
def test_default_host
add_host!
assert_equal('http://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i')
)
end
def test_host_may_be_overridden
add_host!
assert_equal('http://37signals.basecamphq.com/c/a/i',
W.new.url_for(:host => '37signals.basecamphq.com', :controller => 'c', :action => 'a', :id => 'i')
)
end
def test_port
add_host!
assert_equal('http://www.basecamphq.com:3000/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :port => 3000)
)
end
def test_protocol
add_host!
assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
)
end
def test_protocol_with_and_without_separator
add_host!
assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
)
assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://')
)
end
def test_trailing_slash
add_host!
options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'}
assert_equal('http://www.basecamphq.com/foo/bar/33/', W.new.url_for(options) )
end
def test_trailing_slash_with_protocol
add_host!
options = { :trailing_slash => true,:protocol => 'https', :controller => 'foo', :action => 'bar', :id => '33'}
assert_equal('https://www.basecamphq.com/foo/bar/33/', W.new.url_for(options) )
assert_equal 'https://www.basecamphq.com/foo/bar/33/?query=string', W.new.url_for(options.merge({:query => 'string'}))
end
def test_trailing_slash_with_only_path
options = {:controller => 'foo', :trailing_slash => true}
assert_equal '/foo/', W.new.url_for(options.merge({:only_path => true}))
options.update({:action => 'bar', :id => '33'})
assert_equal '/foo/bar/33/', W.new.url_for(options.merge({:only_path => true}))
assert_equal '/foo/bar/33/?query=string', W.new.url_for(options.merge({:query => 'string',:only_path => true}))
end
def test_trailing_slash_with_anchor
options = {:trailing_slash => true, :controller => 'foo', :action => 'bar', :id => '33', :only_path => true, :anchor=> 'chapter7'}
assert_equal '/foo/bar/33/#chapter7', W.new.url_for(options)
assert_equal '/foo/bar/33/?query=string#chapter7', W.new.url_for(options.merge({:query => 'string'}))
end
def test_trailing_slash_with_params
url = W.new.url_for(:trailing_slash => true, :only_path => true, :controller => 'cont', :action => 'act', :p1 => 'cafe', :p2 => 'link')
params = extract_params(url)
assert_equal params[0], { :p1 => 'cafe' }.to_query
assert_equal params[1], { :p2 => 'link' }.to_query
end
def test_relative_url_root_is_respected
orig_relative_url_root = ActionController::Base.relative_url_root
ActionController::Base.relative_url_root = '/subdir'
add_host!
assert_equal('https://www.basecamphq.com/subdir/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
)
ensure
ActionController::Base.relative_url_root = orig_relative_url_root
end
def test_named_routes
ActionController::Routing::Routes.draw do |map|
map.no_args '/this/is/verbose', :controller => 'home', :action => 'index'
map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index'
map.connect ':controller/:action/:id'
end
# We need to create a new class in order to install the new named route.
kls = Class.new { include ActionController::UrlWriter }
controller = kls.new
assert controller.respond_to?(:home_url)
assert_equal 'http://www.basecamphq.com/home/sweet/home/again',
controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again')
assert_equal("/home/sweet/home/alabama", controller.send(:home_path, :user => 'alabama', :host => 'unused'))
assert_equal("http://www.basecamphq.com/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'www.basecamphq.com'))
assert_equal("http://www.basecamphq.com/this/is/verbose", controller.send(:no_args_url, :host=>'www.basecamphq.com'))
ensure
ActionController::Routing::Routes.load!
end
def test_relative_url_root_is_respected_for_named_routes
orig_relative_url_root = ActionController::Base.relative_url_root
ActionController::Base.relative_url_root = '/subdir'
ActionController::Routing::Routes.draw do |map|
map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index'
end
kls = Class.new { include ActionController::UrlWriter }
controller = kls.new
assert_equal 'http://www.basecamphq.com/subdir/home/sweet/home/again',
controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again')
ensure
ActionController::Routing::Routes.load!
ActionController::Base.relative_url_root = orig_relative_url_root
end
def test_only_path
ActionController::Routing::Routes.draw do |map|
map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index'
map.connect ':controller/:action/:id'
end
# We need to create a new class in order to install the new named route.
kls = Class.new { include ActionController::UrlWriter }
controller = kls.new
assert controller.respond_to?(:home_url)
assert_equal '/brave/new/world',
controller.send(:url_for, :controller => 'brave', :action => 'new', :id => 'world', :only_path => true)
assert_equal("/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'unused', :only_path => true))
assert_equal("/home/sweet/home/alabama", controller.send(:home_path, 'alabama'))
ensure
ActionController::Routing::Routes.load!
end
def test_one_parameter
assert_equal('/c/a?param=val',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :param => 'val')
)
end
def test_two_parameters
url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :p1 => 'X1', :p2 => 'Y2')
params = extract_params(url)
assert_equal params[0], { :p1 => 'X1' }.to_query
assert_equal params[1], { :p2 => 'Y2' }.to_query
end
def test_hash_parameter
url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => {:name => 'Bob', :category => 'prof'})
params = extract_params(url)
assert_equal params[0], { 'query[category]' => 'prof' }.to_query
assert_equal params[1], { 'query[name]' => 'Bob' }.to_query
end
def test_array_parameter
url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => ['Bob', 'prof'])
params = extract_params(url)
assert_equal params[0], { 'query[]' => 'Bob' }.to_query
assert_equal params[1], { 'query[]' => 'prof' }.to_query
end
def test_hash_recursive_parameters
url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => {:person => {:name => 'Bob', :position => 'prof'}, :hobby => 'piercing'})
params = extract_params(url)
assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query
assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query
assert_equal params[2], { 'query[person][position]' => 'prof' }.to_query
end
def test_hash_recursive_and_array_parameters
url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :id => 101, :query => {:person => {:name => 'Bob', :position => ['prof', 'art director']}, :hobby => 'piercing'})
assert_match %r(^/c/a/101), url
params = extract_params(url)
assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query
assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query
assert_equal params[2], { 'query[person][position][]' => 'prof' }.to_query
assert_equal params[3], { 'query[person][position][]' => 'art director' }.to_query
end
def test_path_generation_for_symbol_parameter_keys
assert_generates("/image", :controller=> :image)
end
def test_named_routes_with_nil_keys
ActionController::Routing::Routes.clear!
ActionController::Routing::Routes.draw do |map|
map.main '', :controller => 'posts', :format => nil
map.resources :posts
map.connect ':controller/:action/:id'
end
# We need to create a new class in order to install the new named route.
kls = Class.new { include ActionController::UrlWriter }
kls.default_url_options[:host] = 'www.basecamphq.com'
controller = kls.new
params = {:action => :index, :controller => :posts, :format => :xml}
assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params))
params[:format] = nil
assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params))
ensure
ActionController::Routing::Routes.load!
end
def test_formatted_url_methods_are_deprecated
ActionController::Routing::Routes.draw do |map|
map.resources :posts
end
# We need to create a new class in order to install the new named route.
kls = Class.new { include ActionController::UrlWriter }
controller = kls.new
params = {:id => 1, :format => :xml}
assert_deprecated do
assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params))
end
assert_deprecated do
assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml))
end
ensure
ActionController::Routing::Routes.load!
end
def test_multiple_includes_maintain_distinct_options
first_class = Class.new { include ActionController::UrlWriter }
second_class = Class.new { include ActionController::UrlWriter }
first_host, second_host = 'firsthost.com', 'secondhost.com'
first_class.default_url_options[:host] = first_host
second_class.default_url_options[:host] = second_host
assert_equal first_class.default_url_options[:host], first_host
assert_equal second_class.default_url_options[:host], second_host
end
private
def extract_params(url)
url.split('?', 2).last.split('&')
end
end

View file

@ -1,270 +0,0 @@
require 'abstract_unit'
class VerificationTest < ActionController::TestCase
class TestController < ActionController::Base
verify :only => :guarded_one, :params => "one",
:add_flash => { :error => 'unguarded' },
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_two, :params => %w( one two ),
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_with_flash, :params => "one",
:add_flash => { :notice => "prereqs failed" },
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_in_session, :session => "one",
:redirect_to => { :action => "unguarded" }
verify :only => [:multi_one, :multi_two], :session => %w( one two ),
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_by_method, :method => :post,
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_by_xhr, :xhr => true,
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_by_not_xhr, :xhr => false,
:redirect_to => { :action => "unguarded" }
before_filter :unconditional_redirect, :only => :two_redirects
verify :only => :two_redirects, :method => :post,
:redirect_to => { :action => "unguarded" }
verify :only => :must_be_post, :method => :post, :render => { :status => 405, :text => "Must be post" }, :add_headers => { "Allow" => "POST" }
verify :only => :guarded_one_for_named_route_test, :params => "one",
:redirect_to => :foo_url
verify :only => :no_default_action, :params => "santa"
verify :only => :guarded_with_back, :method => :post,
:redirect_to => :back
def guarded_one
render :text => "#{params[:one]}"
end
def guarded_one_for_named_route_test
render :text => "#{params[:one]}"
end
def guarded_with_flash
render :text => "#{params[:one]}"
end
def guarded_two
render :text => "#{params[:one]}:#{params[:two]}"
end
def guarded_in_session
render :text => "#{session["one"]}"
end
def multi_one
render :text => "#{session["one"]}:#{session["two"]}"
end
def multi_two
render :text => "#{session["two"]}:#{session["one"]}"
end
def guarded_by_method
render :text => "#{request.method}"
end
def guarded_by_xhr
render :text => "#{request.xhr?}"
end
def guarded_by_not_xhr
render :text => "#{request.xhr?}"
end
def unguarded
render :text => "#{params[:one]}"
end
def two_redirects
render :nothing => true
end
def must_be_post
render :text => "Was a post!"
end
def guarded_with_back
render :text => "#{params[:one]}"
end
def no_default_action
# Will never run
end
protected
def rescue_action(e) raise end
def unconditional_redirect
redirect_to :action => "unguarded"
end
end
def setup
@controller = TestController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionController::Routing::Routes.add_named_route :foo, '/foo', :controller => 'test', :action => 'foo'
end
def test_using_symbol_back_with_no_referrer
assert_raise(ActionController::RedirectBackError) { get :guarded_with_back }
end
def test_using_symbol_back_redirects_to_referrer
@request.env["HTTP_REFERER"] = "/foo"
get :guarded_with_back
assert_redirected_to '/foo'
end
def test_no_deprecation_warning_for_named_route
assert_not_deprecated do
get :guarded_one_for_named_route_test, :two => "not one"
assert_redirected_to '/foo'
end
end
def test_guarded_one_with_prereqs
get :guarded_one, :one => "here"
assert_equal "here", @response.body
end
def test_guarded_one_without_prereqs
get :guarded_one
assert_redirected_to :action => "unguarded"
assert_equal 'unguarded', flash[:error]
end
def test_guarded_with_flash_with_prereqs
get :guarded_with_flash, :one => "here"
assert_equal "here", @response.body
assert flash.empty?
end
def test_guarded_with_flash_without_prereqs
get :guarded_with_flash
assert_redirected_to :action => "unguarded"
assert_equal "prereqs failed", flash[:notice]
end
def test_guarded_two_with_prereqs
get :guarded_two, :one => "here", :two => "there"
assert_equal "here:there", @response.body
end
def test_guarded_two_without_prereqs_one
get :guarded_two, :two => "there"
assert_redirected_to :action => "unguarded"
end
def test_guarded_two_without_prereqs_two
get :guarded_two, :one => "here"
assert_redirected_to :action => "unguarded"
end
def test_guarded_two_without_prereqs_both
get :guarded_two
assert_redirected_to :action => "unguarded"
end
def test_unguarded_with_params
get :unguarded, :one => "here"
assert_equal "here", @response.body
end
def test_unguarded_without_params
get :unguarded
assert_equal "", @response.body
end
def test_guarded_in_session_with_prereqs
get :guarded_in_session, {}, "one" => "here"
assert_equal "here", @response.body
end
def test_guarded_in_session_without_prereqs
get :guarded_in_session
assert_redirected_to :action => "unguarded"
end
def test_multi_one_with_prereqs
get :multi_one, {}, "one" => "here", "two" => "there"
assert_equal "here:there", @response.body
end
def test_multi_one_without_prereqs
get :multi_one
assert_redirected_to :action => "unguarded"
end
def test_multi_two_with_prereqs
get :multi_two, {}, "one" => "here", "two" => "there"
assert_equal "there:here", @response.body
end
def test_multi_two_without_prereqs
get :multi_two
assert_redirected_to :action => "unguarded"
end
def test_guarded_by_method_with_prereqs
post :guarded_by_method
assert_equal "post", @response.body
end
def test_guarded_by_method_without_prereqs
get :guarded_by_method
assert_redirected_to :action => "unguarded"
end
def test_guarded_by_xhr_with_prereqs
xhr :post, :guarded_by_xhr
assert_equal "true", @response.body
end
def test_guarded_by_xhr_without_prereqs
get :guarded_by_xhr
assert_redirected_to :action => "unguarded"
end
def test_guarded_by_not_xhr_with_prereqs
get :guarded_by_not_xhr
assert_equal "false", @response.body
end
def test_guarded_by_not_xhr_without_prereqs
xhr :post, :guarded_by_not_xhr
assert_redirected_to :action => "unguarded"
end
def test_guarded_post_and_calls_render_succeeds
post :must_be_post
assert_equal "Was a post!", @response.body
end
def test_default_failure_should_be_a_bad_request
post :no_default_action
assert_response :bad_request
end
def test_guarded_post_and_calls_render_fails_and_sets_allow_header
get :must_be_post
assert_response 405
assert_equal "Must be post", @response.body
assert_equal "POST", @response.headers["Allow"]
end
def test_second_redirect
assert_nothing_raised { get :two_redirects }
end
end

View file

@ -1,141 +0,0 @@
require 'abstract_unit'
class ViewLoadPathsTest < ActionController::TestCase
class TestController < ActionController::Base
def self.controller_path() "test" end
def rescue_action(e) raise end
before_filter :add_view_path, :only => :hello_world_at_request_time
def hello_world() end
def hello_world_at_request_time() render(:action => 'hello_world') end
private
def add_view_path
prepend_view_path "#{FIXTURE_LOAD_PATH}/override"
end
end
class Test::SubController < ActionController::Base
layout 'test/sub'
def hello_world; render(:template => 'test/hello_world'); end
end
def setup
TestController.view_paths = nil
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = TestController.new
# Following is needed in order to setup @controller.template object properly
@controller.send :initialize_template_class, @response
@controller.send :assign_shortcuts, @request, @response
# Track the last warning.
@old_behavior = ActiveSupport::Deprecation.behavior
@last_message = nil
ActiveSupport::Deprecation.behavior = Proc.new { |message, callback| @last_message = message }
end
def teardown
ActiveSupport::Deprecation.behavior = @old_behavior
end
def test_template_load_path_was_set_correctly
assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
end
def test_controller_appends_view_path_correctly
@controller.append_view_path 'foo'
assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
@controller.append_view_path(%w(bar baz))
assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
@controller.append_view_path(FIXTURE_LOAD_PATH)
assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
end
def test_controller_prepends_view_path_correctly
@controller.prepend_view_path 'baz'
assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
@controller.prepend_view_path(%w(foo bar))
assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
@controller.prepend_view_path(FIXTURE_LOAD_PATH)
assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
end
def test_template_appends_view_path_correctly
@controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller)
class_view_paths = TestController.view_paths
@controller.append_view_path 'foo'
assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
@controller.append_view_path(%w(bar baz))
assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
assert_equal class_view_paths, TestController.view_paths
end
def test_template_prepends_view_path_correctly
@controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller)
class_view_paths = TestController.view_paths
@controller.prepend_view_path 'baz'
assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
@controller.prepend_view_path(%w(foo bar))
assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
assert_equal class_view_paths, TestController.view_paths
end
def test_view_paths
get :hello_world
assert_response :success
assert_equal "Hello world!", @response.body
end
def test_view_paths_override
TestController.prepend_view_path "#{FIXTURE_LOAD_PATH}/override"
get :hello_world
assert_response :success
assert_equal "Hello overridden world!", @response.body
end
def test_view_paths_override_for_layouts_in_controllers_with_a_module
@controller = Test::SubController.new
Test::SubController.view_paths = [ "#{FIXTURE_LOAD_PATH}/override", FIXTURE_LOAD_PATH, "#{FIXTURE_LOAD_PATH}/override2" ]
get :hello_world
assert_response :success
assert_equal "layout: Hello overridden world!", @response.body
end
def test_view_paths_override_at_request_time
get :hello_world_at_request_time
assert_response :success
assert_equal "Hello overridden world!", @response.body
end
def test_inheritance
original_load_paths = ActionController::Base.view_paths
self.class.class_eval %{
class A < ActionController::Base; end
class B < A; end
class C < ActionController::Base; end
}
A.view_paths = ['a/path']
assert_equal ['a/path'], A.view_paths.map(&:to_s)
assert_equal A.view_paths, B.view_paths
assert_equal original_load_paths, C.view_paths
C.view_paths = []
assert_nothing_raised { C.view_paths << 'c/path' }
assert_equal ['c/path'], C.view_paths.map(&:to_s)
end
end

View file

@ -1,260 +0,0 @@
require 'abstract_unit'
class WebServiceTest < ActionController::IntegrationTest
class TestController < ActionController::Base
def assign_parameters
if params[:full]
render :text => dump_params_keys
else
render :text => (params.keys - ['controller', 'action']).sort.join(", ")
end
end
def dump_params_keys(hash = params)
hash.keys.sort.inject("") do |s, k|
value = hash[k]
value = Hash === value ? "(#{dump_params_keys(value)})" : ""
s << ", " unless s.empty?
s << "#{k}#{value}"
end
end
def rescue_action(e) raise end
end
def setup
@controller = TestController.new
@default_param_parsers = ActionController::Base.param_parsers.dup
end
def teardown
ActionController::Base.param_parsers = @default_param_parsers
end
def test_check_parameters
with_test_route_set do
get "/"
assert_equal '', @controller.response.body
end
end
def test_post_xml
with_test_route_set do
post "/", '<entry attributed="true"><summary>content...</summary></entry>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'content...', @controller.params["entry"]['summary']
assert_equal 'true', @controller.params["entry"]['attributed']
end
end
def test_put_xml
with_test_route_set do
put "/", '<entry attributed="true"><summary>content...</summary></entry>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'content...', @controller.params["entry"]['summary']
assert_equal 'true', @controller.params["entry"]['attributed']
end
end
def test_put_xml_using_a_type_node
with_test_route_set do
put "/", '<type attributed="true"><summary>content...</summary></type>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'type', @controller.response.body
assert @controller.params.has_key?(:type)
assert_equal 'content...', @controller.params["type"]['summary']
assert_equal 'true', @controller.params["type"]['attributed']
end
end
def test_put_xml_using_a_type_node_and_attribute
with_test_route_set do
put "/", '<type attributed="true"><summary type="boolean">false</summary></type>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'type', @controller.response.body
assert @controller.params.has_key?(:type)
assert_equal false, @controller.params["type"]['summary']
assert_equal 'true', @controller.params["type"]['attributed']
end
end
def test_post_xml_using_a_type_node
with_test_route_set do
post "/", '<font attributed="true"><type>arial</type></font>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'font', @controller.response.body
assert @controller.params.has_key?(:font)
assert_equal 'arial', @controller.params['font']['type']
assert_equal 'true', @controller.params["font"]['attributed']
end
end
def test_post_xml_using_a_root_node_named_type
with_test_route_set do
post "/", '<type type="integer">33</type>',
{'CONTENT_TYPE' => 'application/xml'}
assert @controller.params.has_key?(:type)
assert_equal 33, @controller.params['type']
end
end
def test_post_xml_using_an_attributted_node_named_type
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access }
post "/", '<request><type type="string">Arial,12</type><z>3</z></request>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'type, z', @controller.response.body
assert @controller.params.has_key?(:type)
assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect
assert_equal '3', @controller.params['z'], @controller.params.inspect
end
end
def test_register_and_use_yaml
with_test_route_set do
ActionController::Base.param_parsers[Mime::YAML] = Proc.new { |d| YAML.load(d) }
post "/", {"entry" => "loaded from yaml"}.to_yaml,
{'CONTENT_TYPE' => 'application/x-yaml'}
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'loaded from yaml', @controller.params["entry"]
end
end
def test_register_and_use_yaml_as_symbol
with_test_route_set do
ActionController::Base.param_parsers[Mime::YAML] = :yaml
post "/", {"entry" => "loaded from yaml"}.to_yaml,
{'CONTENT_TYPE' => 'application/x-yaml'}
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'loaded from yaml', @controller.params["entry"]
end
end
def test_register_and_use_xml_simple
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access }
post "/", '<request><summary>content...</summary><title>SimpleXml</title></request>',
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'summary, title', @controller.response.body
assert @controller.params.has_key?(:summary)
assert @controller.params.has_key?(:title)
assert_equal 'content...', @controller.params["summary"]
assert_equal 'SimpleXml', @controller.params["title"]
end
end
def test_use_xml_ximple_with_empty_request
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} }
assert_equal "", @controller.response.body
end
end
def test_dasherized_keys_as_xml
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
post "/?full=1", "<first-key>\n<sub-key>...</sub-key>\n</first-key>",
{'CONTENT_TYPE' => 'application/xml'}
assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body
assert_equal "...", @controller.params[:first_key][:sub_key]
end
end
def test_typecast_as_xml
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
xml = <<-XML
<data>
<a type="integer">15</a>
<b type="boolean">false</b>
<c type="boolean">true</c>
<d type="date">2005-03-17</d>
<e type="datetime">2005-03-17T21:41:07Z</e>
<f>unparsed</f>
<g type="integer">1</g>
<g>hello</g>
<g type="date">1974-07-25</g>
</data>
XML
post "/", xml, {'CONTENT_TYPE' => 'application/xml'}
params = @controller.params
assert_equal 15, params[:data][:a]
assert_equal false, params[:data][:b]
assert_equal true, params[:data][:c]
assert_equal Date.new(2005,3,17), params[:data][:d]
assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e]
assert_equal "unparsed", params[:data][:f]
assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g]
end
end
def test_entities_unescaped_as_xml_simple
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
xml = <<-XML
<data>&lt;foo &quot;bar&apos;s&quot; &amp; friends&gt;</data>
XML
post "/", xml, {'CONTENT_TYPE' => 'application/xml'}
assert_equal %(<foo "bar's" & friends>), @controller.params[:data]
end
end
def test_typecast_as_yaml
with_test_route_set do
ActionController::Base.param_parsers[Mime::YAML] = :yaml
yaml = <<-YAML
---
data:
a: 15
b: false
c: true
d: 2005-03-17
e: 2005-03-17T21:41:07Z
f: unparsed
g:
- 1
- hello
- 1974-07-25
YAML
post "/", yaml, {'CONTENT_TYPE' => 'application/x-yaml'}
params = @controller.params
assert_equal 15, params[:data][:a]
assert_equal false, params[:data][:b]
assert_equal true, params[:data][:c]
assert_equal Date.new(2005,3,17), params[:data][:d]
assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e]
assert_equal "unparsed", params[:data][:f]
assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g]
end
end
private
def with_test_route_set
with_routing do |set|
set.draw do |map|
map.with_options :controller => "web_service_test/test" do |c|
c.connect "/", :action => "assign_parameters"
end
end
yield
end
end
end