TeX and CSS tweaks.

Sync with latest Instiki Trunk
(Updates Rails to 1.2.2)
This commit is contained in:
Jacques Distler 2007-02-09 02:04:31 -06:00
parent 0ac586ee25
commit c358389f25
443 changed files with 24218 additions and 9823 deletions

View file

@ -4,14 +4,14 @@ require File.dirname(__FILE__) + '/../abstract_unit'
class ActionPackAssertionsController < ActionController::Base
# this does absolutely nothing
def nothing() render_text ""; end
def nothing() head :ok end
# a standard template
def hello_world() render "test/hello_world"; end
# a standard template
def hello_xml_world() render "test/hello_xml_world"; end
# a redirect to an internal location
def redirect_internal() redirect_to "/nothing"; end
@ -22,18 +22,18 @@ class ActionPackAssertionsController < ActionController::Base
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_url "http://www.rubyonrails.org"; end
# a 404
def response404() render_text "", "404 AWOL"; end
def response404() head '404 AWOL' end
# a 500
def response500() render_text "", "500 Sorry"; end
def response500() head '500 Sorry' end
# a fictional 599
def response599() render_text "", "599 Whoah!"; end
def response599() head '599 Whoah!' end
# putting stuff in the flash
def flash_me
@ -54,64 +54,68 @@ class ActionPackAssertionsController < ActionController::Base
end
def render_based_on_parameters
render_text "Mr. #{@params["name"]}"
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']}"
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
raise "post" if request.post?
render_text "request method: #{request.env['REQUEST_METHOD']}"
end
def get_valid_record
@record = Class.new do
@record = Class.new do
def valid?
true
end
def errors
Class.new do
def full_messages; []; end
Class.new do
def full_messages; []; end
end.new
end
end
end.new
render :nothing => true
render :nothing => true
end
def get_invalid_record
@record = Class.new do
@record = Class.new do
def valid?
false
end
def errors
Class.new do
def full_messages; ['...stuff...']; end
Class.new do
def full_messages; ['...stuff...']; end
end.new
end
end.new
render :nothing => true
end.new
render :nothing => true
end
# 911
@ -120,32 +124,51 @@ 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
# ---------------------------------------------------------------------------
# tell the controller where to find its templates but start from parent
# directory of test_request_response to simulate the behaviour of a
# tell the controller where to find its templates but start from parent
# directory of test_request_response to simulate the behaviour of a
# production environment
ActionPackAssertionsController.template_root = File.dirname(__FILE__) + "/../fixtures/"
# a test case to exercise the new capabilities TestRequest & TestResponse
class ActionPackAssertionsControllerTest < Test::Unit::TestCase
# let's get this party started
# let's get this party started
def setup
ActionController::Routing::Routes.reload
ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module content admin/user))
@controller = ActionPackAssertionsController.new
@request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
end
def teardown
ActionController::Routing::Routes.reload
end
# -- assertion-based testing ------------------------------------------------
def test_assert_tag_and_url_for
@ -156,10 +179,10 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
# test the session assertion to make sure something is there.
def test_assert_session_has
process :session_stuffing
assert_session_has 'xmas'
assert_session_has_no 'halloween'
assert_deprecated_assertion { assert_session_has 'xmas' }
assert_deprecated_assertion { assert_session_has_no 'halloween' }
end
# test the get method, make sure the request really was a get
def test_get
assert_raise(RuntimeError) { get :raise_on_get }
@ -173,7 +196,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
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
@ -190,106 +213,168 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
# test the assertion of goodies in the template
def test_assert_template_has
process :assign_this
assert_template_has 'howdy'
assert_deprecated_assertion { assert_template_has 'howdy' }
end
# test the assertion for goodies that shouldn't exist in the template
def test_assert_template_has_no
process :nothing
assert_template_has_no 'maple syrup'
assert_template_has_no 'howdy'
assert_deprecated_assertion { assert_template_has_no 'maple syrup' }
assert_deprecated_assertion { assert_template_has_no 'howdy' }
end
# test the redirection assertions
def test_assert_redirect
process :redirect_internal
assert_redirect
assert_deprecated_assertion { assert_redirect }
end
# test the redirect url string
def test_assert_redirect_url
process :redirect_external
assert_redirect_url 'http://www.rubyonrails.org'
assert_deprecated_assertion do
assert_redirect_url 'http://www.rubyonrails.org'
end
end
# test the redirection pattern matching on a string
def test_assert_redirect_url_match_string
process :redirect_external
assert_redirect_url_match 'rails.org'
assert_deprecated_assertion do
assert_redirect_url_match 'rails.org'
end
end
# test the redirection pattern matching on a pattern
def test_assert_redirect_url_match_pattern
process :redirect_external
assert_redirect_url_match /ruby/
assert_deprecated_assertion do
assert_redirect_url_match /ruby/
end
end
# test the redirection to a named route
def test_assert_redirect_to_named_route
process :redirect_to_named_route
assert_raise(Test::Unit::AssertionFailedError) do
assert_redirected_to 'http://test.host/route_two'
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.named_routes.install
process :redirect_to_named_route
assert_redirected_to 'http://test.host/route_one'
assert_redirected_to route_one_url
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(Test::Unit::AssertionFailedError) do
assert_redirected_to 'http://test.host/route_two'
end
assert_raise(Test::Unit::AssertionFailedError) do
assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two'
end
assert_raise(Test::Unit::AssertionFailedError) do
assert_redirected_to route_two_url
end
assert_raise(Test::Unit::AssertionFailedError) 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
# passes -> assert_redirected_to "http://test.host/action_pack_assertions/foo"
assert_redirected_to "/action_pack_assertions/foo"
end
end
# test the flash-based assertions with something is in the flash
def test_flash_assertions_full
process :flash_me
assert @response.has_flash_with_contents?
assert_flash_exists
assert_flash_not_empty
assert_flash_has 'hello'
assert_flash_has_no 'stds'
assert_deprecated_assertion { assert_flash_exists }
assert_deprecated_assertion { assert_flash_not_empty }
assert_deprecated_assertion { assert_flash_has 'hello' }
assert_deprecated_assertion { assert_flash_has_no 'stds' }
end
# test the flash-based assertions with no flash at all
def test_flash_assertions_negative
process :nothing
assert_flash_empty
assert_flash_has_no 'hello'
assert_flash_has_no 'qwerty'
assert_deprecated_assertion { assert_flash_empty }
assert_deprecated_assertion { assert_flash_has_no 'hello' }
assert_deprecated_assertion { assert_flash_has_no 'qwerty' }
end
# test the assert_rendered_file
# test the assert_rendered_file
def test_assert_rendered_file
process :hello_world
assert_rendered_file 'test/hello_world'
assert_rendered_file 'hello_world'
assert_deprecated(/render/) { process :hello_world }
assert_deprecated_assertion { assert_rendered_file 'test/hello_world' }
assert_deprecated_assertion { assert_rendered_file 'hello_world' }
end
# test the assert_success assertion
def test_assert_success
process :nothing
assert_success
assert_rendered_file
assert_deprecated_assertion { assert_success }
end
# -- standard request/response object testing --------------------------------
# ensure our session is working properly
def test_session_objects
process :session_stuffing
assert @response.has_session_object?('xmas')
assert_session_equal 'turkey', 'xmas'
assert_deprecated_assertion { assert_session_equal 'turkey', 'xmas' }
assert !@response.has_session_object?('easter')
end
# 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
def test_assigned_equal
process :assign_this
assert_assigned_equal "ho", :howdy
assert_deprecated_assertion { assert_assigned_equal "ho", :howdy }
end
# check the empty flashing
@ -314,24 +399,25 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
assert !@response.has_flash_with_contents?
assert_nil @response.flash['hello']
end
# examine that the flash objects are what we expect
def test_flash_equals
process :flash_me
assert_flash_equal 'my name is inigo montoya...', 'hello'
assert_deprecated_assertion do
assert_flash_equal 'my name is inigo montoya...', 'hello'
end
end
# check if we were rendered by a file-based template?
# check if we were rendered by a file-based template?
def test_rendered_action
process :nothing
assert !@response.rendered_with_file?
process :hello_world
assert_deprecated(/render/) { process :hello_world }
assert @response.rendered_with_file?
assert 'hello_world', @response.rendered_file
end
# check the redirection location
def test_redirection_location
process :redirect_internal
@ -339,24 +425,26 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
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
# 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
@ -372,7 +460,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
assert !@response.redirect_url_match?("phpoffrails")
assert !@response.redirect_url_match?(/perloffrails/)
end
# check for a redirection
def test_redirection
process :redirect_internal
@ -384,51 +472,57 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
process :nothing
assert !@response.redirect?
end
# check a successful response code
def test_successful_response_code
process :nothing
assert @response.success?
end
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_template_xpath_match_no_matches
process :hello_xml_world
assert_deprecated(/render/) { process :hello_xml_world }
assert_raises Test::Unit::AssertionFailedError do
assert_template_xpath_match('/no/such/node/in/document')
assert_deprecated_assertion do
assert_template_xpath_match('/no/such/node/in/document')
end
end
end
def test_simple_one_element_xpath_match
process :hello_xml_world
assert_template_xpath_match('//title', "Hello World")
assert_deprecated(/render/) { process :hello_xml_world }
assert_deprecated_assertion do
assert_template_xpath_match('//title', "Hello World")
end
end
def test_array_of_elements_in_xpath_match
process :hello_xml_world
assert_template_xpath_match('//p', %w( abes monks wiseguys ))
assert_deprecated(/render/) { process :hello_xml_world }
assert_deprecated_assertion do
assert_template_xpath_match('//p', %w( abes monks wiseguys ))
end
end
def test_follow_redirect
process :redirect_to_action
assert_redirected_to :action => "flash_me"
follow_redirect
assert_equal 1, @request.parameters["id"].to_i
assert "Inconceivable!", @response.body
end
def test_follow_redirect_outside_current_action
process :redirect_to_controller
assert_redirected_to :controller => "elsewhere", :action => "flash_me"
@ -436,6 +530,18 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
assert_raises(RuntimeError, "Can't follow redirects outside of current controller (elsewhere)") { follow_redirect }
end
def test_assert_redirection_fails_with_incorrect_controller
process :redirect_to_controller
assert_raise(Test::Unit::AssertionFailedError) 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_leadling_slash
process :redirect_to_path
assert_redirected_to '/some/path'
@ -453,41 +559,52 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
@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
end
def test_assert_valid
get :get_valid_record
assert_valid assigns('record')
end
assert_valid assigns('record')
end
def test_assert_valid_failing
get :get_invalid_record
begin
assert_valid assigns('record')
assert_valid assigns('record')
assert false
rescue Test::Unit::AssertionFailedError => e
rescue Test::Unit::AssertionFailedError => e
end
end
protected
def assert_deprecated_assertion(&block)
assert_deprecated(/assert/, &block)
end
end
class ActionPackHeaderTest < Test::Unit::TestCase
class ActionPackHeaderTest < Test::Unit::TestCase
def setup
@controller = ActionPackAssertionsController.new
@request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
end
def test_rendering_xml_sets_content_type
process :hello_xml_world
assert_equal('application/xml', @controller.headers['Content-Type'])
assert_deprecated(/render/) { process :hello_xml_world }
assert_equal('application/xml; charset=utf-8', @controller.headers['Content-Type'])
end
def test_rendering_xml_respects_content_type
@response.headers['Content-Type'] = 'application/pdf'
process :hello_xml_world
assert_equal('application/pdf', @controller.headers['Content-Type'])
assert_deprecated(/render/) { process :hello_xml_world }
assert_equal('application/pdf; charset=utf-8', @controller.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

@ -5,23 +5,21 @@ 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
scaffold :address
def self.controller_name; "addresses"; end
def self.controller_path; "addresses"; end
end
AddressesTestController.template_root = File.dirname(__FILE__) + "/../fixtures/"
@ -44,6 +42,4 @@ class AddressesTest < Test::Unit::TestCase
get :list
assert_equal "We only need to get this far!", @response.body.chomp
end
end

View file

@ -12,6 +12,7 @@ module Submodule
hide_action :hidden_action
def hidden_action
raise "Noooo!"
end
def another_hidden_action
@ -23,7 +24,6 @@ module Submodule
end
end
class EmptyController < ActionController::Base
include ActionController::Caching
end
class NonEmptyController < ActionController::Base
def public_action
@ -34,10 +34,27 @@ class NonEmptyController < ActionController::Base
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 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
@ -57,10 +74,63 @@ class ControllerInstanceTests < Test::Unit::TestCase
def test_action_methods
@empty_controllers.each do |c|
assert_equal Set.new, c.send(:action_methods), "#{c.class.controller_path} should be empty!"
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|
assert_equal Set.new('public_action'), c.send(:action_methods), "#{c.class.controller_path} should not be empty!"
hide_mocha_methods_from_controller(c)
assert_equal Set.new('public_action'), c.send(:action_methods), "#{c.controller_path} should not be empty!"
end
end
protected
# Mocha adds methods to Object which are then included in the public_instance_methods
# This method hides those from the controller so the above tests won't know the difference
def hide_mocha_methods_from_controller(controller)
mocha_methods = [:expects, :metaclass, :mocha, :mocha_inspect, :reset_mocha, :stubba_object, :stubba_method, :stubs, :verify]
controller.class.send(:hide_action, *mocha_methods)
end
end
class PerformActionTest < Test::Unit::TestCase
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"
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
end

View file

@ -7,15 +7,15 @@ class CaptureController < ActionController::Base
def content_for
render :layout => "talk_from_action"
end
def erb_content_for
render :layout => "talk_from_action"
end
def block_content_for
render :layout => "talk_from_action"
end
def non_erb_block_content_for
render :layout => "talk_from_action"
end
@ -43,36 +43,38 @@ class CaptureTest < Test::Unit::TestCase
get :capturing
assert_equal "Dreamy days", @response.body.strip
end
def test_content_for
get :content_for
assert_equal expected_content_for_output, @response.body
end
def test_erb_content_for
get :content_for
assert_equal expected_content_for_output, @response.body
end
def test_block_content_for
get :block_content_for
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
def test_update_element_with_capture
get :update_element_with_capture
assert_deprecated 'update_element_function' do
get :update_element_with_capture
end
assert_equal(
"<script type=\"text/javascript\">\n//<![CDATA[\n$('products').innerHTML = '\\n <p>Product 1</p>\\n <p>Product 2</p>\\n';\n\n//]]>\n</script>" +
"\n\n$('status').innerHTML = '\\n <b>You bought something!</b>\\n';",
"\n\n$('status').innerHTML = '\\n <b>You bought something!</b>\\n';",
@response.body.strip
)
end
private
def expected_content_for_output
"<title>Putting stuff in the title!</title>\n\nGreat stuff!"

View file

@ -17,6 +17,7 @@ class CGITest < Test::Unit::TestCase
@query_string_without_equal = "action"
@query_string_with_many_ampersands =
"&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
@query_string_with_empty_key = "action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save"
end
def test_query_string
@ -27,13 +28,43 @@ class CGITest < Test::Unit::TestCase
end
def test_deep_query_string
assert_equal({'x' => {'y' => {'z' => '10'}}}, CGIMethods.parse_query_parameters('x[y][z]=10'))
expected = {'x' => {'y' => {'z' => '10'}}}
assert_equal(expected, CGIMethods.parse_query_parameters('x[y][z]=10'))
end
def test_deep_query_string_with_array
assert_equal({'x' => {'y' => {'z' => ['10']}}}, CGIMethods.parse_query_parameters('x[y][z][]=10'))
assert_equal({'x' => {'y' => {'z' => ['10', '5']}}}, CGIMethods.parse_query_parameters('x[y][z][]=10&x[y][z][]=5'))
end
def test_deep_query_string_with_array_of_hash
assert_equal({'x' => {'y' => [{'z' => '10'}]}}, CGIMethods.parse_query_parameters('x[y][][z]=10'))
assert_equal({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][w]=10'))
end
def test_deep_query_string_with_array_of_hashes_with_one_pair
assert_equal({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][z]=20'))
assert_equal("10", CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][z]=20')["x"]["y"].first["z"])
assert_equal("10", CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][z]=20').with_indifferent_access[:x][:y].first[:z])
end
def test_request_hash_parsing
query = {
"note[viewers][viewer][][type]" => ["User", "Group"],
"note[viewers][viewer][][id]" => ["1", "2"]
}
expected = { "note" => { "viewers"=>{"viewer"=>[{ "id"=>"1", "type"=>"User"}, {"type"=>"Group", "id"=>"2"} ]} } }
assert_equal(expected, CGIMethods.parse_request_parameters(query))
end
def test_deep_query_string_with_array_of_hashes_with_multiple_pairs
assert_equal(
{'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}},
CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b')
)
end
def test_query_string_with_nil
assert_equal(
@ -69,6 +100,13 @@ class CGITest < Test::Unit::TestCase
CGIMethods.parse_query_parameters(@query_string_without_equal)
)
end
def test_query_string_with_empty_key
assert_equal(
{ "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
CGIMethods.parse_query_parameters(@query_string_with_empty_key)
)
end
def test_query_string_with_many_ampersands
assert_equal(
@ -87,7 +125,8 @@ class CGITest < Test::Unit::TestCase
"something_nil" => [ nil ],
"something_empty" => [ "" ],
"products[first]" => [ "Apple Computer" ],
"products[second]" => [ "Pc" ]
"products[second]" => [ "Pc" ],
"" => [ 'Save' ]
}
expected_output = {
@ -116,9 +155,10 @@ class CGITest < Test::Unit::TestCase
end
def test_parse_params_from_multipart_upload
mockup = Struct.new(:content_type, :original_filename)
mockup = Struct.new(:content_type, :original_filename, :read, :rewind)
file = mockup.new('img/jpeg', 'foo.jpg')
ie_file = mockup.new('img/jpeg', 'c:\\Documents and Settings\\foo\\Desktop\\bar.jpg')
non_file_text_part = mockup.new('text/plain', '', 'abc')
input = {
"something" => [ StringIO.new("") ],
@ -129,9 +169,10 @@ class CGITest < Test::Unit::TestCase
"products[string]" => [ StringIO.new("Apple Computer") ],
"products[file]" => [ file ],
"ie_products[string]" => [ StringIO.new("Microsoft") ],
"ie_products[file]" => [ ie_file ]
"ie_products[file]" => [ ie_file ],
"text_part" => [non_file_text_part]
}
expected_output = {
"something" => "",
"array_of_stringios" => ["One", "Two"],
@ -153,7 +194,8 @@ class CGITest < Test::Unit::TestCase
"ie_products" => {
"string" => "Microsoft",
"file" => ie_file
}
},
"text_part" => "abc"
}
params = CGIMethods.parse_request_parameters(input)
@ -206,29 +248,36 @@ class CGITest < Test::Unit::TestCase
def test_parse_params_with_single_brackets_in_middle
input = { "a/b[c]d" => %w(e) }
expected = { "a/b[c]d" => "e" }
expected = { "a/b" => {} }
assert_equal expected, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_separated_brackets
input = { "a/b@[c]d[e]" => %w(f) }
expected = { "a/b@" => { "c]d[e" => "f" }}
expected = { "a/b@" => { }}
assert_equal expected, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_separated_brackets_and_array
input = { "a/b@[c]d[e][]" => %w(f) }
expected = { "a/b@" => { "c]d[e" => ["f"] }}
expected = { "a/b@" => { }}
assert_equal expected , CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_unmatched_brackets_and_array
input = { "a/b@[c][d[e][]" => %w(f) }
expected = { "a/b@" => { "c" => { "d[e" => ["f"] }}}
expected = { "a/b@" => { "c" => { }}}
assert_equal expected, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_nil_key
input = { nil => nil, "test2" => %w(value1) }
expected = { "test2" => "value1" }
assert_equal expected, CGIMethods.parse_request_parameters(input)
end
end
class MultipartCGITest < Test::Unit::TestCase
FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart'
@ -292,23 +341,39 @@ class MultipartCGITest < Test::Unit::TestCase
assert_equal 'bar', params['foo']
# Ruby CGI doesn't handle multipart/mixed for us.
assert_kind_of StringIO, params['files']
assert_kind_of String, params['files']
assert_equal 19756, params['files'].size
end
# Rewind readable cgi params so others may reread them (such as CGI::Session
# when passing the session id in a multipart form).
def test_multipart_param_rewound
params = process('text_file')
assert_equal 'bar', @cgi.params['foo'][0].read
end
private
def process(name)
old_stdin = $stdin
File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
ENV['CONTENT_LENGTH'] = file.stat.size.to_s
$stdin = file
CGIMethods.parse_request_parameters CGI.new.params
@cgi = CGI.new
CGIMethods.parse_request_parameters @cgi.params
end
ensure
$stdin = old_stdin
end
end
# Ensures that PUT works with multipart as well as POST.
class PutMultipartCGITest < MultipartCGITest
def setup
super
ENV['REQUEST_METHOD'] = 'PUT'
end
end
class CGIRequestTest < Test::Unit::TestCase
def setup
@ -360,4 +425,16 @@ class CGIRequestTest < Test::Unit::TestCase
assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], alt_cookies["_session_id"]
assert_equal ["yes"], alt_cookies["is_admin"]
end
def test_unbalanced_query_string_with_array
assert_equal(
{'location' => ["1", "2"], 'age_group' => ["2"]},
CGIMethods.parse_query_parameters("location[]=1&location[]=2&age_group[]=2")
)
assert_equal(
{'location' => ["1", "2"], 'age_group' => ["2"]},
CGIMethods.parse_request_parameters({'location[]' => ["1", "2"],
'age_group[]' => ["2"]})
)
end
end

View file

@ -46,7 +46,7 @@ end
class CalleeController < ActionController::Base
def being_called
render_text "#{@params["name"] || "Lady"} of the House, speaking"
render_text "#{params[:name] || "Lady"} of the House, speaking"
end
def blowing_up
@ -126,4 +126,26 @@ class ComponentsTest < Test::Unit::TestCase
assert_equal "Lady of the House, speaking", @response.body
end
end
end
module A
module B
module C
class NestedController < ActionController::Base
# Stub for uses_component_template_root
def self.caller
[ '/path/to/active_support/deprecation.rb:93:in `uses_component_template_root',
'./test/fixtures/a/b/c/nested_controller.rb' ]
end
end
end
end
end
class UsesComponentTemplateRootTest < Test::Unit::TestCase
def test_uses_component_template_root
assert_deprecated 'uses_component_template_root' do
assert_equal './test/fixtures/', A::B::C::NestedController.uses_component_template_root
end
end
end

View file

@ -4,77 +4,85 @@ class CookieTest < Test::Unit::TestCase
class TestController < ActionController::Base
def authenticate_with_deprecated_writer
cookie "name" => "user_name", "value" => "david"
render_text "hello world"
end
def authenticate
cookies["user_name"] = "david"
render_text "hello world"
end
def authenticate_for_fourten_days
cookies["user_name"] = { "value" => "david", "expires" => Time.local(2005, 10, 10) }
render_text "hello world"
end
def authenticate_for_fourten_days_with_symbols
cookies[:user_name] = { :value => "david", :expires => Time.local(2005, 10, 10) }
render_text "hello world"
end
def set_multiple_cookies
cookies["user_name"] = { "value" => "david", "expires" => Time.local(2005, 10, 10) }
cookies["login"] = "XJ-122"
render_text "hello world"
end
def access_frozen_cookies
@cookies["will"] = "work"
render_text "hello world"
cookies["will"] = "work"
end
def rescue_action(e) raise end
def logout
cookies.delete("user_name")
end
def rescue_action(e)
raise unless ActionController::MissingTemplate # No templates here, and we don't care about the output
end
end
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = TestController.new
@request.host = "www.nextangle.com"
end
def test_setting_cookie_with_deprecated_writer
@request.action = "authenticate_with_deprecated_writer"
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], process_request.headers["cookie"]
get :authenticate_with_deprecated_writer
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], @response.headers["cookie"]
end
def test_setting_cookie
@request.action = "authenticate"
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], process_request.headers["cookie"]
get :authenticate
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], @response.headers["cookie"]
end
def test_setting_cookie_for_fourteen_days
@request.action = "authenticate_for_fourten_days"
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], process_request.headers["cookie"]
get :authenticate_for_fourten_days
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], @response.headers["cookie"]
end
def test_setting_cookie_for_fourteen_days_with_symbols
@request.action = "authenticate_for_fourten_days"
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], process_request.headers["cookie"]
get :authenticate_for_fourten_days
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], @response.headers["cookie"]
end
def test_multiple_cookies
@request.action = "set_multiple_cookies"
assert_equal 2, process_request.headers["cookie"].size
get :set_multiple_cookies
assert_equal 2, @response.cookies.size
end
def test_setting_test_cookie
@request.action = "access_frozen_cookies"
assert_nothing_raised { process_request }
assert_nothing_raised { get :access_frozen_cookies }
end
def test_expiring_cookie
get :logout
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "", "expires" => Time.at(0)) ], @response.headers["cookie"]
end
def test_cookiejar_accessor
@request.cookies["user_name"] = CGI::Cookie.new("name" => "user_name", "value" => "david", "expires" => Time.local(2025, 10, 10))
@controller.request = @request
jar = ActionController::CookieJar.new(@controller)
assert_equal "david", jar["user_name"]
assert_equal nil, jar["something_else"]
end
private
def process_request
TestController.process(@request, @response)
end
end

