Checkout of Instiki Trunk 1/21/2007.

This commit is contained in:
Jacques Distler 2007-01-22 07:43:50 -06:00
commit 69b62b6f33
1138 changed files with 139586 additions and 0 deletions

View file

@ -0,0 +1,493 @@
require File.dirname(__FILE__) + '/../abstract_unit'
# a controller class to facilitate the tests
class ActionPackAssertionsController < ActionController::Base
# this does absolutely nothing
def nothing() render_text ""; 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
def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end
def redirect_to_controller() redirect_to :controller => "elsewhere", :action => "flash_me"; end
def redirect_to_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
# a 500
def response500() render_text "", "500 Sorry"; end
# a fictional 599
def response599() render_text "", "599 Whoah!"; end
# putting stuff in the flash
def flash_me
flash['hello'] = 'my name is inigo montoya...'
render_text "Inconceivable!"
end
# we have a flash, but nothing is in it
def flash_me_naked
flash.clear
render_text "wow!"
end
# assign some template instance variables
def assign_this
@howdy = "ho"
render :inline => "Mr. Henke"
end
def render_based_on_parameters
render_text "Mr. #{@params["name"]}"
end
def render_url
render_text "<div>#{url_for(:action => 'flash_me', :only_path => true)}</div>"
end
# puts something in the session
def session_stuffing
session['xmas'] = 'turkey'
render_text "ho ho ho"
end
# raises exception on get requests
def raise_on_get
raise "get" if @request.get?
render_text "request method: #{@request.env['REQUEST_METHOD']}"
end
# raises exception on post requests
def raise_on_post
raise "post" if @request.post?
render_text "request method: #{@request.env['REQUEST_METHOD']}"
end
def get_valid_record
@record = Class.new do
def valid?
true
end
def errors
Class.new do
def full_messages; []; end
end.new
end
end.new
render :nothing => true
end
def get_invalid_record
@record = Class.new do
def valid?
false
end
def errors
Class.new do
def full_messages; ['...stuff...']; end
end.new
end
end.new
render :nothing => true
end
# 911
def rescue_action(e) raise; end
end
module Admin
class InnerModuleController < ActionController::Base
def redirect_to_absolute_controller
redirect_to :controller => '/content'
end
def redirect_to_fellow_controller
redirect_to :controller => 'user'
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
# 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
def setup
@controller = ActionPackAssertionsController.new
@request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
end
# -- assertion-based testing ------------------------------------------------
def test_assert_tag_and_url_for
get :render_url
assert_tag :content => "/action_pack_assertions/flash_me"
end
# test the 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'
end
# test the get method, make sure the request really was a get
def test_get
assert_raise(RuntimeError) { get :raise_on_get }
get :raise_on_post
assert_equal @response.body, 'request method: GET'
end
# test the get method, make sure the request really was a get
def test_post
assert_raise(RuntimeError) { post :raise_on_post }
post :raise_on_get
assert_equal @response.body, 'request method: POST'
end
# the following test fails because the request_method is now cached on the request instance
# test the get/post switch within one test action
# def test_get_post_switch
# post :raise_on_get
# assert_equal @response.body, 'request method: POST'
# get :raise_on_post
# assert_equal @response.body, 'request method: GET'
# post :raise_on_get
# assert_equal @response.body, 'request method: POST'
# get :raise_on_post
# assert_equal @response.body, 'request method: GET'
# end
# test the assertion of goodies in the template
def test_assert_template_has
process :assign_this
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'
end
# test the redirection assertions
def test_assert_redirect
process :redirect_internal
assert_redirect
end
# test the redirect url string
def test_assert_redirect_url
process :redirect_external
assert_redirect_url 'http://www.rubyonrails.org'
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'
end
# test the redirection pattern matching on a pattern
def test_assert_redirect_url_match_pattern
process :redirect_external
assert_redirect_url_match /ruby/
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'
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'
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'
end
# test the assert_rendered_file
def test_assert_rendered_file
process :hello_world
assert_rendered_file 'test/hello_world'
assert_rendered_file 'hello_world'
end
# test the assert_success assertion
def test_assert_success
process :nothing
assert_success
assert_rendered_file
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 !@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
end
# check the empty flashing
def test_flash_me_naked
process :flash_me_naked
assert !@response.has_flash?
assert !@response.has_flash_with_contents?
end
# check if we have flash objects
def test_flash_haves
process :flash_me
assert @response.has_flash?
assert @response.has_flash_with_contents?
assert @response.has_flash_object?('hello')
end
# ensure we don't have flash objects
def test_flash_have_nots
process :nothing
assert !@response.has_flash?
assert !@response.has_flash_with_contents?
assert_nil @response.flash['hello']
end
# 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'
end
# 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 @response.rendered_with_file?
assert 'hello_world', @response.rendered_file
end
# check the redirection location
def test_redirection_location
process :redirect_internal
assert_equal 'http://test.host/nothing', @response.redirect_url
process :redirect_external
assert_equal 'http://www.rubyonrails.org', @response.redirect_url
process :nothing
assert_nil @response.redirect_url
end
# check server errors
def test_server_error_response_code
process :response500
assert @response.server_error?
process :response599
assert @response.server_error?
process :response404
assert !@response.server_error?
end
# check a 404 response code
def test_missing_response_code
process :response404
assert @response.missing?
end
# check to see if our redirection matches a pattern
def test_redirect_url_match
process :redirect_external
assert @response.redirect?
assert @response.redirect_url_match?("rubyonrails")
assert @response.redirect_url_match?(/rubyonrails/)
assert !@response.redirect_url_match?("phpoffrails")
assert !@response.redirect_url_match?(/perloffrails/)
end
# check for a redirection
def test_redirection
process :redirect_internal
assert @response.redirect?
process :redirect_external
assert @response.redirect?
process :nothing
assert !@response.redirect?
end
# check a successful response code
def test_successful_response_code
process :nothing
assert @response.success?
end
# a basic check to make sure we have a TestResponse object
def test_has_response
process :nothing
assert_kind_of ActionController::TestResponse, @response
end
def test_render_based_on_parameters
process :render_based_on_parameters, "name" => "David"
assert_equal "Mr. David", @response.body
end
def test_assert_template_xpath_match_no_matches
process :hello_xml_world
assert_raises Test::Unit::AssertionFailedError do
assert_template_xpath_match('/no/such/node/in/document')
end
end
def test_simple_one_element_xpath_match
process :hello_xml_world
assert_template_xpath_match('//title', "Hello World")
end
def test_array_of_elements_in_xpath_match
process :hello_xml_world
assert_template_xpath_match('//p', %w( abes monks wiseguys ))
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"
assert_raises(RuntimeError, "Can't follow redirects outside of current controller (elsewhere)") { follow_redirect }
end
def test_redirected_to_url_leadling_slash
process :redirect_to_path
assert_redirected_to '/some/path'
end
def test_redirected_to_url_no_leadling_slash
process :redirect_to_path
assert_redirected_to 'some/path'
end
def test_redirected_to_url_full_url
process :redirect_to_path
assert_redirected_to 'http://test.host/some/path'
end
def test_redirected_to_with_nested_controller
@controller = Admin::InnerModuleController.new
get :redirect_to_absolute_controller
assert_redirected_to :controller => 'content'
get :redirect_to_fellow_controller
assert_redirected_to :controller => 'admin/user'
end
def test_assert_valid
get :get_valid_record
assert_valid assigns('record')
end
def test_assert_valid_failing
get :get_invalid_record
begin
assert_valid assigns('record')
assert false
rescue Test::Unit::AssertionFailedError => e
end
end
end
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'])
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'])
end
end

View file

@ -0,0 +1,49 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class Address
def Address.count(conditions = nil, join = nil)
nil
end
def Address.find_all(arg1, arg2, arg3, arg4)
[]
end
def self.find(*args)
[]
end
end
class AddressesTestController < ActionController::Base
scaffold :address
def self.controller_name; "addresses"; end
def self.controller_path; "addresses"; end
end
AddressesTestController.template_root = File.dirname(__FILE__) + "/../fixtures/"
class AddressesTest < Test::Unit::TestCase
def setup
@controller = AddressesTestController.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_list
get :list
assert_equal "We only need to get this far!", @response.body.chomp
end
end

View file

@ -0,0 +1,66 @@
require File.dirname(__FILE__) + '/../abstract_unit'
require 'test/unit'
require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
# Provide some controller to run the tests on.
module Submodule
class ContainedEmptyController < ActionController::Base
end
class ContainedNonEmptyController < ActionController::Base
def public_action
end
hide_action :hidden_action
def hidden_action
end
def another_hidden_action
end
hide_action :another_hidden_action
end
class SubclassedController < ContainedNonEmptyController
hide_action :public_action # Hiding it here should not affect the superclass.
end
end
class EmptyController < ActionController::Base
include ActionController::Caching
end
class NonEmptyController < ActionController::Base
def public_action
end
hide_action :hidden_action
def hidden_action
end
end
class ControllerClassTests < Test::Unit::TestCase
def test_controller_path
assert_equal 'empty', EmptyController.controller_path
assert_equal 'submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
end
def test_controller_name
assert_equal 'empty', EmptyController.controller_name
assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
end
end
class ControllerInstanceTests < Test::Unit::TestCase
def setup
@empty = EmptyController.new
@contained = Submodule::ContainedEmptyController.new
@empty_controllers = [@empty, @contained, Submodule::SubclassedController.new]
@non_empty_controllers = [NonEmptyController.new,
Submodule::ContainedNonEmptyController.new]
end
def test_action_methods
@empty_controllers.each do |c|
assert_equal Set.new, c.send(:action_methods), "#{c.class.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!"
end
end
end

View file

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

View file

@ -0,0 +1,74 @@
require 'fileutils'
require File.dirname(__FILE__) + '/../abstract_unit'
class TestLogDevice < Logger::LogDevice
attr :last_message, true
def initialize
@last_message=String.new
end
def write(message)
@last_message << message
end
def clear
@last_message = String.new
end
end
#setup our really sophisticated logger
TestLog = TestLogDevice.new
RAILS_DEFAULT_LOGGER = Logger.new(TestLog)
ActionController::Base.logger = RAILS_DEFAULT_LOGGER
def use_store
#generate a random key to ensure the cache is always in a different location
RANDOM_KEY = rand(99999999).to_s
FILE_STORE_PATH = File.dirname(__FILE__) + '/../temp/' + RANDOM_KEY
ActionController::Base.perform_caching = true
ActionController::Base.fragment_cache_store = :file_store, FILE_STORE_PATH
end
class TestController < ActionController::Base
caches_action :render_to_cache, :index
def render_to_cache
render_text "Render Cached"
end
alias :index :render_to_cache
end
class FileStoreTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = TestController.new
@request.host = "hostname.com"
end
def teardown
FileUtils.rm_rf(FILE_STORE_PATH)
end
def test_render_cached
assert_fragment_cached { get :render_to_cache }
assert_fragment_hit { get :render_to_cache }
end
private
def assert_fragment_cached
yield
assert(TestLog.last_message.include?("Cached fragment:"), "--ERROR-- FileStore write failed ----")
assert(!TestLog.last_message.include?("Couldn't create cache directory:"), "--ERROR-- FileStore create directory failed ----")
TestLog.clear
end
def assert_fragment_hit
yield
assert(TestLog.last_message.include?("Fragment read:"), "--ERROR-- Fragment not found in FileStore ----")
assert(!TestLog.last_message.include?("Cached fragment:"), "--ERROR-- Did cache ----")
TestLog.clear
end
end

View file

@ -0,0 +1,80 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class CaptureController < ActionController::Base
def self.controller_name; "test"; end
def self.controller_path; "test"; end
def content_for
render :layout => "talk_from_action"
end
def 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
def rescue_action(e) raise end
end
CaptureController.template_root = File.dirname(__FILE__) + "/../fixtures/"
class CaptureTest < Test::Unit::TestCase
def setup
@controller = CaptureController.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_simple_capture
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_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';",
@response.body.strip
)
end
private
def expected_content_for_output
"<title>Putting stuff in the title!</title>\n\nGreat stuff!"
end
end

View file

@ -0,0 +1,363 @@
require File.dirname(__FILE__) + '/../abstract_unit'
require 'action_controller/cgi_process'
require 'action_controller/cgi_ext/cgi_ext'
require 'stringio'
class CGITest < Test::Unit::TestCase
def setup
@query_string = "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
@query_string_with_nil = "action=create_customer&full_name="
@query_string_with_array = "action=create_customer&selected[]=1&selected[]=2&selected[]=3"
@query_string_with_amps = "action=create_customer&name=Don%27t+%26+Does"
@query_string_with_multiple_of_same_name =
"action=update_order&full_name=Lau%20Taarnskov&products=4&products=2&products=3"
@query_string_with_many_equal = "action=create_customer&full_name=abc=def=ghi"
@query_string_without_equal = "action"
@query_string_with_many_ampersands =
"&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
end
def test_query_string
assert_equal(
{ "action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"},
CGIMethods.parse_query_parameters(@query_string)
)
end
def test_deep_query_string
assert_equal({'x' => {'y' => {'z' => '10'}}}, 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_query_string_with_nil
assert_equal(
{ "action" => "create_customer", "full_name" => nil},
CGIMethods.parse_query_parameters(@query_string_with_nil)
)
end
def test_query_string_with_array
assert_equal(
{ "action" => "create_customer", "selected" => ["1", "2", "3"]},
CGIMethods.parse_query_parameters(@query_string_with_array)
)
end
def test_query_string_with_amps
assert_equal(
{ "action" => "create_customer", "name" => "Don't & Does"},
CGIMethods.parse_query_parameters(@query_string_with_amps)
)
end
def test_query_string_with_many_equal
assert_equal(
{ "action" => "create_customer", "full_name" => "abc=def=ghi"},
CGIMethods.parse_query_parameters(@query_string_with_many_equal)
)
end
def test_query_string_without_equal
assert_equal(
{ "action" => nil },
CGIMethods.parse_query_parameters(@query_string_without_equal)
)
end
def test_query_string_with_many_ampersands
assert_equal(
{ "action" => "create_customer", "full_name" => "David Heinemeier Hansson"},
CGIMethods.parse_query_parameters(@query_string_with_many_ampersands)
)
end
def test_parse_params
input = {
"customers[boston][first][name]" => [ "David" ],
"customers[boston][first][url]" => [ "http://David" ],
"customers[boston][second][name]" => [ "Allan" ],
"customers[boston][second][url]" => [ "http://Allan" ],
"something_else" => [ "blah" ],
"something_nil" => [ nil ],
"something_empty" => [ "" ],
"products[first]" => [ "Apple Computer" ],
"products[second]" => [ "Pc" ]
}
expected_output = {
"customers" => {
"boston" => {
"first" => {
"name" => "David",
"url" => "http://David"
},
"second" => {
"name" => "Allan",
"url" => "http://Allan"
}
}
},
"something_else" => "blah",
"something_empty" => "",
"something_nil" => "",
"products" => {
"first" => "Apple Computer",
"second" => "Pc"
}
}
assert_equal expected_output, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_from_multipart_upload
mockup = Struct.new(:content_type, :original_filename)
file = mockup.new('img/jpeg', 'foo.jpg')
ie_file = mockup.new('img/jpeg', 'c:\\Documents and Settings\\foo\\Desktop\\bar.jpg')
input = {
"something" => [ StringIO.new("") ],
"array_of_stringios" => [[ StringIO.new("One"), StringIO.new("Two") ]],
"mixed_types_array" => [[ StringIO.new("Three"), "NotStringIO" ]],
"mixed_types_as_checkboxes[strings][nested]" => [[ file, "String", StringIO.new("StringIO")]],
"ie_mixed_types_as_checkboxes[strings][nested]" => [[ ie_file, "String", StringIO.new("StringIO")]],
"products[string]" => [ StringIO.new("Apple Computer") ],
"products[file]" => [ file ],
"ie_products[string]" => [ StringIO.new("Microsoft") ],
"ie_products[file]" => [ ie_file ]
}
expected_output = {
"something" => "",
"array_of_stringios" => ["One", "Two"],
"mixed_types_array" => [ "Three", "NotStringIO" ],
"mixed_types_as_checkboxes" => {
"strings" => {
"nested" => [ file, "String", "StringIO" ]
},
},
"ie_mixed_types_as_checkboxes" => {
"strings" => {
"nested" => [ ie_file, "String", "StringIO" ]
},
},
"products" => {
"string" => "Apple Computer",
"file" => file
},
"ie_products" => {
"string" => "Microsoft",
"file" => ie_file
}
}
params = CGIMethods.parse_request_parameters(input)
assert_equal expected_output, params
# Lone filenames are preserved.
assert_equal 'foo.jpg', params['mixed_types_as_checkboxes']['strings']['nested'].first.original_filename
assert_equal 'foo.jpg', params['products']['file'].original_filename
# But full Windows paths are reduced to their basename.
assert_equal 'bar.jpg', params['ie_mixed_types_as_checkboxes']['strings']['nested'].first.original_filename
assert_equal 'bar.jpg', params['ie_products']['file'].original_filename
end
def test_parse_params_with_file
input = {
"customers[boston][first][name]" => [ "David" ],
"something_else" => [ "blah" ],
"logo" => [ File.new(File.dirname(__FILE__) + "/cgi_test.rb").path ]
}
expected_output = {
"customers" => {
"boston" => {
"first" => {
"name" => "David"
}
}
},
"something_else" => "blah",
"logo" => File.new(File.dirname(__FILE__) + "/cgi_test.rb").path,
}
assert_equal expected_output, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_array
input = { "selected[]" => [ "1", "2", "3" ] }
expected_output = { "selected" => [ "1", "2", "3" ] }
assert_equal expected_output, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_non_alphanumeric_name
input = { "a/b[c]" => %w(d) }
expected = { "a/b" => { "c" => "d" }}
assert_equal expected, CGIMethods.parse_request_parameters(input)
end
def test_parse_params_with_single_brackets_in_middle
input = { "a/b[c]d" => %w(e) }
expected = { "a/b[c]d" => "e" }
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" }}
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"] }}
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"] }}}
assert_equal expected, CGIMethods.parse_request_parameters(input)
end
end
class MultipartCGITest < Test::Unit::TestCase
FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart'
def setup
ENV['REQUEST_METHOD'] = 'POST'
ENV['CONTENT_LENGTH'] = '0'
ENV['CONTENT_TYPE'] = 'multipart/form-data, boundary=AaB03x'
end
def test_single_parameter
params = process('single_parameter')
assert_equal({ 'foo' => 'bar' }, params)
end
def test_text_file
params = process('text_file')
assert_equal %w(file foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
assert_kind_of StringIO, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain\r", file.content_type
assert_equal 'contents', file.read
end
def test_large_text_file
params = process('large_text_file')
assert_equal %w(file foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
assert_kind_of Tempfile, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain\r", file.content_type
assert ('a' * 20480) == file.read
end
def test_binary_file
params = process('binary_file')
assert_equal %w(file flowers foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
assert_kind_of StringIO, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain\r", file.content_type
assert_equal 'contents', file.read
file = params['flowers']
assert_kind_of StringIO, file
assert_equal 'flowers.jpg', file.original_filename
assert_equal "image/jpeg\r", file.content_type
assert_equal 19512, file.size
#assert_equal File.read(File.dirname(__FILE__) + '/../../../activerecord/test/fixtures/flowers.jpg'), file.read
end
def test_mixed_files
params = process('mixed_files')
assert_equal %w(files foo), params.keys.sort
assert_equal 'bar', params['foo']
# Ruby CGI doesn't handle multipart/mixed for us.
assert_kind_of StringIO, params['files']
assert_equal 19756, params['files'].size
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
end
ensure
$stdin = old_stdin
end
end
class CGIRequestTest < Test::Unit::TestCase
def setup
@request_hash = {"HTTP_MAX_FORWARDS"=>"10", "SERVER_NAME"=>"glu.ttono.us:8007", "FCGI_ROLE"=>"RESPONDER", "HTTP_X_FORWARDED_HOST"=>"glu.ttono.us", "HTTP_ACCEPT_ENCODING"=>"gzip, deflate", "HTTP_USER_AGENT"=>"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/312.5.1 (KHTML, like Gecko) Safari/312.3.1", "PATH_INFO"=>"", "HTTP_ACCEPT_LANGUAGE"=>"en", "HTTP_HOST"=>"glu.ttono.us:8007", "SERVER_PROTOCOL"=>"HTTP/1.1", "REDIRECT_URI"=>"/dispatch.fcgi", "SCRIPT_NAME"=>"/dispatch.fcgi", "SERVER_ADDR"=>"207.7.108.53", "REMOTE_ADDR"=>"207.7.108.53", "SERVER_SOFTWARE"=>"lighttpd/1.4.5", "HTTP_COOKIE"=>"_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes", "HTTP_X_FORWARDED_SERVER"=>"glu.ttono.us", "REQUEST_URI"=>"/admin", "DOCUMENT_ROOT"=>"/home/kevinc/sites/typo/public", "SERVER_PORT"=>"8007", "QUERY_STRING"=>"", "REMOTE_PORT"=>"63137", "GATEWAY_INTERFACE"=>"CGI/1.1", "HTTP_X_FORWARDED_FOR"=>"65.88.180.234", "HTTP_ACCEPT"=>"*/*", "SCRIPT_FILENAME"=>"/home/kevinc/sites/typo/public/dispatch.fcgi", "REDIRECT_STATUS"=>"200", "REQUEST_METHOD"=>"GET"}
# cookie as returned by some Nokia phone browsers (no space after semicolon separator)
@alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace84796670c052c6ceb2451fb0f2;is_admin=yes"}
@fake_cgi = Struct.new(:env_table).new(@request_hash)
@request = ActionController::CgiRequest.new(@fake_cgi)
end
def test_proxy_request
assert_equal 'glu.ttono.us', @request.host_with_port
end
def test_http_host
@request_hash.delete "HTTP_X_FORWARDED_HOST"
@request_hash['HTTP_HOST'] = "rubyonrails.org:8080"
assert_equal "rubyonrails.org:8080", @request.host_with_port
@request_hash['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org"
assert_equal "www.secondhost.org", @request.host
end
def test_http_host_with_default_port_overrides_server_port
@request_hash.delete "HTTP_X_FORWARDED_HOST"
@request_hash['HTTP_HOST'] = "rubyonrails.org"
assert_equal "rubyonrails.org", @request.host_with_port
end
def test_host_with_port_defaults_to_server_name_if_no_host_headers
@request_hash.delete "HTTP_X_FORWARDED_HOST"
@request_hash.delete "HTTP_HOST"
assert_equal "glu.ttono.us:8007", @request.host_with_port
end
def test_host_with_port_falls_back_to_server_addr_if_necessary
@request_hash.delete "HTTP_X_FORWARDED_HOST"
@request_hash.delete "HTTP_HOST"
@request_hash.delete "SERVER_NAME"
assert_equal "207.7.108.53:8007", @request.host_with_port
end
def test_cookie_syntax_resilience
cookies = CGI::Cookie::parse(@request_hash["HTTP_COOKIE"]);
assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], cookies["_session_id"]
assert_equal ["yes"], cookies["is_admin"]
alt_cookies = CGI::Cookie::parse(@alt_cookie_fmt_request_hash["HTTP_COOKIE"]);
assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], alt_cookies["_session_id"]
assert_equal ["yes"], alt_cookies["is_admin"]
end
end

View file

@ -0,0 +1,129 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class CallerController < ActionController::Base
def calling_from_controller
render_component(:controller => "callee", :action => "being_called")
end
def calling_from_controller_with_params
render_component(:controller => "callee", :action => "being_called", :params => { "name" => "David" })
end
def calling_from_controller_with_different_status_code
render_component(:controller => "callee", :action => "blowing_up")
end
def calling_from_template
render_template "Ring, ring: <%= render_component(:controller => 'callee', :action => 'being_called') %>"
end
def internal_caller
render_template "Are you there? <%= render_component(:action => 'internal_callee') %>"
end
def internal_callee
render_text "Yes, ma'am"
end
def set_flash
render_component(:controller => "callee", :action => "set_flash")
end
def use_flash
render_component(:controller => "callee", :action => "use_flash")
end
def calling_redirected
render_component(:controller => "callee", :action => "redirected")
end
def calling_redirected_as_string
render_template "<%= render_component(:controller => 'callee', :action => 'redirected') %>"
end
def rescue_action(e) raise end
end
class CalleeController < ActionController::Base
def being_called
render_text "#{@params["name"] || "Lady"} of the House, speaking"
end
def blowing_up
render_text "It's game over, man, just game over, man!", "500 Internal Server Error"
end
def set_flash
flash[:notice] = 'My stoney baby'
render :text => 'flash is set'
end
def use_flash
render :text => flash[:notice] || 'no flash'
end
def redirected
redirect_to :controller => "callee", :action => "being_called"
end
def rescue_action(e) raise end
end
class ComponentsTest < Test::Unit::TestCase
def setup
@controller = CallerController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_calling_from_controller
get :calling_from_controller
assert_equal "Lady of the House, speaking", @response.body
end
def test_calling_from_controller_with_params
get :calling_from_controller_with_params
assert_equal "David of the House, speaking", @response.body
end
def test_calling_from_controller_with_different_status_code
get :calling_from_controller_with_different_status_code
assert_equal 500, @response.response_code
end
def test_calling_from_template
get :calling_from_template
assert_equal "Ring, ring: Lady of the House, speaking", @response.body
end
def test_internal_calling
get :internal_caller
assert_equal "Are you there? Yes, ma'am", @response.body
end
def test_flash
get :set_flash
assert_equal 'My stoney baby', flash[:notice]
get :use_flash
assert_equal 'My stoney baby', @response.body
get :use_flash
assert_equal 'no flash', @response.body
end
def test_component_redirect_redirects
get :calling_redirected
assert_redirected_to :action => "being_called"
end
def test_component_multiple_redirect_redirects
test_component_redirect_redirects
test_internal_calling
end
def test_component_as_string_redirect_renders_redirecte_action
get :calling_redirected_as_string
assert_equal "Lady of the House, speaking", @response.body
end
end

View file

@ -0,0 +1,80 @@
require File.dirname(__FILE__) + '/../abstract_unit'
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"
end
def rescue_action(e) raise end
end
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.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"]
end
def test_setting_cookie
@request.action = "authenticate"
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], process_request.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"]
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"]
end
def test_multiple_cookies
@request.action = "set_multiple_cookies"
assert_equal 2, process_request.headers["cookie"].size
end
def test_setting_test_cookie
@request.action = "access_frozen_cookies"
assert_nothing_raised { process_request }
end
private
def process_request
TestController.process(@request, @response)
end
end

View file

@ -0,0 +1,41 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class CustomHandler
def initialize( view )
@view = view
end
def render( template, local_assigns )
[ template,
local_assigns,
@view ]
end
end
class CustomHandlerTest < Test::Unit::TestCase
def setup
ActionView::Base.register_template_handler "foo", CustomHandler
ActionView::Base.register_template_handler :foo2, CustomHandler
@view = ActionView::Base.new
end
def test_custom_render
result = @view.render_template( "foo", "hello <%= one %>", nil, :one => "two" )
assert_equal(
[ "hello <%= one %>", { :one => "two" }, @view ],
result )
end
def test_custom_render2
result = @view.render_template( "foo2", "hello <%= one %>", nil, :one => "two" )
assert_equal(
[ "hello <%= one %>", { :one => "two" }, @view ],
result )
end
def test_unhandled_extension
# uses the ERb handler by default if the extension isn't recognized
result = @view.render_template( "bar", "hello <%= one %>", nil, :one => "two" )
assert_equal "hello two", result
end
end

View file

@ -0,0 +1,17 @@
class << Object; alias_method :const_available?, :const_defined?; end
class ContentController < Class.new(ActionController::Base)
end
class NotAController
end
module Admin
class << self; alias_method :const_available?, :const_defined?; end
SomeConstant = 10
class UserController < Class.new(ActionController::Base); end
class NewsFeedController < Class.new(ActionController::Base); end
end
ActionController::Routing::Routes.draw do |map|
map.route_one 'route_one', :controller => 'elsewhere', :action => 'flash_me'
map.connect ':controller/:action/:id'
end

View file

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

View file

@ -0,0 +1,410 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class FilterTest < Test::Unit::TestCase
class TestController < ActionController::Base
before_filter :ensure_login
after_filter :clean_up
def show
render :inline => "ran action"
end
private
def ensure_login
@ran_filter ||= []
@ran_filter << "ensure_login"
end
def clean_up
@ran_after_filter ||= []
@ran_after_filter << "clean_up"
end
end
class RenderingController < ActionController::Base
before_filter :render_something_else
def show
@ran_action = true
render :inline => "ran action"
end
private
def render_something_else
render :inline => "something else"
end
end
class ConditionalFilterController < ActionController::Base
def show
render :inline => "ran action"
end
def another_action
render :inline => "ran action"
end
def show_without_filter
render :inline => "ran action without filter"
end
private
def ensure_login
@ran_filter ||= []
@ran_filter << "ensure_login"
end
def clean_up_tmp
@ran_filter ||= []
@ran_filter << "clean_up_tmp"
end
def rescue_action(e) raise(e) end
end
class ConditionalCollectionFilterController < ConditionalFilterController
before_filter :ensure_login, :except => [ :show_without_filter, :another_action ]
end
class OnlyConditionSymController < ConditionalFilterController
before_filter :ensure_login, :only => :show
end
class ExceptConditionSymController < ConditionalFilterController
before_filter :ensure_login, :except => :show_without_filter
end
class BeforeAndAfterConditionController < ConditionalFilterController
before_filter :ensure_login, :only => :show
after_filter :clean_up_tmp, :only => :show
end
class OnlyConditionProcController < ConditionalFilterController
before_filter(:only => :show) {|c| c.assigns["ran_proc_filter"] = true }
end
class ExceptConditionProcController < ConditionalFilterController
before_filter(:except => :show_without_filter) {|c| c.assigns["ran_proc_filter"] = true }
end
class ConditionalClassFilter
def self.filter(controller) controller.assigns["ran_class_filter"] = true end
end
class OnlyConditionClassController < ConditionalFilterController
before_filter ConditionalClassFilter, :only => :show
end
class ExceptConditionClassController < ConditionalFilterController
before_filter ConditionalClassFilter, :except => :show_without_filter
end
class AnomolousYetValidConditionController < ConditionalFilterController
before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.assigns["ran_proc_filter1"] = true }, :except => :show_without_filter) { |c| c.assigns["ran_proc_filter2"] = true}
end
class PrependingController < TestController
prepend_before_filter :wonderful_life
# skip_before_filter :fire_flash
private
def wonderful_life
@ran_filter ||= []
@ran_filter << "wonderful_life"
end
end
class ConditionalSkippingController < TestController
skip_before_filter :ensure_login, :only => [ :login ]
skip_after_filter :clean_up, :only => [ :login ]
before_filter :find_user, :only => [ :change_password ]
def login
render :inline => "ran action"
end
def change_password
render :inline => "ran action"
end
protected
def find_user
@ran_filter ||= []
@ran_filter << "find_user"
end
end
class ConditionalParentOfConditionalSkippingController < ConditionalFilterController
before_filter :conditional_in_parent, :only => [:show, :another_action]
after_filter :conditional_in_parent, :only => [:show, :another_action]
private
def conditional_in_parent
@ran_filter ||= []
@ran_filter << 'conditional_in_parent'
end
end
class ChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
skip_before_filter :conditional_in_parent, :only => :another_action
skip_after_filter :conditional_in_parent, :only => :another_action
end
class ProcController < PrependingController
before_filter(proc { |c| c.assigns["ran_proc_filter"] = true })
end
class ImplicitProcController < PrependingController
before_filter { |c| c.assigns["ran_proc_filter"] = true }
end
class AuditFilter
def self.filter(controller)
controller.assigns["was_audited"] = true
end
end
class AroundFilter
def before(controller)
@execution_log = "before"
controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log
controller.assigns["before_ran"] = true
end
def after(controller)
controller.assigns["execution_log"] = @execution_log + " and after"
controller.assigns["after_ran"] = true
controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log
end
end
class AppendedAroundFilter
def before(controller)
controller.class.execution_log << " before appended aroundfilter "
end
def after(controller)
controller.class.execution_log << " after appended aroundfilter "
end
end
class AuditController < ActionController::Base
before_filter(AuditFilter)
def show
render_text "hello"
end
end
class 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
class MixedFilterController < PrependingController
cattr_accessor :execution_log
def initialize
@@execution_log = ""
end
before_filter { |c| c.class.execution_log << " before procfilter " }
prepend_around_filter AroundFilter.new
after_filter { |c| c.class.execution_log << " after procfilter " }
append_around_filter AppendedAroundFilter.new
end
class MixedSpecializationController < ActionController::Base
class OutOfOrder < StandardError; end
before_filter :first
before_filter :second, :only => :foo
def foo
render_text 'foo'
end
def bar
render_text 'bar'
end
protected
def first
@first = true
end
def second
raise OutOfOrder unless @first
end
end
class DynamicDispatchController < ActionController::Base
before_filter :choose
%w(foo bar baz).each do |action|
define_method(action) { render :text => action }
end
private
def choose
self.action_name = params[:choose]
end
end
def test_added_filter_to_inheritance_graph
assert_equal [ :ensure_login ], TestController.before_filters
end
def test_base_class_in_isolation
assert_equal [ ], ActionController::Base.before_filters
end
def test_prepending_filter
assert_equal [ :wonderful_life, :ensure_login ], PrependingController.before_filters
end
def test_running_filters
assert_equal %w( wonderful_life ensure_login ), test_process(PrependingController).template.assigns["ran_filter"]
end
def test_running_filters_with_proc
assert test_process(ProcController).template.assigns["ran_proc_filter"]
end
def test_running_filters_with_implicit_proc
assert test_process(ImplicitProcController).template.assigns["ran_proc_filter"]
end
def test_running_filters_with_class
assert test_process(AuditController).template.assigns["was_audited"]
end
def test_running_anomolous_yet_valid_condition_filters
response = test_process(AnomolousYetValidConditionController)
assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
assert response.template.assigns["ran_class_filter"]
assert response.template.assigns["ran_proc_filter1"]
assert response.template.assigns["ran_proc_filter2"]
response = test_process(AnomolousYetValidConditionController, "show_without_filter")
assert_equal nil, response.template.assigns["ran_filter"]
assert !response.template.assigns["ran_class_filter"]
assert !response.template.assigns["ran_proc_filter1"]
assert !response.template.assigns["ran_proc_filter2"]
end
def test_running_collection_condition_filters
assert_equal %w( ensure_login ), test_process(ConditionalCollectionFilterController).template.assigns["ran_filter"]
assert_equal nil, test_process(ConditionalCollectionFilterController, "show_without_filter").template.assigns["ran_filter"]
assert_equal nil, test_process(ConditionalCollectionFilterController, "another_action").template.assigns["ran_filter"]
end
def test_running_only_condition_filters
assert_equal %w( ensure_login ), test_process(OnlyConditionSymController).template.assigns["ran_filter"]
assert_equal nil, test_process(OnlyConditionSymController, "show_without_filter").template.assigns["ran_filter"]
assert test_process(OnlyConditionProcController).template.assigns["ran_proc_filter"]
assert !test_process(OnlyConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
assert test_process(OnlyConditionClassController).template.assigns["ran_class_filter"]
assert !test_process(OnlyConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
end
def test_running_except_condition_filters
assert_equal %w( ensure_login ), test_process(ExceptConditionSymController).template.assigns["ran_filter"]
assert_equal nil, test_process(ExceptConditionSymController, "show_without_filter").template.assigns["ran_filter"]
assert test_process(ExceptConditionProcController).template.assigns["ran_proc_filter"]
assert !test_process(ExceptConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
assert test_process(ExceptConditionClassController).template.assigns["ran_class_filter"]
assert !test_process(ExceptConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
end
def test_running_before_and_after_condition_filters
assert_equal %w( ensure_login clean_up_tmp), test_process(BeforeAndAfterConditionController).template.assigns["ran_filter"]
assert_equal nil, test_process(BeforeAndAfterConditionController, "show_without_filter").template.assigns["ran_filter"]
end
def test_bad_filter
assert_raises(ActionController::ActionControllerError) {
test_process(BadFilterController)
}
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"]
end
def test_prepending_and_appending_around_filter
controller = test_process(MixedFilterController)
assert_equal " before aroundfilter before procfilter before appended aroundfilter " +
" after appended aroundfilter after aroundfilter after procfilter ",
MixedFilterController.execution_log
end
def test_rendering_breaks_filtering_chain
response = test_process(RenderingController)
assert_equal "something else", response.body
assert !response.template.assigns["ran_action"]
end
def test_filters_with_mixed_specialization_run_in_order
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'bar')
assert_equal 'bar', response.body
end
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'foo')
assert_equal 'foo', response.body
end
end
def test_dynamic_dispatch
%w(foo bar baz).each do |action|
request = ActionController::TestRequest.new
request.query_parameters[:choose] = action
response = DynamicDispatchController.process(request, ActionController::TestResponse.new)
assert_equal action, response.body
end
end
def test_conditional_skipping_of_filters
assert_nil test_process(ConditionalSkippingController, "login").template.assigns["ran_filter"]
assert_equal %w( ensure_login find_user ), test_process(ConditionalSkippingController, "change_password").template.assigns["ran_filter"]
assert_nil test_process(ConditionalSkippingController, "login").template.controller.instance_variable_get("@ran_after_filter")
assert_equal %w( clean_up ), test_process(ConditionalSkippingController, "change_password").template.controller.instance_variable_get("@ran_after_filter")
end
def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
assert_nil test_process(ChildOfConditionalParentController, 'another_action').template.assigns['ran_filter']
end
private
def test_process(controller, action = "show")
request = ActionController::TestRequest.new
request.action = action
controller.process(request, ActionController::TestResponse.new)
end
end

View file

@ -0,0 +1,85 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class FlashTest < Test::Unit::TestCase
class TestController < ActionController::Base
def set_flash
flash["that"] = "hello"
render :inline => "hello"
end
def set_flash_now
flash.now["that"] = "hello"
flash.now["foo"] ||= "bar"
flash.now["foo"] ||= "err"
@flashy = flash.now["that"]
@flash_copy = {}.update flash
render :inline => "hello"
end
def attempt_to_use_flash_now
@flash_copy = {}.update flash
@flashy = flash["that"]
render :inline => "hello"
end
def use_flash
@flash_copy = {}.update flash
@flashy = flash["that"]
render :inline => "hello"
end
def use_flash_and_keep_it
@flash_copy = {}.update flash
@flashy = flash["that"]
silence_warnings { keep_flash }
render :inline => "hello"
end
def rescue_action(e)
raise unless ActionController::MissingTemplate === e
end
end
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = TestController.new
end
def test_flash
get :set_flash
get :use_flash
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "hello", @response.template.assigns["flashy"]
get :use_flash
assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
end
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "hello", @response.template.assigns["flashy"]
get :use_flash
assert_equal "hello", @response.template.assigns["flash_copy"]["that"], "On second flash"
get :use_flash
assert_nil @response.template.assigns["flash_copy"]["that"], "On third flash"
end
def test_flash_now
get :set_flash_now
assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
assert_equal "bar" , @response.template.assigns["flash_copy"]["foo"]
assert_equal "hello", @response.template.assigns["flashy"]
get :attempt_to_use_flash_now
assert_nil @response.template.assigns["flash_copy"]["that"]
assert_nil @response.template.assigns["flash_copy"]["foo"]
assert_nil @response.template.assigns["flashy"]
end
end

View file

@ -0,0 +1,45 @@
require File.dirname(__FILE__) + '/../abstract_unit'
MemCache = Struct.new(:MemCache, :address) unless Object.const_defined?(:MemCache)
class FragmentCacheStoreSettingTest < Test::Unit::TestCase
def teardown
ActionController::Base.fragment_cache_store = ActionController::Caching::Fragments::MemoryStore.new
end
def test_file_fragment_cache_store
ActionController::Base.fragment_cache_store = :file_store, "/path/to/cache/directory"
assert_kind_of(
ActionController::Caching::Fragments::FileStore,
ActionController::Base.fragment_cache_store
)
assert_equal "/path/to/cache/directory", ActionController::Base.fragment_cache_store.cache_path
end
def test_drb_fragment_cache_store
ActionController::Base.fragment_cache_store = :drb_store, "druby://localhost:9192"
assert_kind_of(
ActionController::Caching::Fragments::DRbStore,
ActionController::Base.fragment_cache_store
)
assert_equal "druby://localhost:9192", ActionController::Base.fragment_cache_store.address
end
def test_mem_cache_fragment_cache_store
ActionController::Base.fragment_cache_store = :mem_cache_store, "localhost"
assert_kind_of(
ActionController::Caching::Fragments::MemCacheStore,
ActionController::Base.fragment_cache_store
)
assert_equal %w(localhost), ActionController::Base.fragment_cache_store.addresses
end
def test_object_assigned_fragment_cache_store
ActionController::Base.fragment_cache_store = ActionController::Caching::Fragments::FileStore.new("/path/to/cache/directory")
assert_kind_of(
ActionController::Caching::Fragments::FileStore,
ActionController::Base.fragment_cache_store
)
assert_equal "/path/to/cache/directory", ActionController::Base.fragment_cache_store.cache_path
end
end

View file

@ -0,0 +1,187 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class TestController < ActionController::Base
attr_accessor :delegate_attr
def delegate_method() end
def rescue_action(e) raise end
end
module Fun
class GamesController < ActionController::Base
def render_hello_world
render :inline => "hello: <%= stratego %>"
end
def rescue_action(e) raise end
end
class PDFController < ActionController::Base
def test
render :inline => "test: <%= foobar %>"
end
def rescue_action(e) raise end
end
end
module LocalAbcHelper
def a() end
def b() end
def c() end
end
class HelperTest < Test::Unit::TestCase
def setup
# Increment symbol counter.
@symbol = (@@counter ||= 'A0').succ!.dup
# Generate new controller class.
controller_class_name = "Helper#{@symbol}Controller"
eval("class #{controller_class_name} < TestController; end")
@controller_class = self.class.const_get(controller_class_name)
# Generate new template class and assign to controller.
template_class_name = "Test#{@symbol}View"
eval("class #{template_class_name} < ActionView::Base; end")
@template_class = self.class.const_get(template_class_name)
@controller_class.template_class = @template_class
# Set default test helper.
self.test_helper = LocalAbcHelper
end
def teardown
# Reset template class.
#ActionController::Base.template_class = ActionView::Base
end
def test_deprecated_helper
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised { @controller_class.helper TestHelper }
assert_equal [], missing_methods
end
def test_declare_helper
require 'abc_helper'
self.test_helper = AbcHelper
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised { @controller_class.helper :abc }
assert_equal [], missing_methods
end
def test_declare_missing_helper
assert_equal expected_helper_methods, missing_methods
assert_raise(MissingSourceFile) { @controller_class.helper :missing }
end
def test_declare_missing_file_from_helper
require 'broken_helper'
rescue LoadError => e
assert_nil /\bbroken_helper\b/.match(e.to_s)[1]
end
def test_helper_block
assert_nothing_raised {
@controller_class.helper { def block_helper_method; end }
}
assert master_helper_methods.include?('block_helper_method')
end
def test_helper_block_include
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised {
@controller_class.helper { include TestHelper }
}
assert [], missing_methods
end
def test_helper_method
assert_nothing_raised { @controller_class.helper_method :delegate_method }
assert master_helper_methods.include?('delegate_method')
end
def test_helper_attr
assert_nothing_raised { @controller_class.helper_attr :delegate_attr }
assert master_helper_methods.include?('delegate_attr')
assert master_helper_methods.include?('delegate_attr=')
end
def test_helper_for_nested_controller
request = ActionController::TestRequest.new
response = ActionController::TestResponse.new
request.action = 'render_hello_world'
assert_equal 'hello: Iz guuut!', Fun::GamesController.process(request, response).body
end
def test_helper_for_acronym_controller
request = ActionController::TestRequest.new
response = ActionController::TestResponse.new
request.action = 'test'
assert_equal 'test: baz', Fun::PDFController.process(request, response).body
end
private
def expected_helper_methods
TestHelper.instance_methods
end
def master_helper_methods
@controller_class.master_helper_module.instance_methods
end
def missing_methods
expected_helper_methods - master_helper_methods
end
def test_helper=(helper_module)
silence_warnings { self.class.const_set('TestHelper', helper_module) }
end
end
class IsolatedHelpersTest < Test::Unit::TestCase
class A < ActionController::Base
def index
render :inline => '<%= shout %>'
end
def rescue_action(e) raise end
end
class B < A
helper { def shout; 'B' end }
def index
render :inline => '<%= shout %>'
end
end
class C < A
helper { def shout; 'C' end }
def index
render :inline => '<%= shout %>'
end
end
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.action = 'index'
end
def test_helper_in_a
assert_raise(NameError) { A.process(@request, @response) }
end
def test_helper_in_b
assert_equal 'B', B.process(@request, @response).body
end
def test_helper_in_c
assert_equal 'C', C.process(@request, @response).body
end
end

View file

@ -0,0 +1,73 @@
require File.dirname(__FILE__) + '/../abstract_unit'
# The template_root must be set on Base and not LayoutTest so that LayoutTest's inherited method has access to
# the template_root when looking for a layout
ActionController::Base.template_root = File.dirname(__FILE__) + '/../fixtures/layout_tests/'
class LayoutTest < ActionController::Base
def self.controller_path; 'views' end
end
# Restore template root to be unset
ActionController::Base.template_root = nil
class ProductController < LayoutTest
end
class ItemController < LayoutTest
end
class ThirdPartyTemplateLibraryController < LayoutTest
end
module ControllerNameSpace
end
class ControllerNameSpace::NestedController < LayoutTest
end
class MabView
def initialize(view)
end
def render(text, locals = {})
text
end
end
ActionView::Base::register_template_handler :mab, MabView
class LayoutAutoDiscoveryTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.host = "www.nextangle.com"
end
def test_application_layout_is_default_when_no_controller_match
@controller = ProductController.new
get :hello
assert_equal 'layout_test.rhtml hello.rhtml', @response.body
end
def test_controller_name_layout_name_match
@controller = ItemController.new
get :hello
assert_equal 'item.rhtml hello.rhtml', @response.body
end
def test_third_party_template_library_auto_discovers_layout
@controller = ThirdPartyTemplateLibraryController.new
get :hello
assert_equal 'layouts/third_party_template_library', @controller.active_layout
assert_equal 'Mab', @response.body
end
def test_namespaced_controllers_auto_detect_layouts
@controller = ControllerNameSpace::NestedController.new
get :hello
assert_equal 'layouts/controller_name_space/nested', @controller.active_layout
assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
end
end

View file

@ -0,0 +1,257 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class RespondToController < ActionController::Base
layout :set_layout
def html_xml_or_rss
respond_to do |type|
type.html { render :text => "HTML" }
type.xml { render :text => "XML" }
type.rss { render :text => "RSS" }
type.all { render :text => "Nothing" }
end
end
def js_or_html
respond_to do |type|
type.html { render :text => "HTML" }
type.js { render :text => "JS" }
type.all { render :text => "Nothing" }
end
end
def html_or_xml
respond_to do |type|
type.html { render :text => "HTML" }
type.xml { render :text => "XML" }
type.all { render :text => "Nothing" }
end
end
def just_xml
respond_to do |type|
type.xml { render :text => "XML" }
end
end
def using_defaults
respond_to do |type|
type.html
type.js
type.xml
end
end
def using_defaults_with_type_list
respond_to(:html, :js, :xml)
end
def made_for_content_type
respond_to do |type|
type.rss { render :text => "RSS" }
type.atom { render :text => "ATOM" }
type.all { render :text => "Nothing" }
end
end
def custom_type_handling
respond_to do |type|
type.html { render :text => "HTML" }
type.custom("application/crazy-xml") { render :text => "Crazy XML" }
type.all { render :text => "Nothing" }
end
end
def handle_any
respond_to do |type|
type.html { render :text => "HTML" }
type.any(:js, :xml) { render :text => "Either JS or XML" }
end
end
def all_types_with_layout
respond_to do |type|
type.html
type.js
end
end
def rescue_action(e)
raise
end
protected
def set_layout
if action_name == "all_types_with_layout"
"standard"
end
end
end
RespondToController.template_root = File.dirname(__FILE__) + "/../fixtures/"
class MimeControllerTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = RespondToController.new
@request.host = "www.example.com"
end
def test_html
@request.env["HTTP_ACCEPT"] = "text/html"
get :js_or_html
assert_equal 'HTML', @response.body
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_response 406
end
def test_all
@request.env["HTTP_ACCEPT"] = "*/*"
get :js_or_html
assert_equal 'HTML', @response.body # js is not part of all
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_equal 'XML', @response.body
end
def test_xml
@request.env["HTTP_ACCEPT"] = "application/xml"
get :html_xml_or_rss
assert_equal 'XML', @response.body
end
def test_js_or_html
@request.env["HTTP_ACCEPT"] = "text/javascript, text/html"
get :js_or_html
assert_equal 'JS', @response.body
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_response 406
end
def test_js_or_anything
@request.env["HTTP_ACCEPT"] = "text/javascript, */*"
get :js_or_html
assert_equal 'JS', @response.body
get :html_or_xml
assert_equal 'HTML', @response.body
get :just_xml
assert_equal 'XML', @response.body
end
def test_using_defaults
@request.env["HTTP_ACCEPT"] = "*/*"
get :using_defaults
assert_equal 'Hello world!', @response.body
@request.env["HTTP_ACCEPT"] = "text/javascript"
get :using_defaults
assert_equal '$("body").visualEffect("highlight");', @response.body
@request.env["HTTP_ACCEPT"] = "application/xml"
get :using_defaults
assert_equal "<p>Hello world!</p>\n", @response.body
end
def test_using_defaults_with_type_list
@request.env["HTTP_ACCEPT"] = "*/*"
get :using_defaults_with_type_list
assert_equal 'Hello world!', @response.body
@request.env["HTTP_ACCEPT"] = "text/javascript"
get :using_defaults_with_type_list
assert_equal '$("body").visualEffect("highlight");', @response.body
@request.env["HTTP_ACCEPT"] = "application/xml"
get :using_defaults_with_type_list
assert_equal "<p>Hello world!</p>\n", @response.body
end
def test_with_content_type
@request.env["CONTENT_TYPE"] = "application/atom+xml"
get :made_for_content_type
assert_equal "ATOM", @response.body
@request.env["CONTENT_TYPE"] = "application/rss+xml"
get :made_for_content_type
assert_equal "RSS", @response.body
end
def test_synonyms
@request.env["HTTP_ACCEPT"] = "application/javascript"
get :js_or_html
assert_equal 'JS', @response.body
@request.env["HTTP_ACCEPT"] = "application/x-xml"
get :html_xml_or_rss
assert_equal "XML", @response.body
end
def test_custom_types
@request.env["HTTP_ACCEPT"] = "application/crazy-xml"
get :custom_type_handling
assert_equal 'Crazy XML', @response.body
@request.env["HTTP_ACCEPT"] = "text/html"
get :custom_type_handling
assert_equal 'HTML', @response.body
end
def test_xhtml_alias
@request.env["HTTP_ACCEPT"] = "application/xhtml+xml,application/xml"
get :html_or_xml
assert_equal 'HTML', @response.body
end
def test_firefox_simulation
@request.env["HTTP_ACCEPT"] = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
get :html_or_xml
assert_equal 'HTML', @response.body
end
def test_handle_any
@request.env["HTTP_ACCEPT"] = "*/*"
get :handle_any
assert_equal 'HTML', @response.body
@request.env["HTTP_ACCEPT"] = "text/javascript"
get :handle_any
assert_equal 'Either JS or XML', @response.body
@request.env["HTTP_ACCEPT"] = "text/xml"
get :handle_any
assert_equal 'Either JS or XML', @response.body
end
def test_all_types_with_layout
@request.env["HTTP_ACCEPT"] = "text/javascript"
get :all_types_with_layout
assert_equal 'RJS for all_types_with_layout', @response.body
@request.env["HTTP_ACCEPT"] = "text/html"
get :all_types_with_layout
assert_equal '<html>HTML for all_types_with_layout</html>', @response.body
end
def test_xhr
xhr :get, :js_or_html
assert_equal 'JS', @response.body
xhr :get, :using_defaults
assert_equal '$("body").visualEffect("highlight");', @response.body
end
end

View file

@ -0,0 +1,24 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class MimeTypeTest < Test::Unit::TestCase
Mime::PNG = Mime::Type.new("image/png")
Mime::PLAIN = Mime::Type.new("text/plain")
def test_parse_single
Mime::LOOKUP.keys.each do |mime_type|
assert_equal [Mime::Type.lookup(mime_type)], Mime::Type.parse(mime_type)
end
end
def test_parse_without_q
accept = "text/xml,application/xhtml+xml,text/yaml,application/xml,text/html,image/png,text/plain,*/*"
expect = [Mime::HTML, Mime::XML, Mime::YAML, Mime::PNG, Mime::PLAIN, Mime::ALL]
assert_equal expect, Mime::Type.parse(accept)
end
def test_parse_with_q
accept = "text/xml,application/xhtml+xml,text/yaml; q=0.3,application/xml,text/html; q=0.8,image/png,text/plain; q=0.5,*/*; q=0.2"
expect = [Mime::HTML, Mime::XML, Mime::PNG, Mime::PLAIN, Mime::YAML, Mime::ALL]
assert_equal expect, Mime::Type.parse(accept)
end
end

View file

@ -0,0 +1,600 @@
require File.dirname(__FILE__) + '/../abstract_unit'
silence_warnings { Customer = Struct.new("Customer", :name) }
module Fun
class GamesController < ActionController::Base
def hello_world
end
end
end
module NewRenderTestHelper
def rjs_helper_method_from_module
page.visual_effect :highlight
end
end
class NewRenderTestController < ActionController::Base
layout :determine_layout
def self.controller_name; "test"; end
def self.controller_path; "test"; end
def hello_world
end
def render_hello_world
render :template => "test/hello_world"
end
def render_hello_world_from_variable
@person = "david"
render :text => "hello #{@person}"
end
def render_action_hello_world
render :action => "hello_world"
end
def render_action_hello_world_as_symbol
render :action => :hello_world
end
def render_text_hello_world
render :text => "hello world"
end
def render_text_hello_world_with_layout
@variable_for_layout = ", I'm here!"
render :text => "hello world", :layout => true
end
def hello_world_with_layout_false
render :layout => false
end
def render_custom_code
render :text => "hello world", :status => "404 Moved"
end
def render_file_with_instance_variables
@secret = 'in the sauce'
path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.rhtml')
render :file => path
end
def render_file_with_locals
path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.rhtml')
render :file => path, :locals => {:secret => 'in the sauce'}
end
def render_file_not_using_full_path
@secret = 'in the sauce'
render :file => 'test/render_file_with_ivar', :use_full_path => true
end
def render_file_not_using_full_path_with_relative_path
@secret = 'in the sauce'
render :file => 'test/../test/render_file_with_ivar', :use_full_path => true
end
def render_file_not_using_full_path_with_dot_in_path
@secret = 'in the sauce'
render :file => 'test/dot.directory/render_file_with_ivar', :use_full_path => true
end
def render_xml_hello
@name = "David"
render :template => "test/hello"
end
def greeting
# let's just rely on the template
end
def layout_test
render :action => "hello_world"
end
def layout_test_with_different_layout
render :action => "hello_world", :layout => "standard"
end
def rendering_without_layout
render :action => "hello_world", :layout => false
end
def layout_overriding_layout
render :action => "hello_world", :layout => "standard"
end
def rendering_nothing_on_layout
render :nothing => true
end
def builder_layout_test
render :action => "hello"
end
def partials_list
@test_unchanged = 'hello'
@customers = [ Customer.new("david"), Customer.new("mary") ]
render :action => "list"
end
def partial_only
render :partial => true
end
def partial_only_with_layout
render :partial => "partial_only", :layout => true
end
def partial_with_locals
render :partial => "customer", :locals => { :customer => Customer.new("david") }
end
def partial_collection
render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_locals
render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" }
end
def empty_partial_collection
render :partial => "customer", :collection => []
end
def partial_with_hash_object
render :partial => "hash_object", :object => {:first_name => "Sam"}
end
def partial_with_implicit_local_assignment
@customer = Customer.new("Marcel")
render :partial => "customer"
end
def hello_in_a_string
@customers = [ Customer.new("david"), Customer.new("mary") ]
render :text => "How's there? #{render_to_string("test/list")}"
end
def accessing_params_in_template
render :inline => "Hello: <%= params[:name] %>"
end
def accessing_params_in_template_with_layout
render :layout => nil, :inline => "Hello: <%= params[:name] %>"
end
def render_with_explicit_template
render "test/hello_world"
end
def double_render
render :text => "hello"
render :text => "world"
end
def double_redirect
redirect_to :action => "double_render"
redirect_to :action => "double_render"
end
def render_and_redirect
render :text => "hello"
redirect_to :action => "double_render"
end
def rendering_with_conflicting_local_vars
@name = "David"
def @template.name() nil end
render :action => "potential_conflicts"
end
def hello_world_from_rxml_using_action
render :action => "hello_world.rxml"
end
def hello_world_from_rxml_using_template
render :template => "test/hello_world.rxml"
end
helper NewRenderTestHelper
helper do
def rjs_helper_method(value)
page.visual_effect :highlight, value
end
end
def enum_rjs_test
render :update do |page|
page.select('.product').each do |value|
page.rjs_helper_method_from_module
page.rjs_helper_method(value)
page.sortable(value, :url => { :action => "order" })
page.draggable(value)
end
end
end
def delete_with_js
@project_id = 4
end
def render_js_with_explicit_template
@project_id = 4
render :template => 'test/delete_with_js'
end
def render_js_with_explicit_action_template
@project_id = 4
render :action => 'delete_with_js'
end
def update_page
render :update do |page|
page.replace_html 'balance', '$37,000,000.00'
page.visual_effect :highlight, 'balance'
end
end
def update_page_with_instance_variables
@money = '$37,000,000.00'
@div_id = 'balance'
render :update do |page|
page.replace_html @div_id, @money
page.visual_effect :highlight, @div_id
end
end
def action_talk_to_layout
# Action template sets variable that's picked up by layout
end
def render_text_with_assigns
@hello = "world"
render :text => "foo"
end
def yield_content_for
render :action => "content_for", :layout => "yield"
end
def rescue_action(e) raise end
private
def determine_layout
case action_name
when "hello_world", "layout_test", "rendering_without_layout",
"rendering_nothing_on_layout", "render_text_hello_world",
"render_text_hello_world_with_layout",
"hello_world_with_layout_false",
"partial_only", "partial_only_with_layout",
"accessing_params_in_template",
"accessing_params_in_template_with_layout",
"render_with_explicit_template",
"render_js_with_explicit_template",
"render_js_with_explicit_action_template",
"delete_with_js", "update_page", "update_page_with_instance_variables"
"layouts/standard"
when "builder_layout_test"
"layouts/builder"
when "action_talk_to_layout", "layout_overriding_layout"
"layouts/talk_from_action"
end
end
end
NewRenderTestController.template_root = File.dirname(__FILE__) + "/../fixtures/"
Fun::GamesController.template_root = File.dirname(__FILE__) + "/../fixtures/"
class NewRenderTest < Test::Unit::TestCase
def setup
@controller = NewRenderTestController.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_simple_show
get :hello_world
assert_response :success
assert_template "test/hello_world"
assert_equal "<html>Hello world!</html>", @response.body
end
def test_do_with_render
get :render_hello_world
assert_template "test/hello_world"
end
def test_do_with_render_from_variable
get :render_hello_world_from_variable
assert_equal "hello david", @response.body
end
def test_do_with_render_action
get :render_action_hello_world
assert_template "test/hello_world"
end
def test_do_with_render_action_as_symbol
get :render_action_hello_world_as_symbol
assert_template "test/hello_world"
end
def test_do_with_render_text
get :render_text_hello_world
assert_equal "hello world", @response.body
end
def test_do_with_render_text_and_layout
get :render_text_hello_world_with_layout
assert_equal "<html>hello world, I'm here!</html>", @response.body
end
def test_do_with_render_action_and_layout_false
get :hello_world_with_layout_false
assert_equal 'Hello world!', @response.body
end
def test_do_with_render_custom_code
get :render_custom_code
assert_response :missing
end
def test_render_file_with_instance_variables
get :render_file_with_instance_variables
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_not_using_full_path
get :render_file_not_using_full_path
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_not_using_full_path_with_relative_path
get :render_file_not_using_full_path_with_relative_path
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_not_using_full_path_with_dot_in_path
get :render_file_not_using_full_path_with_dot_in_path
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_with_locals
get :render_file_with_locals
assert_equal "The secret is in the sauce\n", @response.body
end
def test_attempt_to_access_object_method
assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone }
end
def test_private_methods
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_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
end
def test_enum_rjs_test
get :enum_rjs_test
assert_equal <<-EOS.strip, @response.body
$$(".product").each(function(value, index) {
new Effect.Highlight(element,{});
new Effect.Highlight(value,{});
Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}});
new Draggable(value, {});
});
EOS
end
def test_render_xml_with_default
get :greeting
assert_equal "<p>This is grand!</p>\n", @response.body
end
def test_render_rjs_with_default
get :delete_with_js
assert_equal %!["person"].each(Element.remove);\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
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
end
def test_layout_rendering
get :layout_test
assert_equal "<html>Hello world!</html>", @response.body
end
def test_layout_test_with_different_layout
get :layout_test_with_different_layout
assert_equal "<html>Hello world!</html>", @response.body
end
def test_rendering_without_layout
get :rendering_without_layout
assert_equal "Hello world!", @response.body
end
def test_layout_overriding_layout
get :layout_overriding_layout
assert_no_match %r{<title>}, @response.body
end
def test_rendering_nothing_on_layout
get :rendering_nothing_on_layout
assert_equal " ", @response.body
end
def test_render_xml_with_layouts
get :builder_layout_test
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
end
def test_partial_only
get :partial_only
assert_equal "only partial", @response.body
end
def test_partial_only_with_layout
get :partial_only_with_layout
assert_equal "<html>only partial</html>", @response.body
end
def test_render_to_string
get :hello_in_a_string
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_nested_rendering
get :hello_world
assert_equal "Living in a nested world", Fun::GamesController.process(@request, @response).body
end
def test_accessing_params_in_template
get :accessing_params_in_template, :name => "David"
assert_equal "Hello: David", @response.body
end
def test_accessing_params_in_template_with_layout
get :accessing_params_in_template_with_layout, :name => "David"
assert_equal "<html>Hello: David</html>", @response.body
end
def test_render_with_explicit_template
get :render_with_explicit_template
assert_response :success
end
def test_double_render
assert_raises(ActionController::DoubleRenderError) { get :double_render }
end
def test_double_redirect
assert_raises(ActionController::DoubleRenderError) { get :double_redirect }
end
def test_render_and_redirect
assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect }
end
def test_rendering_with_conflicting_local_vars
get :rendering_with_conflicting_local_vars
assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body)
end
def test_action_talk_to_layout
get :action_talk_to_layout
assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body
end
def test_partials_list
get :partials_list
assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_partial_with_locals
get :partial_with_locals
assert_equal "Hello: david", @response.body
end
def test_partial_collection
get :partial_collection
assert_equal "Hello: davidHello: mary", @response.body
end
def test_partial_collection_with_locals
get :partial_collection_with_locals
assert_equal "Bonjour: davidBonjour: mary", @response.body
end
def test_empty_partial_collection
get :empty_partial_collection
assert_equal " ", @response.body
end
def test_partial_with_hash_object
get :partial_with_hash_object
assert_equal "Sam", @response.body
end
def test_partial_with_implicit_local_assignment
get :partial_with_implicit_local_assignment
assert_equal "Hello: Marcel", @response.body
end
def test_render_text_with_assigns
get :render_text_with_assigns
assert_equal "world", assigns["hello"]
end
def test_update_page
get :update_page
assert_template nil
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_match /balance/, @response.body
assert_match /\$37/, @response.body
end
def test_yield_content_for
get :yield_content_for
assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body
end
def test_overwritting_rendering_relative_file_with_extension
get :hello_world_from_rxml_using_template
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
get :hello_world_from_rxml_using_action
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
end
end