View file

@ -6,7 +6,6 @@ class NotAController
end
module Admin
class << self; alias_method :const_available?, :const_defined?; end
SomeConstant = 10
class UserController < Class.new(ActionController::Base); end
class NewsFeedController < Class.new(ActionController::Base); end
end

View file

@ -21,6 +21,34 @@ class FilterTest < Test::Unit::TestCase
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
action_name != "fail_#{i}"
end
end
end
class RenderingController < ActionController::Base
before_filter :render_something_else
@ -134,7 +162,7 @@ class FilterTest < Test::Unit::TestCase
@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]
@ -152,6 +180,10 @@ class FilterTest < Test::Unit::TestCase
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.assigns["ran_proc_filter"] = true })
end
@ -198,15 +230,6 @@ class FilterTest < Test::Unit::TestCase
end
end
class BadFilterController < ActionController::Base
before_filter 2
def show() "show" end
protected
def rescue_action(e) raise(e) end
end
class AroundFilterController < PrependingController
around_filter AroundFilter.new
end
@ -336,19 +359,20 @@ class FilterTest < Test::Unit::TestCase
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_bad_filter
assert_raises(ActionController::ActionControllerError) {
test_process(BadFilterController)
}
bad_filter_controller = Class.new(ActionController::Base)
assert_raises(ActionController::ActionControllerError) do
bad_filter_controller.before_filter 2
end
end
def test_around_filter
controller = test_process(AroundFilterController)
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"]
@ -401,6 +425,16 @@ class FilterTest < Test::Unit::TestCase
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
private
def test_process(controller, action = "show")
request = ActionController::TestRequest.new
@ -408,3 +442,254 @@ class FilterTest < Test::Unit::TestCase
controller.process(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.assigns['before'] = true
b.call
c.assigns['after'] = true
end
end
class ControllerWithWrongFilterType < PostsController
around_filter lambda { yield }, :only => :no_raise
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 1, ControllerWithWrongFilterType.filter_chain.size
assert_equal 6, ControllerWithNestedFilters.filter_chain.size
assert_equal 4, ControllerWithAllTypesOfFilters.filter_chain.size
end
def test_wrong_filter_type
assert_raise(ActionController::ActionControllerError) do
test_process(ControllerWithWrongFilterType,'no_raise')
end
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")
request = ActionController::TestRequest.new
request.action = action
controller.process(request, ActionController::TestResponse.new)
end
end

View file

@ -35,6 +35,16 @@ class FlashTest < Test::Unit::TestCase
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 ActionController::MissingTemplate === e
end
@ -60,7 +70,7 @@ class FlashTest < Test::Unit::TestCase
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
assert_deprecated(/keep_flash/) { get :use_flash_and_keep_it }
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "hello", @response.template.assigns["flashy"]
@ -82,4 +92,11 @@ class FlashTest < Test::Unit::TestCase
assert_nil @response.template.assigns["flash_copy"]["foo"]
assert_nil @response.template.assigns["flashy"]
end
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
end

View file

@ -77,8 +77,8 @@ class HelperTest < Test::Unit::TestCase
def test_declare_missing_file_from_helper
require 'broken_helper'
rescue LoadError => e
assert_nil /\bbroken_helper\b/.match(e.to_s)[1]
rescue LoadError => e
assert_nil(/\bbroken_helper\b/.match(e.to_s)[1])
end
def test_helper_block

View file

@ -70,4 +70,118 @@ class LayoutAutoDiscoveryTest < Test::Unit::TestCase
assert_equal 'layouts/controller_name_space/nested', @controller.active_layout
assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
end
end
end
class ExemptFromLayoutTest < Test::Unit::TestCase
def setup
@controller = LayoutTest.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_rjs_exempt_from_layout
assert @controller.send(:template_exempt_from_layout?, 'test.rjs')
end
def test_rhtml_and_rxml_not_exempt_from_layout
assert !@controller.send(:template_exempt_from_layout?, 'test.rhtml')
assert !@controller.send(:template_exempt_from_layout?, 'test.rxml')
end
def test_other_extension_not_exempt_from_layout
assert !@controller.send(:template_exempt_from_layout?, 'test.random')
end
def test_add_extension_to_exempt_from_layout
['rpdf', :rpdf].each do |ext|
assert_nothing_raised do
ActionController::Base.exempt_from_layout ext
end
assert @controller.send(:template_exempt_from_layout?, "test.#{ext}")
end
end
def test_add_regexp_to_exempt_from_layout
ActionController::Base.exempt_from_layout /\.rdoc/
assert @controller.send(:template_exempt_from_layout?, 'test.rdoc')
end
def test_rhtml_exempt_from_layout_status_should_prevent_layout_render
ActionController::Base.exempt_from_layout :rhtml
assert @controller.send(:template_exempt_from_layout?, 'test.rhtml')
get :hello
assert_equal 'hello.rhtml', @response.body
ActionController::Base.exempt_from_layout.delete(/\.rhtml$/)
end
end
class DefaultLayoutController < LayoutTest
end
class HasOwnLayoutController < LayoutTest
layout 'item'
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 < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
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
end
class SetsNonExistentLayoutFile < LayoutTest
layout "nofile.rhtml"
end
class LayoutExceptionRaised < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_exception_raised_when_layout_file_not_found
@controller = SetsNonExistentLayoutFile.new
get :hello
@response.template.class.module_eval { attr_accessor :exception }
assert_equal ActionController::MissingTemplate, @response.template.exception.class
end
end

View file

@ -20,6 +20,13 @@ class RespondToController < ActionController::Base
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" }
@ -61,6 +68,29 @@ class RespondToController < ActionController::Base
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
Mime.send :remove_const, :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
Mime.send :remove_const, :MOBILE
end
def handle_any
respond_to do |type|
@ -141,6 +171,27 @@ class MimeControllerTest < Test::Unit::TestCase
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.env['HTTP_ACCEPT'] = content_type
get :json_or_yaml
assert_equal body, @response.body
end
end
end
def test_js_or_anything
@request.env["HTTP_ACCEPT"] = "text/javascript, */*"
get :js_or_html
@ -254,4 +305,47 @@ class MimeControllerTest < Test::Unit::TestCase
xhr :get, :using_defaults
assert_equal '$("body").visualEffect("highlight");', @response.body
end
def test_custom_constant
get :custom_constant_handling, :format => "mobile"
assert_equal "Mobile", @response.body
end
def custom_constant_handling_without_block
assert_raised(ActionController::RenderError) do
get :custom_constant_handling, :format => "mobile"
end
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_render_action_for_html
@controller.instance_eval do
def render(*args)
unless args.empty?
@action = args.first[:action]
end
response.body = @action
end
end
get :using_defaults
assert_equal "using_defaults", @response.body
get :using_defaults, :format => "xml"
assert_equal "using_defaults.rxml", @response.body
end
end

View file

@ -21,4 +21,13 @@ class MimeTypeTest < Test::Unit::TestCase
expect = [Mime::HTML, Mime::XML, Mime::PNG, Mime::PLAIN, Mime::YAML, Mime::ALL]
assert_equal expect, Mime::Type.parse(accept)
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
Mime.send :remove_const, :GIF
end
end

View file

@ -161,6 +161,33 @@ class NewRenderTestController < ActionController::Base
render :text => "How's there? #{render_to_string("test/list")}"
end
def render_to_string_with_assigns
@before = "i'm before the render"
render_to_string :text => "foo"
@after = "i'm after the render"
render :action => "test/hello_world"
end
def render_to_string_with_partial
@partial_only = render_to_string :partial => "partial_only"
@partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") }
render :action => "test/hello_world"
end
def render_to_string_with_exception
render_to_string :file => "exception that will not be caught - this will certainly not work", :use_full_path => true
end
def render_to_string_with_caught_exception
@before = "i'm before the render"
begin
render_to_string :file => "exception that will be caught- hope my future instance vars still work!", :use_full_path => true
rescue
end
@after = "i'm after the render"
render :action => "test/hello_world"
end
def accessing_params_in_template
render :inline => "Hello: <%= params[:name] %>"
end
@ -187,6 +214,11 @@ class NewRenderTestController < ActionController::Base
render :text => "hello"
redirect_to :action => "double_render"
end
def render_to_string_and_render
@stuff = render_to_string :text => "here is some cached stuff"
render :text => "Hi web users! #{@stuff}"
end
def rendering_with_conflicting_local_vars
@name = "David"
@ -202,6 +234,30 @@ class NewRenderTestController < ActionController::Base
render :template => "test/hello_world.rxml"
end
def head_with_location_header
head :location => "/foo"
end
def head_with_symbolic_status
head :status => params[:status].intern
end
def head_with_integer_status
head :status => params[:status].to_i
end
def head_with_string_status
head :status => params[:status]
end
def head_with_custom_header
head :x_custom_header => "something"
end
def head_with_status_code_first
head :forbidden, :x_custom_header => "something"
end
helper NewRenderTestHelper
helper do
def rjs_helper_method(value)
@ -263,6 +319,11 @@ class NewRenderTestController < ActionController::Base
render :action => "content_for", :layout => "yield"
end
def render_content_type_from_body
response.content_type = Mime::RSS
render :text => "hello world!"
end
def rescue_action(e) raise end
private
@ -393,18 +454,26 @@ class NewRenderTest < Test::Unit::TestCase
ActionController::Base.protected_variables_cache = nil
get :hello_world
assert_nil(assigns["request"])
assert !assigns.include?('request'), 'request should not be in assigns'
ActionController::Base.view_controller_internals = true
ActionController::Base.protected_variables_cache = nil
get :hello_world
assert_kind_of ActionController::AbstractRequest, assigns["request"]
assert assigns.include?('request'), 'request should be in assigns'
assert_deprecated 'request' do
assert_kind_of ActionController::AbstractRequest, assigns['request']
end
assert_not_deprecated do
assert_kind_of ActionController::AbstractRequest, @response.template.request
assert_kind_of ActionController::AbstractRequest, assigns['_request']
end
ensure
ActionController::Base.view_controller_internals = view_internals_old_value
ActionController::Base.protected_variables_cache = nil
end
def test_render_xml
get :render_xml_hello
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
@ -429,17 +498,17 @@ EOS
def test_render_rjs_with_default
get :delete_with_js
assert_equal %!["person"].each(Element.remove);\nnew Effect.Highlight(\"project-4\",{});!, @response.body
assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
end
def test_render_rjs_template_explicitly
get :render_js_with_explicit_template
assert_equal %!["person"].each(Element.remove);\nnew Effect.Highlight(\"project-4\",{});!, @response.body
assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
end
def test_rendering_rjs_action_explicitly
get :render_js_with_explicit_action_template
assert_equal %!["person"].each(Element.remove);\nnew Effect.Highlight(\"project-4\",{});!, @response.body
assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
end
def test_layout_rendering
@ -483,9 +552,31 @@ EOS
end
def test_render_to_string
get :hello_in_a_string
assert_not_deprecated { get :hello_in_a_string }
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_render_to_string_doesnt_break_assigns
get :render_to_string_with_assigns
assert_equal "i'm before the render", assigns(:before)
assert_equal "i'm after the render", assigns(:after)
end
def test_render_to_string_partial
get :render_to_string_with_partial
assert_equal "only partial", assigns(:partial_only)
assert_equal "Hello: david", assigns(:partial_with_locals)
end
def test_bad_render_to_string_still_throws_exception
assert_raises(ActionController::MissingTemplate) { get :render_to_string_with_exception }
end
def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns
assert_nothing_raised { get :render_to_string_with_caught_exception }
assert_equal "i'm before the render", assigns(:before)
assert_equal "i'm after the render", assigns(:after)
end
def test_nested_rendering
get :hello_world
@ -503,7 +594,7 @@ EOS
end
def test_render_with_explicit_template
get :render_with_explicit_template
assert_deprecated(/render/) { get :render_with_explicit_template }
assert_response :success
end
@ -518,6 +609,12 @@ EOS
def test_render_and_redirect
assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect }
end
# specify the one exception to double render rule - render_to_string followed by render
def test_render_to_string_and_render
get :render_to_string_and_render
assert_equal("Hi web users! here is some cached stuff", @response.body)
end
def test_rendering_with_conflicting_local_vars
get :rendering_with_conflicting_local_vars
@ -572,20 +669,20 @@ EOS
def test_update_page
get :update_page
assert_template nil
assert_equal 'text/javascript; charset=UTF-8', @response.headers['Content-Type']
assert_equal 'text/javascript; charset=utf-8', @response.headers['Content-Type']
assert_equal 2, @response.body.split($/).length
end
def test_update_page_with_instance_variables
get :update_page_with_instance_variables
assert_template nil
assert_equal 'text/javascript; charset=UTF-8', @response.headers['Content-Type']
assert_equal 'text/javascript; charset=utf-8', @response.headers['Content-Type']
assert_match /balance/, @response.body
assert_match /\$37/, @response.body
end
def test_yield_content_for
get :yield_content_for
assert_not_deprecated { get :yield_content_for }
assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body
end
@ -597,4 +694,57 @@ EOS
get :hello_world_from_rxml_using_action
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
end
def test_head_with_location_header
get :head_with_location_header
assert @response.body.blank?
assert_equal "/foo", @response.headers["Location"]
assert_response :ok
end
def test_head_with_custom_header
get :head_with_custom_header
assert @response.body.blank?
assert_equal "something", @response.headers["X-Custom-Header"]
assert_response :ok
end
def test_head_with_symbolic_status
get :head_with_symbolic_status, :status => "ok"
assert_equal "200 OK", @response.headers["Status"]
assert_response :ok
get :head_with_symbolic_status, :status => "not_found"
assert_equal "404 Not Found", @response.headers["Status"]
assert_response :not_found
ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code|
get :head_with_symbolic_status, :status => status.to_s
assert_equal code, @response.response_code
assert_response status
end
end
def test_head_with_integer_status
ActionController::StatusCodes::STATUS_CODES.each do |code, message|
get :head_with_integer_status, :status => code.to_s
assert_equal message, @response.message
end
end
def test_head_with_string_status
get :head_with_string_status, :status => "404 Eat Dirt"
assert_equal 404, @response.response_code
assert_equal "Eat Dirt", @response.message
assert_response :not_found
end
def test_head_with_status_code_first
get :head_with_status_code_first
assert_equal 403, @response.response_code
assert_equal "Forbidden", @response.message
assert_equal "something", @response.headers["X-Custom-Header"]
assert_response :forbidden
end
end

View file

@ -5,27 +5,64 @@ require File.dirname(__FILE__) + '/../../lib/action_controller/cgi_ext/raw_post_
class RawPostDataTest < Test::Unit::TestCase
def setup
ENV['REQUEST_METHOD'] = 'POST'
ENV['CONTENT_TYPE'] = ''
ENV['CONTENT_LENGTH'] = '0'
ENV.delete('RAW_POST_DATA')
@request_body = 'a=1'
end
def test_raw_post_data
process_raw "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
def test_post_with_urlencoded_body
ENV['REQUEST_METHOD'] = 'POST'
ENV['CONTENT_TYPE'] = ' apPlication/x-Www-form-urlEncoded; charset=utf-8'
assert_equal ['1'], cgi_params['a']
assert_has_raw_post_data
end
def test_post_with_empty_content_type_treated_as_urlencoded
ENV['REQUEST_METHOD'] = 'POST'
ENV['CONTENT_TYPE'] = ''
assert_equal ['1'], cgi_params['a']
assert_has_raw_post_data
end
def test_post_with_unrecognized_content_type_reads_body_but_doesnt_parse_params
ENV['REQUEST_METHOD'] = 'POST'
ENV['CONTENT_TYPE'] = 'foo/bar'
assert cgi_params.empty?
assert_has_raw_post_data
end
def test_put_with_urlencoded_body
ENV['REQUEST_METHOD'] = 'PUT'
ENV['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
assert_equal ['1'], cgi_params['a']
assert_has_raw_post_data
end
def test_put_with_empty_content_type_ignores_body
ENV['REQUEST_METHOD'] = 'PUT'
ENV['CONTENT_TYPE'] = ''
assert cgi_params.empty?
assert_has_raw_post_data
end
def test_put_with_unrecognized_content_type_ignores_body
ENV['REQUEST_METHOD'] = 'PUT'
ENV['CONTENT_TYPE'] = 'foo/bar'
assert cgi_params.empty?
assert_has_raw_post_data
end
private
def process_raw(query_string)
old_stdin = $stdin
begin
$stdin = StringIO.new(query_string.dup)
ENV['CONTENT_LENGTH'] = $stdin.size.to_s
CGI.new
assert_not_nil ENV['RAW_POST_DATA']
assert ENV['RAW_POST_DATA'].frozen?
assert_equal query_string, ENV['RAW_POST_DATA']
ensure
$stdin = old_stdin
end
def cgi_params
old_stdin, $stdin = $stdin, StringIO.new(@request_body.dup)
ENV['CONTENT_LENGTH'] = $stdin.size.to_s
CGI.new.params
ensure
$stdin = old_stdin
end
def assert_has_raw_post_data(expected_body = @request_body)
assert_not_nil ENV['RAW_POST_DATA']
assert ENV['RAW_POST_DATA'].frozen?
assert_equal expected_body, ENV['RAW_POST_DATA']
end
end

View file

@ -45,52 +45,60 @@ class RedirectTest < Test::Unit::TestCase
def test_simple_redirect
get :simple_redirect
assert_redirect_url "http://test.host/redirect/hello_world"
assert_response :redirect
assert_equal "http://test.host/redirect/hello_world", redirect_to_url
end
def test_redirect_with_method_reference_and_parameters
get :method_redirect
assert_redirect_url "http://test.host/redirect/dashboard/1?message=hello"
assert_deprecated(/redirect_to/) { get :method_redirect }
assert_response :redirect
assert_equal "http://test.host/redirect/dashboard/1?message=hello", 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_redirect_error_with_pretty_diff
get :host_redirect
assert_response :redirect
begin
assert_redirected_to :action => "other_host", :only_path => true
rescue Test::Unit::AssertionFailedError => err
redirection_msg, diff_msg = err.message.scan(/<\{[^\}]+\}>/).collect { |s| s[2..-3] }
assert_match %r(:only_path=>false), redirection_msg
assert_match %r(:host=>"other.test.host"), redirection_msg
assert_match %r(:action=>"other_host"), redirection_msg
assert_match %r(:only_path=>true), diff_msg
assert_match %r(:host=>"other.test.host"), diff_msg
assert_match %r("only_path"=>false), redirection_msg
assert_match %r("host"=>"other.test.host"), redirection_msg
assert_match %r("action"=>"other_host"), redirection_msg
assert_match %r("only_path"=>true), diff_msg
assert_match %r("host"=>"other.test.host"), diff_msg
end
end
def test_module_redirect
get :module_redirect
assert_redirect_url "http://test.host/module_test/module_redirect/hello_world"
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_back
@request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
get :redirect_to_back
assert_redirect_url "http://www.example.com/coming/from"
assert_response :redirect
assert_equal "http://www.example.com/coming/from", redirect_to_url
end
def test_redirect_to_back_with_no_referer
@ -117,26 +125,31 @@ module ModuleTest
def test_simple_redirect
get :simple_redirect
assert_redirect_url "http://test.host/module_test/module_redirect/hello_world"
assert_response :redirect
assert_equal "http://test.host/module_test/module_redirect/hello_world", redirect_to_url
end
def test_redirect_with_method_reference_and_parameters
get :method_redirect
assert_redirect_url "http://test.host/module_test/module_redirect/dashboard/1?message=hello"
assert_deprecated(/redirect_to/) { get :method_redirect }
assert_response :redirect
assert_equal "http://test.host/module_test/module_redirect/dashboard/1?message=hello", 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_redirect_url "http://test.host/redirect/hello_world"
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

View file

@ -34,15 +34,36 @@ class TestController < ActionController::Base
def render_action_hello_world_with_symbol
render_action :hello_world
end
def render_text_hello_world
render_text "hello world"
end
def render_json_hello_world
render_json({:hello => 'world'}.to_json)
end
def render_json_hello_world_with_callback
render_json({:hello => 'world'}.to_json, 'alert')
end
def render_symbol_json
render :json => {:hello => 'world'}.to_json
end
def render_custom_code
render_text "hello world", "404 Moved"
end
def render_text_appendix
render_text "hello world"
render_text ", goodbye!", "404 Not Found", true
end
def render_nothing_with_appendix
render_text "appended", nil, true
end
def render_xml_hello
@name = "David"
render "test/hello"
@ -55,11 +76,15 @@ class TestController < ActionController::Base
def layout_test
render_action "hello_world"
end
def builder_layout_test
render_action "hello"
end
def builder_partial_test
render_action "hello_world_container"
end
def partials_list
@test_unchanged = 'hello'
@customers = [ Customer.new("david"), Customer.new("mary") ]
@ -74,7 +99,7 @@ class TestController < ActionController::Base
@customers = [ Customer.new("david"), Customer.new("mary") ]
render_text "How's there? #{render_to_string("test/list")}"
end
def accessing_params_in_template
render_template "Hello: <%= params[:name] %>"
end
@ -84,7 +109,7 @@ class TestController < ActionController::Base
render :inline => "<%= 'Goodbye, ' + local_name %>",
:locals => { :local_name => name }
end
def accessing_local_assigns_in_inline_template_with_string_keys
name = params[:local_name]
ActionView::Base.local_assigns_support_string_keys = true
@ -98,12 +123,13 @@ class TestController < ActionController::Base
end
def rescue_action(e) raise end
private
def determine_layout
case action_name
case action_name
when "layout_test": "layouts/standard"
when "builder_layout_test": "layouts/builder"
when "render_symbol_json": "layouts/standard" # to make sure layouts don't interfere
end
end
end
@ -127,7 +153,7 @@ class RenderTest < Test::Unit::TestCase
end
def test_do_with_render
get :render_hello_world
assert_deprecated_render { get :render_hello_world }
assert_template "test/hello_world"
end
@ -151,11 +177,41 @@ class RenderTest < Test::Unit::TestCase
assert_equal "hello world", @response.body
end
def test_do_with_render_json
get :render_json_hello_world
assert_equal '{hello: "world"}', @response.body
assert_equal 'application/json', @response.content_type
end
def test_do_with_render_json_with_callback
get :render_json_hello_world_with_callback
assert_equal 'alert({hello: "world"})', @response.body
assert_equal 'application/json', @response.content_type
end
def test_do_with_render_symbol_json
get :render_symbol_json
assert_equal '{hello: "world"}', @response.body
assert_equal 'application/json', @response.content_type
end
def test_do_with_render_custom_code
get :render_custom_code
assert_response 404
end
def test_do_with_render_text_appendix
get :render_text_appendix
assert_response 404
assert_equal 'hello world, goodbye!', @response.body
end
def test_do_with_render_nothing_with_appendix
get :render_nothing_with_appendix
assert_response 200
assert_equal 'appended', @response.body
end
def test_attempt_to_access_object_method
assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone }
end
@ -164,27 +220,8 @@ class RenderTest < Test::Unit::TestCase
assert_raises(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout }
end
def test_access_to_request_in_view
view_internals_old_value = ActionController::Base.view_controller_internals
ActionController::Base.view_controller_internals = false
ActionController::Base.protected_variables_cache = nil
get :hello_world
assert_nil assigns["request"]
ActionController::Base.view_controller_internals = true
ActionController::Base.protected_variables_cache = nil
get :hello_world
assert_kind_of ActionController::AbstractRequest, assigns["request"]
ActionController::Base.view_controller_internals = view_internals_old_value
ActionController::Base.protected_variables_cache = nil
end
def test_render_xml
get :render_xml_hello
assert_deprecated_render { get :render_xml_hello }
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
end
@ -193,6 +230,11 @@ class RenderTest < Test::Unit::TestCase
assert_equal "<p>This is grand!</p>\n", @response.body
end
def test_render_xml_with_partial
get :builder_partial_test
assert_equal "<test>\n <hello/>\n</test>\n", @response.body
end
def test_layout_rendering
get :layout_test
assert_equal "<html>Hello world!</html>", @response.body
@ -238,9 +280,14 @@ class RenderTest < Test::Unit::TestCase
get :accessing_local_assigns_in_inline_template, :local_name => "Local David"
assert_equal "Goodbye, Local David", @response.body
end
def test_accessing_local_assigns_in_inline_template_with_string_keys
get :accessing_local_assigns_in_inline_template_with_string_keys, :local_name => "Local David"
assert_equal "Goodbye, Local David", @response.body
end
protected
def assert_deprecated_render(&block)
assert_deprecated(/render/, &block)
end
end

View file

@ -174,39 +174,55 @@ class RequestTest < Test::Unit::TestCase
assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
assert_equal "/path/of/some/uri", @request.path
@request.set_REQUEST_URI nil
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1"
@request.env['SCRIPT_NAME'] = "/path/dispatch.rb"
assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
assert_equal "/of/some/uri", @request.path
@request.set_REQUEST_URI nil
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/path/of/some/uri"
@request.env['SCRIPT_NAME'] = nil
assert_equal "/path/of/some/uri", @request.request_uri
assert_equal "/path/of/some/uri", @request.path
@request.set_REQUEST_URI nil
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/"
assert_equal "/", @request.request_uri
assert_equal "/", @request.path
@request.set_REQUEST_URI nil
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/?m=b"
assert_equal "/?m=b", @request.request_uri
assert_equal "/", @request.path
@request.set_REQUEST_URI nil
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/"
@request.env['SCRIPT_NAME'] = "/dispatch.cgi"
assert_equal "/", @request.request_uri
assert_equal "/", @request.path
assert_equal "/", @request.path
@request.set_REQUEST_URI nil
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/hieraki/"
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
assert_equal "/hieraki/", @request.request_uri
assert_equal "/", @request.path
assert_equal "/", @request.path
@request.set_REQUEST_URI '/hieraki/dispatch.cgi'
@request.relative_url_root = '/hieraki'
assert_equal "/dispatch.cgi", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI '/hieraki/dispatch.cgi'
@request.relative_url_root = '/foo'
assert_equal "/hieraki/dispatch.cgi", @request.path
@request.relative_url_root = nil
# This test ensures that Rails uses REQUEST_URI over PATH_INFO
@request.relative_url_root = nil
@ -216,7 +232,7 @@ class RequestTest < Test::Unit::TestCase
assert_equal "/some/path", @request.request_uri
assert_equal "/some/path", @request.path
end
def test_host_with_port
@request.host = "rubyonrails.org"
@ -262,5 +278,40 @@ class RequestTest < Test::Unit::TestCase
@request.env['HTTP_X_FORWARDED_PROTO'] = 'https'
assert @request.ssl?
end
def test_symbolized_request_methods
[:get, :post, :put, :delete].each do |method|
set_request_method_to method
assert_equal method, @request.method
end
end
def test_allow_method_hacking_on_post
set_request_method_to :post
[:get, :put, :delete].each do |method|
@request.instance_eval { @parameters = { :_method => method } ; @request_method = nil }
assert_equal method, @request.method
end
end
def test_restrict_method_hacking
@request.instance_eval { @parameters = { :_method => 'put' } }
[:get, :put, :delete].each do |method|
set_request_method_to method
assert_equal method, @request.method
end
end
def test_head_masquarading_as_get
set_request_method_to :head
assert_equal :get, @request.method
assert @request.get?
assert @request.head?
end
protected
def set_request_method_to(method)
@request.env['REQUEST_METHOD'] = method.to_s.upcase
@request.instance_eval { @request_method = nil }
end
end

File diff suppressed because it is too large Load diff

View file

@ -63,6 +63,14 @@ class SendFileTest < Test::Unit::TestCase
assert_equal file_data, response.body
end
def test_headers_after_send_shouldnt_include_charset
response = process('data')
assert_equal "application/octet-stream", response.headers["Content-Type"]
response = process('file')
assert_equal "application/octet-stream", response.headers["Content-Type"]
end
# Test that send_file_headers! is setting the correct HTTP headers.
def test_send_file_headers!
options = {
@ -97,7 +105,7 @@ class SendFileTest < Test::Unit::TestCase
define_method "test_send_#{method}_status" do
@controller.options = { :stream => false, :status => 500 }
assert_nothing_raised { assert_not_nil process(method) }
assert_equal '500', @controller.headers['Status']
assert_equal '500 Internal Server Error', @controller.headers['Status']
end
define_method "test_default_send_#{method}_status" do

View file

@ -44,6 +44,49 @@ class SessionManagementTest < Test::Unit::TestCase
end
end
class AssociationCachingTestController < ActionController::Base
class ObjectWithAssociationCache
def initialize
@cached_associations = false
end
def fetch_associations
@cached_associations = true
end
def clear_association_cache
@cached_associations = false
end
def has_cached_associations?
@cached_associations
end
end
def show
session[:object] = ObjectWithAssociationCache.new
session[:object].fetch_associations
if session[:object].has_cached_associations?
render :text => "has cached associations"
else
render :text => "does not have cached associations"
end
end
def tell
if session[:object]
if session[:object].has_cached_associations?
render :text => "has cached associations"
else
render :text => "does not have cached associations"
end
else
render :text => "there is no object"
end
end
end
def setup
@request, @response = ActionController::TestRequest.new,
ActionController::TestResponse.new
@ -91,4 +134,12 @@ class SessionManagementTest < Test::Unit::TestCase
assert_equal CGI::Session::ActiveRecordStore, ActionController::Base.session_store
end
end
def test_process_cleanup_with_session_management_support
@controller = AssociationCachingTestController.new
get :show
assert_equal "has cached associations", @response.body
get :tell
assert_equal "does not have cached associations", @response.body
end
end

View file

@ -8,6 +8,12 @@ class TestTest < Test::Unit::TestCase
render :text => 'ignore me'
end
def set_session
session['string'] = 'A wonder'
session[:symbol] = 'it works'
render :text => 'Success'
end
def render_raw_post
raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank?
render :text => request.raw_post
@ -15,8 +21,8 @@ class TestTest < Test::Unit::TestCase
def test_params
render :text => params.inspect
end
end
def test_uri
render :text => request.request_uri
end
@ -41,7 +47,7 @@ class TestTest < Test::Unit::TestCase
</html>
HTML
end
def test_only_one_param
render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
end
@ -49,7 +55,7 @@ HTML
def test_remote_addr
render :text => (request.remote_addr || "not specified")
end
def test_file_upload
render :text => params[:file].size
end
@ -58,8 +64,20 @@ HTML
redirect_to :generate_url, :id => 5
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
headers['Location'] = 'created resource'
head :created
end
private
def rescue_action(e)
raise e
end
@ -74,6 +92,7 @@ HTML
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionController::Routing::Routes.reload
ActionController::Routing.use_controllers! %w(content admin/user test_test/test)
end
def teardown
@ -91,13 +110,21 @@ HTML
def test_process_without_flash
process :set_flash
assert_equal '><', flash['test']
end
end
def test_process_with_flash
process :set_flash, nil, nil, { "test" => "value" }
assert_equal '>value<', flash['test']
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_request_uri_with_no_params
process :test_uri
assert_equal "/test_test/test/test_uri", @response.body
@ -112,12 +139,12 @@ HTML
@request.set_REQUEST_URI "/explicit/uri"
process :test_uri, :id => 7
assert_equal "/explicit/uri", @response.body
end
def test_multiple_calls
end
def test_multiple_calls
process :test_only_one_param, :left => true
assert_equal "OK", @response.body
process :test_only_one_param, :right => true
process :test_only_one_param, :right => true
assert_equal "OK", @response.body
end
@ -207,6 +234,8 @@ HTML
# 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
@ -233,7 +262,7 @@ HTML
process :test_html_output
# there is a tag containing only one child with an id of 'foo'
assert_tag :children => { :count => 1,
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" } }
@ -243,11 +272,11 @@ HTML
process :test_html_output
# the output contains the string "Name"
assert_tag :content => "Name"
assert_tag :content => /Name/
# the output does not contain the string "test"
assert_no_tag :content => "test"
assert_no_tag :content => /test/
end
def test_assert_tag_multiple
process :test_html_output
@ -267,7 +296,7 @@ HTML
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,
@ -281,8 +310,29 @@ HTML
:only => { :tag => "img" } } } }
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
@ -310,11 +360,11 @@ HTML
def test_array_path_parameter_handled_properly
with_routing do |set|
set.draw do
set.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params'
set.connect ':controller/:action/:id'
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
@ -333,13 +383,13 @@ HTML
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
@ -380,32 +430,80 @@ HTML
end
end
end
FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
def test_test_uploaded_file
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
content_type = 'image/png'
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 File.read(path), file.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_assert_redirected_to_symbol
get :redirect_to_symbol
assert_redirected_to :generate_url
with_foo_routing do |set|
assert_deprecated(/generate_url.*redirect_to/) do
get :redirect_to_symbol
end
assert_response :redirect
assert_redirected_to :generate_url
end
end
def test_assert_follow_redirect_to_same_controller
with_foo_routing do |set|
get :redirect_to_same_controller
assert_response :redirect
assert_redirected_to :controller => 'test_test/test', :action => 'test_uri', :id => 5
assert_nothing_raised { follow_redirect }
end
end
def test_assert_follow_redirect_to_different_controller
with_foo_routing do |set|
get :redirect_to_different_controller
assert_response :redirect
assert_redirected_to :controller => 'fail', :id => 5
assert_raise(RuntimeError) { follow_redirect }
end
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(Test::Unit::AssertionFailedError) do
assert_redirected_to 'created resource'
end
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

View file

@ -6,23 +6,6 @@ class UrlRewriterTests < Test::Unit::TestCase
@params = {}
@rewriter = ActionController::UrlRewriter.new(@request, @params)
end
def test_simple_build_query_string
assert_query_equal '?x=1&y=2', @rewriter.send(:build_query_string, :x => '1', :y => '2')
end
def test_convert_ints_build_query_string
assert_query_equal '?x=1&y=2', @rewriter.send(:build_query_string, :x => 1, :y => 2)
end
def test_escape_spaces_build_query_string
assert_query_equal '?x=hello+world&y=goodbye+world', @rewriter.send(:build_query_string, :x => 'hello world', :y => 'goodbye world')
end
def test_expand_array_build_query_string
assert_query_equal '?x[]=1&x[]=2', @rewriter.send(:build_query_string, :x => [1, 2])
end
def test_escape_spaces_build_query_string_selected_keys
assert_query_equal '?x=hello+world', @rewriter.send(:build_query_string, {:x => 'hello world', :y => 'goodbye world'}, [:x])
end
def test_overwrite_params
@params[:controller] = 'hi'
@ -44,3 +27,89 @@ class UrlRewriterTests < Test::Unit::TestCase
assert_equal(split_query_string(q1), split_query_string(q2))
end
end
class UrlWriterTests < Test::Unit::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_raises RuntimeError do
W.new.url_for :controller => 'c', :action => 'a', :id => 'i'
end
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_named_route
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 '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'))
ensure
ActionController::Routing::Routes.load!
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))
ensure
ActionController::Routing::Routes.load!
end
end