View file

@ -0,0 +1,31 @@
require 'test/unit'
require 'cgi'
require 'stringio'
require File.dirname(__FILE__) + '/../../lib/action_controller/cgi_ext/raw_post_data_fix'
class RawPostDataTest < Test::Unit::TestCase
def setup
ENV['REQUEST_METHOD'] = 'POST'
ENV['CONTENT_TYPE'] = ''
ENV['CONTENT_LENGTH'] = '0'
end
def test_raw_post_data
process_raw "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
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
end
end

View file

@ -0,0 +1,143 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class RedirectController < ActionController::Base
def simple_redirect
redirect_to :action => "hello_world"
end
def method_redirect
redirect_to :dashbord_url, 1, "hello"
end
def host_redirect
redirect_to :action => "other_host", :only_path => false, :host => 'other.test.host'
end
def module_redirect
redirect_to :controller => 'module_test/module_redirect', :action => "hello_world"
end
def redirect_with_assigns
@hello = "world"
redirect_to :action => "hello_world"
end
def redirect_to_back
redirect_to :back
end
def rescue_errors(e) raise e end
def rescue_action(e) raise end
protected
def dashbord_url(id, message)
url_for :action => "dashboard", :params => { "id" => id, "message" => message }
end
end
class RedirectTest < Test::Unit::TestCase
def setup
@controller = RedirectController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_simple_redirect
get :simple_redirect
assert_redirect_url "http://test.host/redirect/hello_world"
end
def test_redirect_with_method_reference_and_parameters
get :method_redirect
assert_redirect_url "http://test.host/redirect/dashboard/1?message=hello"
end
def test_simple_redirect_using_options
get :host_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
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
end
end
def test_module_redirect
get :module_redirect
assert_redirect_url "http://test.host/module_test/module_redirect/hello_world"
end
def test_module_redirect_using_options
get :module_redirect
assert_redirected_to :controller => 'module_test/module_redirect', :action => 'hello_world'
end
def test_redirect_with_assigns
get :redirect_with_assigns
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"
end
def test_redirect_to_back_with_no_referer
assert_raises(ActionController::RedirectBackError) {
@request.env["HTTP_REFERER"] = nil
get :redirect_to_back
}
end
end
module ModuleTest
class ModuleRedirectController < ::RedirectController
def module_redirect
redirect_to :controller => '/redirect', :action => "hello_world"
end
end
class ModuleRedirectTest < Test::Unit::TestCase
def setup
@controller = ModuleRedirectController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_simple_redirect
get :simple_redirect
assert_redirect_url "http://test.host/module_test/module_redirect/hello_world"
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"
end
def test_simple_redirect_using_options
get :host_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"
end
def test_module_redirect_using_options
get :module_redirect
assert_redirected_to :controller => 'redirect', :action => "hello_world"
end
end
end