View file

@ -3,13 +3,14 @@ require File.dirname(__FILE__) + '/../abstract_unit'
class VerificationTest < Test::Unit::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" },
:add_flash => { :notice => "prereqs failed" },
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_in_session, :session => "one",
@ -31,46 +32,46 @@ class VerificationTest < Test::Unit::TestCase
verify :only => :two_redirects, :method => :post,
:redirect_to => { :action => "unguarded" }
verify :only => :must_be_post, :method => :post, :render => { :status => 500, :text => "Must be post"}
verify :only => :must_be_post, :method => :post, :render => { :status => 405, :text => "Must be post" }, :add_headers => { "Allow" => "POST" }
def guarded_one
render :text => "#{@params["one"]}"
render :text => "#{params[:one]}"
end
def guarded_with_flash
render :text => "#{@params["one"]}"
render :text => "#{params[:one]}"
end
def guarded_two
render :text => "#{@params["one"]}:#{@params["two"]}"
render :text => "#{params[:one]}:#{params[:two]}"
end
def guarded_in_session
render :text => "#{@session["one"]}"
render :text => "#{session["one"]}"
end
def multi_one
render :text => "#{@session["one"]}:#{@session["two"]}"
render :text => "#{session["one"]}:#{session["two"]}"
end
def multi_two
render :text => "#{@session["two"]}:#{@session["one"]}"
render :text => "#{session["two"]}:#{session["one"]}"
end
def guarded_by_method
render :text => "#{@request.method}"
render :text => "#{request.method}"
end
def guarded_by_xhr
render :text => "#{@request.xhr?}"
render :text => "#{request.xhr?}"
end
def guarded_by_not_xhr
render :text => "#{@request.xhr?}"
render :text => "#{request.xhr?}"
end
def unguarded
render :text => "#{@params["one"]}"
render :text => "#{params[:one]}"
end
def two_redirects
@ -103,18 +104,19 @@ class VerificationTest < Test::Unit::TestCase
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
assert flash.empty?
end
def test_guarded_with_flash_without_prereqs
get :guarded_with_flash
assert_redirected_to :action => "unguarded"
assert_flash_equal "prereqs failed", "notice"
assert_equal "prereqs failed", flash[:notice]
end
def test_guarded_two_with_prereqs
@ -212,13 +214,13 @@ class VerificationTest < Test::Unit::TestCase
assert_equal "Was a post!", @response.body
end
def test_guarded_post_and_calls_render_fails
def test_guarded_post_and_calls_render_fails_and_sets_allow_header
get :must_be_post
assert_response 500
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

View file

@ -148,13 +148,6 @@ class WebServiceTest < Test::Unit::TestCase
assert_equal %(<foo "bar's" & friends>), @controller.params[:data]
end
def test_dasherized_keys_as_yaml
ActionController::Base.param_parsers[Mime::YAML] = :yaml
process('POST', 'application/x-yaml', "---\nfirst-key:\n sub-key: ...\n", true)
assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body
assert_equal "...", @controller.params[:first_key][:sub_key]
end
def test_typecast_as_yaml
ActionController::Base.param_parsers[Mime::YAML] = :yaml
process('POST', 'application/x-yaml', <<-YAML)