View file

@ -0,0 +1,246 @@
require File.dirname(__FILE__) + '/../abstract_unit'
unless defined?(Customer)
Customer = Struct.new("Customer", :name)
end
module Fun
class GamesController < ActionController::Base
def hello_world
end
end
end
class TestController < ActionController::Base
layout :determine_layout
def hello_world
end
def render_hello_world
render "test/hello_world"
end
def render_hello_world_from_variable
@person = "david"
render_text "hello #{@person}"
end
def render_action_hello_world
render_action "hello_world"
end
def render_action_hello_world_with_symbol
render_action :hello_world
end
def render_text_hello_world
render_text "hello world"
end
def render_custom_code
render_text "hello world", "404 Moved"
end
def render_xml_hello
@name = "David"
render "test/hello"
end
def greeting
# let's just rely on the template
end
def layout_test
render_action "hello_world"
end
def builder_layout_test
render_action "hello"
end
def partials_list
@test_unchanged = 'hello'
@customers = [ Customer.new("david"), Customer.new("mary") ]
render_action "list"
end
def partial_only
render_partial
end
def hello_in_a_string
@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
def accessing_local_assigns_in_inline_template
name = params[:local_name]
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
render :inline => "<%= 'Goodbye, ' + local_name %>",
:locals => { "local_name" => name }
ActionView::Base.local_assigns_support_string_keys = false
end
def render_to_string_test
@foo = render_to_string :inline => "this is a test"
end
def rescue_action(e) raise end
private
def determine_layout
case action_name
when "layout_test": "layouts/standard"
when "builder_layout_test": "layouts/builder"
end
end
end
TestController.template_root = File.dirname(__FILE__) + "/../fixtures/"
Fun::GamesController.template_root = File.dirname(__FILE__) + "/../fixtures/"
class RenderTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@controller = TestController.new
@request.host = "www.nextangle.com"
end
def test_simple_show
get :hello_world
assert_response 200
assert_template "test/hello_world"
end
def test_do_with_render
get :render_hello_world
assert_template "test/hello_world"
end
def test_do_with_render_from_variable
get :render_hello_world_from_variable
assert_equal "hello david", @response.body
end
def test_do_with_render_action
get :render_action_hello_world
assert_template "test/hello_world"
end
def test_do_with_render_action_with_symbol
get :render_action_hello_world_with_symbol
assert_template "test/hello_world"
end
def test_do_with_render_text
get :render_text_hello_world
assert_equal "hello world", @response.body
end
def test_do_with_render_custom_code
get :render_custom_code
assert_response 404
end
def test_attempt_to_access_object_method
assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone }
end
def test_private_methods
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_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
end
def test_render_xml_with_default
get :greeting
assert_equal "<p>This is grand!</p>\n", @response.body
end
def test_layout_rendering
get :layout_test
assert_equal "<html>Hello world!</html>", @response.body
end
def test_render_xml_with_layouts
get :builder_layout_test
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
end
# def test_partials_list
# get :partials_list
# assert_equal "goodbyeHello: davidHello: marygoodbye\n", process_request.body
# end
def test_partial_only
get :partial_only
assert_equal "only partial", @response.body
end
def test_render_to_string
get :hello_in_a_string
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_render_to_string_resets_assigns
get :render_to_string_test
assert_equal "The value of foo is: ::this is a test::\n", @response.body
end
def test_nested_rendering
@controller = Fun::GamesController.new
get :hello_world
assert_equal "Living in a nested world", @response.body
end
def test_accessing_params_in_template
get :accessing_params_in_template, :name => "David"
assert_equal "Hello: David", @response.body
end
def test_accessing_local_assigns_in_inline_template
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
end

View file

@ -0,0 +1,266 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class RequestTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
end
def test_remote_ip
assert_equal '0.0.0.0', @request.remote_ip
@request.remote_addr = '1.2.3.4'
assert_equal '1.2.3.4', @request.remote_ip
@request.env['HTTP_CLIENT_IP'] = '2.3.4.5'
assert_equal '2.3.4.5', @request.remote_ip
@request.env.delete 'HTTP_CLIENT_IP'
@request.env['HTTP_X_FORWARDED_FOR'] = '3.4.5.6'
assert_equal '3.4.5.6', @request.remote_ip
@request.env['HTTP_X_FORWARDED_FOR'] = 'unknown,3.4.5.6'
assert_equal '3.4.5.6', @request.remote_ip
@request.env['HTTP_X_FORWARDED_FOR'] = '172.16.0.1,3.4.5.6'
assert_equal '3.4.5.6', @request.remote_ip
@request.env['HTTP_X_FORWARDED_FOR'] = '192.168.0.1,3.4.5.6'
assert_equal '3.4.5.6', @request.remote_ip
@request.env['HTTP_X_FORWARDED_FOR'] = '10.0.0.1,3.4.5.6'
assert_equal '3.4.5.6', @request.remote_ip
@request.env['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,3.4.5.6'
assert_equal '127.0.0.1', @request.remote_ip
@request.env['HTTP_X_FORWARDED_FOR'] = 'unknown,192.168.0.1'
assert_equal '1.2.3.4', @request.remote_ip
@request.env.delete 'HTTP_X_FORWARDED_FOR'
end
def test_domains
@request.host = "www.rubyonrails.org"
assert_equal "rubyonrails.org", @request.domain
@request.host = "www.rubyonrails.co.uk"
assert_equal "rubyonrails.co.uk", @request.domain(2)
@request.host = "192.168.1.200"
assert_nil @request.domain
@request.host = nil
assert_nil @request.domain
end
def test_subdomains
@request.host = "www.rubyonrails.org"
assert_equal %w( www ), @request.subdomains
@request.host = "www.rubyonrails.co.uk"
assert_equal %w( www ), @request.subdomains(2)
@request.host = "dev.www.rubyonrails.co.uk"
assert_equal %w( dev www ), @request.subdomains(2)
@request.host = "foobar.foobar.com"
assert_equal %w( foobar ), @request.subdomains
@request.host = nil
assert_equal [], @request.subdomains
end
def test_port_string
@request.port = 80
assert_equal "", @request.port_string
@request.port = 8080
assert_equal ":8080", @request.port_string
end
def test_relative_url_root
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
@request.env['SERVER_SOFTWARE'] = 'lighttpd/1.2.3'
assert_equal '', @request.relative_url_root, "relative_url_root should be disabled on lighttpd"
@request.env['SERVER_SOFTWARE'] = 'apache/1.2.3 some random text'
@request.env['SCRIPT_NAME'] = nil
assert_equal "", @request.relative_url_root
@request.env['SCRIPT_NAME'] = "/dispatch.cgi"
assert_equal "", @request.relative_url_root
@request.env['SCRIPT_NAME'] = "/myapp.rb"
assert_equal "", @request.relative_url_root
@request.relative_url_root = nil
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
assert_equal "/hieraki", @request.relative_url_root
@request.relative_url_root = nil
@request.env['SCRIPT_NAME'] = "/collaboration/hieraki/dispatch.cgi"
assert_equal "/collaboration/hieraki", @request.relative_url_root
# apache/scgi case
@request.relative_url_root = nil
@request.env['SCRIPT_NAME'] = "/collaboration/hieraki"
assert_equal "/collaboration/hieraki", @request.relative_url_root
@request.relative_url_root = nil
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
@request.env['SERVER_SOFTWARE'] = 'lighttpd/1.2.3'
@request.env['RAILS_RELATIVE_URL_ROOT'] = "/hieraki"
assert_equal "/hieraki", @request.relative_url_root
# @env overrides path guess
@request.relative_url_root = nil
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
@request.env['SERVER_SOFTWARE'] = 'apache/1.2.3 some random text'
@request.env['RAILS_RELATIVE_URL_ROOT'] = "/real_url"
assert_equal "/real_url", @request.relative_url_root
end
def test_request_uri
@request.env['SERVER_SOFTWARE'] = 'Apache 42.342.3432'
@request.relative_url_root = nil
@request.set_REQUEST_URI "http://www.rubyonrails.org/path/of/some/uri?mapped=1"
assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
assert_equal "/path/of/some/uri", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "http://www.rubyonrails.org/path/of/some/uri"
assert_equal "/path/of/some/uri", @request.request_uri
assert_equal "/path/of/some/uri", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "/path/of/some/uri"
assert_equal "/path/of/some/uri", @request.request_uri
assert_equal "/path/of/some/uri", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "/"
assert_equal "/", @request.request_uri
assert_equal "/", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "/?m=b"
assert_equal "/?m=b", @request.request_uri
assert_equal "/", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "/"
@request.env['SCRIPT_NAME'] = "/dispatch.cgi"
assert_equal "/", @request.request_uri
assert_equal "/", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "/hieraki/"
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
assert_equal "/hieraki/", @request.request_uri
assert_equal "/", @request.path
@request.relative_url_root = nil
@request.set_REQUEST_URI "/collaboration/hieraki/books/edit/2"
@request.env['SCRIPT_NAME'] = "/collaboration/hieraki/dispatch.cgi"
assert_equal "/collaboration/hieraki/books/edit/2", @request.request_uri
assert_equal "/books/edit/2", @request.path
# The following tests are for when REQUEST_URI is not supplied (as in IIS)
@request.relative_url_root = nil
@request.set_REQUEST_URI nil
@request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1"
@request.env['SCRIPT_NAME'] = nil #"/path/dispatch.rb"
assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
assert_equal "/path/of/some/uri", @request.path
@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.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.relative_url_root = nil
@request.env['PATH_INFO'] = "/"
assert_equal "/", @request.request_uri
assert_equal "/", @request.path
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/?m=b"
assert_equal "/?m=b", @request.request_uri
assert_equal "/", @request.path
@request.relative_url_root = nil
@request.env['PATH_INFO'] = "/"
@request.env['SCRIPT_NAME'] = "/dispatch.cgi"
assert_equal "/", @request.request_uri
assert_equal "/", @request.path
@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
# This test ensures that Rails uses REQUEST_URI over PATH_INFO
@request.relative_url_root = nil
@request.env['REQUEST_URI'] = "/some/path"
@request.env['PATH_INFO'] = "/another/path"
@request.env['SCRIPT_NAME'] = "/dispatch.cgi"
assert_equal "/some/path", @request.request_uri
assert_equal "/some/path", @request.path
end
def test_host_with_port
@request.host = "rubyonrails.org"
@request.port = 80
assert_equal "rubyonrails.org", @request.host_with_port
@request.host = "rubyonrails.org"
@request.port = 81
assert_equal "rubyonrails.org:81", @request.host_with_port
end
def test_server_software
assert_equal nil, @request.server_software
@request.env['SERVER_SOFTWARE'] = 'Apache3.422'
assert_equal 'apache', @request.server_software
@request.env['SERVER_SOFTWARE'] = 'lighttpd(1.1.4)'
assert_equal 'lighttpd', @request.server_software
end
def test_xml_http_request
assert !@request.xml_http_request?
assert !@request.xhr?
@request.env['HTTP_X_REQUESTED_WITH'] = "DefinitelyNotAjax1.0"
assert !@request.xml_http_request?
assert !@request.xhr?
@request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
assert @request.xml_http_request?
assert @request.xhr?
end
def test_reports_ssl
assert !@request.ssl?
@request.env['HTTPS'] = 'on'
assert @request.ssl?
end
def test_reports_ssl_when_proxied_via_lighttpd
assert !@request.ssl?
@request.env['HTTP_X_FORWARDED_PROTO'] = 'https'
assert @request.ssl?
end
end

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,109 @@
require File.join(File.dirname(__FILE__), '..', 'abstract_unit')
module TestFileUtils
def file_name() File.basename(__FILE__) end
def file_path() File.expand_path(__FILE__) end
def file_data() File.open(file_path, 'rb') { |f| f.read } end
end
class SendFileController < ActionController::Base
include TestFileUtils
layout "layouts/standard" # to make sure layouts don't interfere
attr_writer :options
def options() @options ||= {} end
def file() send_file(file_path, options) end
def data() send_data(file_data, options) end
def rescue_action(e) raise end
end
SendFileController.template_root = File.dirname(__FILE__) + "/../fixtures/"
class SendFileTest < Test::Unit::TestCase
include TestFileUtils
def setup
@controller = SendFileController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_file_nostream
@controller.options = { :stream => false }
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
assert_kind_of String, response.body
assert_equal file_data, response.body
end
def test_file_stream
response = nil
assert_nothing_raised { response = process('file') }
assert_not_nil response
assert_kind_of Proc, response.body
require 'stringio'
output = StringIO.new
output.binmode
assert_nothing_raised { response.body.call(response, output) }
assert_equal file_data, output.string
end
def test_data
response = nil
assert_nothing_raised { response = process('data') }
assert_not_nil response
assert_kind_of String, response.body
assert_equal file_data, response.body
end
# Test that send_file_headers! is setting the correct HTTP headers.
def test_send_file_headers!
options = {
:length => 1,
:type => 'type',
:disposition => 'disposition',
:filename => 'filename'
}
# Do it a few times: the resulting headers should be identical
# no matter how many times you send with the same options.
# Test resolving Ticket #458.
@controller.headers = {}
@controller.send(:send_file_headers!, options)
@controller.send(:send_file_headers!, options)
@controller.send(:send_file_headers!, options)
h = @controller.headers
assert_equal 1, h['Content-Length']
assert_equal 'type', h['Content-Type']
assert_equal 'disposition; filename="filename"', h['Content-Disposition']
assert_equal 'binary', h['Content-Transfer-Encoding']
# test overriding Cache-Control: no-cache header to fix IE open/save dialog
@controller.headers = { 'Cache-Control' => 'no-cache' }
@controller.send(:send_file_headers!, options)
h = @controller.headers
assert_equal 'private', h['Cache-Control']
end
%w(file data).each do |method|
define_method "test_send_#{method}_status" do
@controller.options = { :stream => false, :status => 500 }
assert_nothing_raised { assert_not_nil process(method) }
assert_equal '500', @controller.headers['Status']
end
define_method "test_default_send_#{method}_status" do
@controller.options = { :stream => false }
assert_nothing_raised { assert_not_nil process(method) }
assert_equal ActionController::Base::DEFAULT_RENDER_STATUS_CODE, @controller.headers['Status']
end
end
end

View file

@ -0,0 +1,94 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class SessionManagementTest < Test::Unit::TestCase
class SessionOffController < ActionController::Base
session :off
def show
render_text "done"
end
def tell
render_text "done"
end
end
class TestController < ActionController::Base
session :off, :only => :show
session :session_secure => true, :except => :show
session :off, :only => :conditional,
:if => Proc.new { |r| r.parameters[:ws] }
def show
render_text "done"
end
def tell
render_text "done"
end
def conditional
render_text ">>>#{params[:ws]}<<<"
end
end
class SpecializedController < SessionOffController
session :disabled => false, :only => :something
def something
render_text "done"
end
def another
render_text "done"
end
end
def setup
@request, @response = ActionController::TestRequest.new,
ActionController::TestResponse.new
end
def test_session_off_globally
@controller = SessionOffController.new
get :show
assert_equal false, @request.session_options
get :tell
assert_equal false, @request.session_options
end
def test_session_off_conditionally
@controller = TestController.new
get :show
assert_equal false, @request.session_options
get :tell
assert_instance_of Hash, @request.session_options
assert @request.session_options[:session_secure]
end
def test_controller_specialization_overrides_settings
@controller = SpecializedController.new
get :something
assert_instance_of Hash, @request.session_options
get :another
assert_equal false, @request.session_options
end
def test_session_off_with_if
@controller = TestController.new
get :conditional
assert_instance_of Hash, @request.session_options
get :conditional, :ws => "ws"
assert_equal false, @request.session_options
end
def test_session_store_setting
ActionController::Base.session_store = :drb_store
assert_equal CGI::Session::DRbStore, ActionController::Base.session_store
if Object.const_defined?(:ActiveRecord)
ActionController::Base.session_store = :active_record_store
assert_equal CGI::Session::ActiveRecordStore, ActionController::Base.session_store
end
end
end

View file

@ -0,0 +1,411 @@
require File.dirname(__FILE__) + '/../abstract_unit'
require File.dirname(__FILE__) + '/fake_controllers'
class TestTest < Test::Unit::TestCase
class TestController < ActionController::Base
def set_flash
flash["test"] = ">#{flash["test"]}<"
render :text => 'ignore me'
end
def render_raw_post
raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank?
render :text => request.raw_post
end
def test_params
render :text => params.inspect
end
def test_uri
render :text => request.request_uri
end
def test_html_output
render :text => <<HTML
<html>
<body>
<a href="/"><img src="/images/button.png" /></a>
<div id="foo">
<ul>
<li class="item">hello</li>
<li class="item">goodbye</li>
</ul>
</div>
<div id="bar">
<form action="/somewhere">
Name: <input type="text" name="person[name]" id="person_name" />
</form>
</div>
</body>
</html>
HTML
end
def test_only_one_param
render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
end
def test_remote_addr
render :text => (request.remote_addr || "not specified")
end
def test_file_upload
render :text => params[:file].size
end
def redirect_to_symbol
redirect_to :generate_url, :id => 5
end
private
def rescue_action(e)
raise e
end
def generate_url(opts)
url_for(opts.merge(:action => "test_uri"))
end
end
def setup
@controller = TestController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionController::Routing::Routes.reload
end
def teardown
ActionController::Routing::Routes.reload
end
def test_raw_post_handling
params = {:page => {:name => 'page name'}, 'some key' => 123}
get :render_raw_post, params.dup
raw_post = params.map {|k,v| [CGI::escape(k.to_s), CGI::escape(v.to_s)].join('=')}.sort.join('&')
assert_equal raw_post, @response.body
end
def test_process_without_flash
process :set_flash
assert_equal '><', flash['test']
end
def test_process_with_flash
process :set_flash, nil, nil, { "test" => "value" }
assert_equal '>value<', flash['test']
end
def test_process_with_request_uri_with_no_params
process :test_uri
assert_equal "/test_test/test/test_uri", @response.body
end
def test_process_with_request_uri_with_params
process :test_uri, :id => 7
assert_equal "/test_test/test/test_uri/7", @response.body
end
def test_process_with_request_uri_with_params_with_explicit_uri
@request.set_REQUEST_URI "/explicit/uri"
process :test_uri, :id => 7
assert_equal "/explicit/uri", @response.body
end
def test_multiple_calls
process :test_only_one_param, :left => true
assert_equal "OK", @response.body
process :test_only_one_param, :right => true
assert_equal "OK", @response.body
end
def test_assert_tag_tag
process :test_html_output
# there is a 'form' tag
assert_tag :tag => 'form'
# there is not an 'hr' tag
assert_no_tag :tag => 'hr'
end
def test_assert_tag_attributes
process :test_html_output
# there is a tag with an 'id' of 'bar'
assert_tag :attributes => { :id => "bar" }
# there is no tag with a 'name' of 'baz'
assert_no_tag :attributes => { :name => "baz" }
end
def test_assert_tag_parent
process :test_html_output
# there is a tag with a parent 'form' tag
assert_tag :parent => { :tag => "form" }
# there is no tag with a parent of 'input'
assert_no_tag :parent => { :tag => "input" }
end
def test_assert_tag_child
process :test_html_output
# there is a tag with a child 'input' tag
assert_tag :child => { :tag => "input" }
# there is no tag with a child 'strong' tag
assert_no_tag :child => { :tag => "strong" }
end
def test_assert_tag_ancestor
process :test_html_output
# there is a 'li' tag with an ancestor having an id of 'foo'
assert_tag :ancestor => { :attributes => { :id => "foo" } }, :tag => "li"
# there is no tag of any kind with an ancestor having an href matching 'foo'
assert_no_tag :ancestor => { :attributes => { :href => /foo/ } }
end
def test_assert_tag_descendant
process :test_html_output
# there is a tag with a decendant 'li' tag
assert_tag :descendant => { :tag => "li" }
# there is no tag with a descendant 'html' tag
assert_no_tag :descendant => { :tag => "html" }
end
def test_assert_tag_sibling
process :test_html_output
# there is a tag with a sibling of class 'item'
assert_tag :sibling => { :attributes => { :class => "item" } }
# there is no tag with a sibling 'ul' tag
assert_no_tag :sibling => { :tag => "ul" }
end
def test_assert_tag_after
process :test_html_output
# there is a tag following a sibling 'div' tag
assert_tag :after => { :tag => "div" }
# there is no tag following a sibling tag with id 'bar'
assert_no_tag :after => { :attributes => { :id => "bar" } }
end
def test_assert_tag_before
process :test_html_output
# there is a tag preceeding a tag with id 'bar'
assert_tag :before => { :attributes => { :id => "bar" } }
# there is no tag preceeding a 'form' tag
assert_no_tag :before => { :tag => "form" }
end
def test_assert_tag_children_count
process :test_html_output
# there is a tag with 2 children
assert_tag :children => { :count => 2 }
# there is no tag with 4 children
assert_no_tag :children => { :count => 4 }
end
def test_assert_tag_children_less_than
process :test_html_output
# there is a tag with less than 5 children
assert_tag :children => { :less_than => 5 }
# there is no 'ul' tag with less than 2 children
assert_no_tag :children => { :less_than => 2 }, :tag => "ul"
end
def test_assert_tag_children_greater_than
process :test_html_output
# there is a 'body' tag with more than 1 children
assert_tag :children => { :greater_than => 1 }, :tag => "body"
# there is no tag with more than 10 children
assert_no_tag :children => { :greater_than => 10 }
end
def test_assert_tag_children_only
process :test_html_output
# there is a tag containing only one child with an id of 'foo'
assert_tag :children => { :count => 1,
:only => { :attributes => { :id => "foo" } } }
# there is no tag containing only one 'li' child
assert_no_tag :children => { :count => 1, :only => { :tag => "li" } }
end
def test_assert_tag_content
process :test_html_output
# the output contains the string "Name"
assert_tag :content => "Name"
# the output does not contain the string "test"
assert_no_tag :content => "test"
end
def test_assert_tag_multiple
process :test_html_output
# there is a 'div', id='bar', with an immediate child whose 'action'
# attribute matches the regexp /somewhere/.
assert_tag :tag => "div", :attributes => { :id => "bar" },
:child => { :attributes => { :action => /somewhere/ } }
# there is no 'div', id='foo', with a 'ul' child with more than
# 2 "li" children.
assert_no_tag :tag => "div", :attributes => { :id => "foo" },
:child => {
:tag => "ul",
:children => { :greater_than => 2,
:only => { :tag => "li" } } }
end
def test_assert_tag_children_without_content
process :test_html_output
# there is a form tag with an 'input' child which is a self closing tag
assert_tag :tag => "form",
:children => { :count => 1,
:only => { :tag => "input" } }
# the body tag has an 'a' child which in turn has an 'img' child
assert_tag :tag => "body",
:children => { :count => 1,
:only => { :tag => "a",
:children => { :count => 1,
:only => { :tag => "img" } } } }
end
def test_assert_generates
assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
end
def test_assert_routing
assert_routing 'content', :controller => 'content', :action => 'index'
end
def test_assert_routing_in_module
assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
end
def test_params_passing
get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
parsed_params = eval(@response.body)
assert_equal(
{'controller' => 'test_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
parsed_params
)
end
def test_id_converted_to_string
get :test_params, :id => 20, :foo => Object.new
assert_kind_of String, @request.path_parameters['id']
end
def test_array_path_parameter_handled_properly
with_routing do |set|
set.draw do
set.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params'
set.connect ':controller/:action/:id'
end
get :test_params, :path => ['hello', 'world']
assert_equal ['hello', 'world'], @request.path_parameters['path']
assert_equal 'hello/world', @request.path_parameters['path'].to_s
end
end
def test_assert_realistic_path_parameters
get :test_params, :id => 20, :foo => Object.new
# All elements of path_parameters should use string keys
@request.path_parameters.keys.each do |key|
assert_kind_of String, key
end
end
def test_with_routing_places_routes_back
assert ActionController::Routing::Routes
routes_id = ActionController::Routing::Routes.object_id
begin
with_routing { raise 'fail' }
fail 'Should not be here.'
rescue RuntimeError
end
assert ActionController::Routing::Routes
assert_equal routes_id, ActionController::Routing::Routes.object_id
end
def test_remote_addr
get :test_remote_addr
assert_equal "0.0.0.0", @response.body
@request.remote_addr = "192.0.0.1"
get :test_remote_addr
assert_equal "192.0.0.1", @response.body
end
def test_header_properly_reset_after_remote_http_request
xhr :get, :test_params
assert_nil @request.env['HTTP_X_REQUESTED_WITH']
end
def test_header_properly_reset_after_get_request
get :test_params
@request.recycle!
assert_nil @request.instance_variable_get("@request_method")
end
%w(controller response request).each do |variable|
%w(get post put delete head process).each do |method|
define_method("test_#{variable}_missing_for_#{method}_raises_error") do
remove_instance_variable "@#{variable}"
begin
send(method, :test_remote_addr)
assert false, "expected RuntimeError, got nothing"
rescue RuntimeError => error
assert true
assert_match %r{@#{variable} is nil}, error.message
rescue => error
assert false, "expected RuntimeError, got #{error.class}"
end
end
end
end
FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
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
end
end

View file

@ -0,0 +1,46 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class UrlRewriterTests < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@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'
@params[:action] = 'bye'
@params[:id] = '2'
assert_equal '/hi/hi/2', @rewriter.rewrite(:only_path => true, :overwrite_params => {:action => 'hi'})
u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:action => 'hi'})
assert_match %r(/hi/hi/2$), u
end
private
def split_query_string(str)
[str[0].chr] + str[1..-1].split(/&/).sort
end
def assert_query_equal(q1, q2)
assert_equal(split_query_string(q1), split_query_string(q2))
end
end

View file

@ -0,0 +1,225 @@
require File.dirname(__FILE__) + '/../abstract_unit'
class VerificationTest < Test::Unit::TestCase
class TestController < ActionController::Base
verify :only => :guarded_one, :params => "one",
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_two, :params => %w( one two ),
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_with_flash, :params => "one",
:add_flash => { "notice" => "prereqs failed" },
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_in_session, :session => "one",
:redirect_to => { :action => "unguarded" }
verify :only => [:multi_one, :multi_two], :session => %w( one two ),
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_by_method, :method => :post,
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_by_xhr, :xhr => true,
:redirect_to => { :action => "unguarded" }
verify :only => :guarded_by_not_xhr, :xhr => false,
:redirect_to => { :action => "unguarded" }
before_filter :unconditional_redirect, :only => :two_redirects
verify :only => :two_redirects, :method => :post,
:redirect_to => { :action => "unguarded" }
verify :only => :must_be_post, :method => :post, :render => { :status => 500, :text => "Must be post"}
def guarded_one
render :text => "#{@params["one"]}"
end
def guarded_with_flash
render :text => "#{@params["one"]}"
end
def guarded_two
render :text => "#{@params["one"]}:#{@params["two"]}"
end
def guarded_in_session
render :text => "#{@session["one"]}"
end
def multi_one
render :text => "#{@session["one"]}:#{@session["two"]}"
end
def multi_two
render :text => "#{@session["two"]}:#{@session["one"]}"
end
def guarded_by_method
render :text => "#{@request.method}"
end
def guarded_by_xhr
render :text => "#{@request.xhr?}"
end
def guarded_by_not_xhr
render :text => "#{@request.xhr?}"
end
def unguarded
render :text => "#{@params["one"]}"
end
def two_redirects
render :nothing => true
end
def must_be_post
render :text => "Was a post!"
end
protected
def rescue_action(e) raise end
def unconditional_redirect
redirect_to :action => "unguarded"
end
end
def setup
@controller = TestController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_guarded_one_with_prereqs
get :guarded_one, :one => "here"
assert_equal "here", @response.body
end
def test_guarded_one_without_prereqs
get :guarded_one
assert_redirected_to :action => "unguarded"
end
def test_guarded_with_flash_with_prereqs
get :guarded_with_flash, :one => "here"
assert_equal "here", @response.body
assert_flash_empty
end
def test_guarded_with_flash_without_prereqs
get :guarded_with_flash
assert_redirected_to :action => "unguarded"
assert_flash_equal "prereqs failed", "notice"
end
def test_guarded_two_with_prereqs
get :guarded_two, :one => "here", :two => "there"
assert_equal "here:there", @response.body
end
def test_guarded_two_without_prereqs_one
get :guarded_two, :two => "there"
assert_redirected_to :action => "unguarded"
end
def test_guarded_two_without_prereqs_two
get :guarded_two, :one => "here"
assert_redirected_to :action => "unguarded"
end
def test_guarded_two_without_prereqs_both
get :guarded_two
assert_redirected_to :action => "unguarded"
end
def test_unguarded_with_params
get :unguarded, :one => "here"
assert_equal "here", @response.body
end
def test_unguarded_without_params
get :unguarded
assert_equal "", @response.body
end
def test_guarded_in_session_with_prereqs
get :guarded_in_session, {}, "one" => "here"
assert_equal "here", @response.body
end
def test_guarded_in_session_without_prereqs
get :guarded_in_session
assert_redirected_to :action => "unguarded"
end
def test_multi_one_with_prereqs
get :multi_one, {}, "one" => "here", "two" => "there"
assert_equal "here:there", @response.body
end
def test_multi_one_without_prereqs
get :multi_one
assert_redirected_to :action => "unguarded"
end
def test_multi_two_with_prereqs
get :multi_two, {}, "one" => "here", "two" => "there"
assert_equal "there:here", @response.body
end
def test_multi_two_without_prereqs
get :multi_two
assert_redirected_to :action => "unguarded"
end
def test_guarded_by_method_with_prereqs
post :guarded_by_method
assert_equal "post", @response.body
end
def test_guarded_by_method_without_prereqs
get :guarded_by_method
assert_redirected_to :action => "unguarded"
end
def test_guarded_by_xhr_with_prereqs
xhr :post, :guarded_by_xhr
assert_equal "true", @response.body
end
def test_guarded_by_xhr_without_prereqs
get :guarded_by_xhr
assert_redirected_to :action => "unguarded"
end
def test_guarded_by_not_xhr_with_prereqs
get :guarded_by_not_xhr
assert_equal "false", @response.body
end
def test_guarded_by_not_xhr_without_prereqs
xhr :post, :guarded_by_not_xhr
assert_redirected_to :action => "unguarded"
end
def test_guarded_post_and_calls_render_succeeds
post :must_be_post
assert_equal "Was a post!", @response.body
end
def test_guarded_post_and_calls_render_fails
get :must_be_post
assert_response 500
assert_equal "Must be post", @response.body
end
def test_second_redirect
assert_nothing_raised { get :two_redirects }
end
end

View file

@ -0,0 +1,255 @@
require File.dirname(__FILE__) + '/../abstract_unit'
require 'stringio'
class WebServiceTest < Test::Unit::TestCase
class MockCGI < CGI #:nodoc:
attr_accessor :stdinput, :stdoutput, :env_table
def initialize(env, data = '')
self.env_table = env
self.stdinput = StringIO.new(data)
self.stdoutput = StringIO.new
super()
end
end
class TestController < ActionController::Base
session :off
def assign_parameters
if params[:full]
render :text => dump_params_keys
else
render :text => (params.keys - ['controller', 'action']).sort.join(", ")
end
end
def dump_params_keys(hash=params)
hash.keys.sort.inject("") do |s, k|
value = hash[k]
value = Hash === value ? "(#{dump_params_keys(value)})" : ""
s << ", " unless s.empty?
s << "#{k}#{value}"
end
end
def rescue_action(e) raise end
end
def setup
@controller = TestController.new
ActionController::Base.param_parsers.clear
ActionController::Base.param_parsers[Mime::XML] = :xml_node
end
def test_check_parameters
process('GET')
assert_equal '', @controller.response.body
end
def test_post_xml
process('POST', 'application/xml', '<entry attributed="true"><summary>content...</summary></entry>')
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'content...', @controller.params["entry"].summary.node_value
assert_equal 'true', @controller.params["entry"]['attributed']
end
def test_put_xml
process('PUT', 'application/xml', '<entry attributed="true"><summary>content...</summary></entry>')
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'content...', @controller.params["entry"].summary.node_value
assert_equal 'true', @controller.params["entry"]['attributed']
end
def test_register_and_use_yaml
ActionController::Base.param_parsers[Mime::YAML] = Proc.new { |d| YAML.load(d) }
process('POST', 'application/x-yaml', {"entry" => "loaded from yaml"}.to_yaml)
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'loaded from yaml', @controller.params["entry"]
end
def test_register_and_use_yaml_as_symbol
ActionController::Base.param_parsers[Mime::YAML] = :yaml
process('POST', 'application/x-yaml', {"entry" => "loaded from yaml"}.to_yaml)
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
assert_equal 'loaded from yaml', @controller.params["entry"]
end
def test_register_and_use_xml_simple
ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) }
process('POST', 'application/xml', '<request><summary>content...</summary><title>SimpleXml</title></request>' )
assert_equal 'summary, title', @controller.response.body
assert @controller.params.has_key?(:summary)
assert @controller.params.has_key?(:title)
assert_equal 'content...', @controller.params["summary"]
assert_equal 'SimpleXml', @controller.params["title"]
end
def test_use_xml_ximple_with_empty_request
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
assert_nothing_raised { process('POST', 'application/xml', "") }
assert_equal "", @controller.response.body
end
def test_deprecated_request_methods
process('POST', 'application/x-yaml')
assert_equal Mime::YAML, @controller.request.content_type
assert_equal true, @controller.request.post?
assert_equal :yaml, @controller.request.post_format
assert_equal true, @controller.request.yaml_post?
assert_equal false, @controller.request.xml_post?
end
def test_dasherized_keys_as_xml
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
process('POST', 'application/xml', "<first-key>\n<sub-key>...</sub-key>\n</first-key>", 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_xml
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
process('POST', 'application/xml', <<-XML)
<data>
<a type="integer">15</a>
<b type="boolean">false</b>
<c type="boolean">true</c>
<d type="date">2005-03-17</d>
<e type="datetime">2005-03-17T21:41:07Z</e>
<f>unparsed</f>
<g type="integer">1</g>
<g>hello</g>
<g type="date">1974-07-25</g>
</data>
XML
params = @controller.params
assert_equal 15, params[:data][:a]
assert_equal false, params[:data][:b]
assert_equal true, params[:data][:c]
assert_equal Date.new(2005,3,17), params[:data][:d]
assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e]
assert_equal "unparsed", params[:data][:f]
assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g]
end
def test_entities_unescaped_as_xml_simple
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
process('POST', 'application/xml', <<-XML)
<data>&lt;foo &quot;bar&apos;s&quot; &amp; friends&gt;</data>
XML
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)
---
data:
a: 15
b: false
c: true
d: 2005-03-17
e: 2005-03-17T21:41:07Z
f: unparsed
g:
- 1
- hello
- 1974-07-25
YAML
params = @controller.params
assert_equal 15, params[:data][:a]
assert_equal false, params[:data][:b]
assert_equal true, params[:data][:c]
assert_equal Date.new(2005,3,17), params[:data][:d]
assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e]
assert_equal "unparsed", params[:data][:f]
assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g]
end
private
def process(verb, content_type = 'application/x-www-form-urlencoded', data = '', full=false)
cgi = MockCGI.new({
'REQUEST_METHOD' => verb,
'CONTENT_TYPE' => content_type,
'QUERY_STRING' => "action=assign_parameters&controller=webservicetest/test#{"&full=1" if full}",
"REQUEST_URI" => "/",
"HTTP_HOST" => 'testdomain.com',
"CONTENT_LENGTH" => data.size,
"SERVER_PORT" => "80",
"HTTPS" => "off"}, data)
@controller.send(:process, ActionController::CgiRequest.new(cgi, {}), ActionController::CgiResponse.new(cgi))
end
end
class XmlNodeTest < Test::Unit::TestCase
def test_all
xn = XmlNode.from_xml(%{<?xml version="1.0" encoding="UTF-8"?>
<response success='true'>
<page title='Ajax Summit' id='1133' email_address='ry87ib@backpackit.com'>
<description>With O'Reilly and Adaptive Path</description>
<notes>
<note title='Hotel' id='1020' created_at='2005-05-14 16:41:11'>
Staying at the Savoy
</note>
</notes>
<tags>
<tag name='Technology' id='4' />
<tag name='Travel' id='5' />
</tags>
</page>
</response>
}
)
assert_equal 'UTF-8', xn.node.document.encoding
assert_equal '1.0', xn.node.document.version
assert_equal 'true', xn['success']
assert_equal 'response', xn.node_name
assert_equal 'Ajax Summit', xn.page['title']
assert_equal '1133', xn.page['id']
assert_equal "With O'Reilly and Adaptive Path", xn.page.description.node_value
assert_equal nil, xn.nonexistent
assert_equal "Staying at the Savoy", xn.page.notes.note.node_value.strip
assert_equal 'Technology', xn.page.tags.tag[0]['name']
assert_equal 'Travel', xn.page.tags.tag[1][:name]
matches = xn.xpath('//@id').map{ |id| id.to_i }
assert_equal [4, 5, 1020, 1133], matches.sort
matches = xn.xpath('//tag').map{ |tag| tag['name'] }
assert_equal ['Technology', 'Travel'], matches.sort
assert_equal "Ajax Summit", xn.page['title']
xn.page['title'] = 'Ajax Summit V2'
assert_equal "Ajax Summit V2", xn.page['title']
assert_equal "Staying at the Savoy", xn.page.notes.note.node_value.strip
xn.page.notes.note.node_value = "Staying at the Ritz"
assert_equal "Staying at the Ritz", xn.page.notes.note.node_value.strip
assert_equal '5', xn.page.tags.tag[1][:id]
xn.page.tags.tag[1]['id'] = '7'
assert_equal '7', xn.page.tags.tag[1]['id']
end
def test_small_entry
node = XmlNode.from_xml('<entry>hi</entry>')
assert_equal 'hi', node.node_value
end
end