test_test.rb 17.6 KB
Newer Older
1 2
require "#{File.dirname(__FILE__)}/../abstract_unit"
require "#{File.dirname(__FILE__)}/fake_controllers"
3 4 5 6 7

class TestTest < Test::Unit::TestCase
  class TestController < ActionController::Base
    def set_flash
      flash["test"] = ">#{flash["test"]}<"
8
      render :text => 'ignore me'
9
    end
10

11 12 13 14 15
    def render_raw_post
      raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank?
      render :text => request.raw_post
    end

16 17 18 19
    def render_body
      render :text => request.body.read
    end

20 21
    def test_params
      render :text => params.inspect
22 23
    end

24
    def test_uri
25
      render :text => request.request_uri
26
    end
27

28 29 30 31
    def test_query_string
      render :text => request.query_string
    end

32
    def test_html_output
33
      render :text => <<HTML
34 35
<html>
  <body>
36
    <a href="/"><img src="/images/button.png" /></a>
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    <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
52 53 54 55 56 57 58 59 60 61
    
    def test_xml_output
      response.content_type = "application/xml"
      render :text => <<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <area>area is an empty tag in HTML, raising an error if not in xml mode</area>
</root>
XML
    end
62

63
    def test_only_one_param
64 65 66 67 68
      render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
    end

    def test_remote_addr
      render :text => (request.remote_addr || "not specified")
69
    end
70

71 72 73
    def test_file_upload
      render :text => params[:file].size
    end
74

75 76 77 78 79 80 81 82
    def redirect_to_same_controller
      redirect_to :controller => 'test', :action => 'test_uri', :id => 5
    end

    def redirect_to_different_controller
      redirect_to :controller => 'fail', :id => 5
    end

83
    def create
J
Jeremy Kemper 已提交
84
      head :created, :location => 'created resource'
85 86
    end

87 88 89 90 91 92 93 94
    private
      def rescue_action(e)
        raise e
      end

      def generate_url(opts)
        url_for(opts.merge(:action => "test_uri"))
      end
95 96 97 98 99 100
  end

  def setup
    @controller = TestController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
101
    ActionController::Routing::Routes.reload
102
    ActionController::Routing.use_controllers! %w(content admin/user test_test/test)
103 104 105 106
  end

  def teardown
    ActionController::Routing::Routes.reload
107 108
  end

109 110
  def test_raw_post_handling
    params = {:page => {:name => 'page name'}, 'some key' => 123}
111
    post :render_raw_post, params.dup
112

113 114 115 116 117 118
    assert_equal params.to_query, @response.body
  end

  def test_body_stream
    params = { :page => { :name => 'page name' }, 'some key' => 123 }

119
    post :render_body, params.dup
120 121

    assert_equal params.to_query, @response.body
122 123
  end

124 125
  def test_process_without_flash
    process :set_flash
126
    assert_equal '><', flash['test']
127 128
  end

129 130
  def test_process_with_flash
    process :set_flash, nil, nil, { "test" => "value" }
131
    assert_equal '>value<', flash['test']
132
  end
133 134 135

  def test_process_with_request_uri_with_no_params
    process :test_uri
136
    assert_equal "/test_test/test/test_uri", @response.body
137 138 139 140
  end

  def test_process_with_request_uri_with_params
    process :test_uri, :id => 7
141
    assert_equal "/test_test/test/test_uri/7", @response.body
142 143 144 145 146
  end

  def test_process_with_request_uri_with_params_with_explicit_uri
    @request.set_REQUEST_URI "/explicit/uri"
    process :test_uri, :id => 7
147
    assert_equal "/explicit/uri", @response.body
148 149
  end

150 151 152 153 154 155 156 157 158 159 160
  def test_process_with_query_string
    process :test_query_string, :q => 'test'
    assert_equal "q=test", @response.body
  end

  def test_process_with_query_string_with_explicit_uri
    @request.set_REQUEST_URI "/explicit/uri?q=test?extra=question"
    process :test_query_string
    assert_equal "q=test?extra=question", @response.body
  end

161
  def test_multiple_calls
162 163
    process :test_only_one_param, :left => true
    assert_equal "OK", @response.body
164
    process :test_only_one_param, :right => true
165
    assert_equal "OK", @response.body
166
  end
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  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" }
200 201
    # there is no tag with a child 'strong' tag
    assert_no_tag :child => { :tag => "strong" }
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  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

243
    # there is a tag preceding a tag with id 'bar'
244
    assert_tag :before => { :attributes => { :id => "bar" } }
245
    # there is no tag preceding a 'form' tag
246 247 248 249 250 251 252 253
    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 }
254 255
    # in particular, there is a <ul> tag with two children (a nameless pair of <li>s)
    assert_tag :tag => 'ul', :children => { :count => 2 }
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    # 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'
282
    assert_tag :children => { :count => 1,
283 284 285 286 287 288 289 290 291
                              :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"
292
    assert_tag :content => /Name/
293
    # the output does not contain the string "test"
294
    assert_no_tag :content => /test/
295
  end
296

297
  def test_assert_tag_multiple
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    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
313

314 315
  def test_assert_tag_children_without_content
    process :test_html_output
316

317 318 319 320 321 322 323 324 325 326 327 328
    # 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
329 330 331 332 333 334 335 336 337 338 339 340 341 342
  
  def test_should_not_impose_childless_html_tags_in_xml
    process :test_xml_output

    begin
      $stderr = StringIO.new
      assert_select 'area' #This will cause a warning if content is processed as HTML
      $stderr.rewind && err = $stderr.read
    ensure
      $stderr = STDERR
    end

    assert err.empty?
  end
343

344 345 346 347 348 349 350 351 352 353
  def test_assert_tag_attribute_matching
    @response.body = '<input type="text" name="my_name">'
    assert_tag :tag => 'input',
                 :attributes => { :name => /my/, :type => 'text' }
    assert_no_tag :tag => 'input',
                 :attributes => { :name => 'my', :type => 'text' }
    assert_no_tag :tag => 'input',
                 :attributes => { :name => /^my$/, :type => 'text' }
  end

354 355 356 357 358 359 360
  def test_assert_tag_content_matching
    @response.body = "<p>hello world</p>"
    assert_tag :tag => "p", :content => "hello world"
    assert_tag :tag => "p", :content => /hello/
    assert_no_tag :tag => "p", :content => "hello"
  end

361
  def test_assert_generates
362
    assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
363 364 365 366
    assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action"}
    assert_generates 'controller/action/5', {:controller => "controller", :action => "action", :id => "5", :name => "bob"}, {}, {:name => "bob"}
    assert_generates 'controller/action/7', {:id => "7", :name => "bob"}, {:controller => "controller", :action => "action"}, {:name => "bob"}
    assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action", :name => "bob"}, {}
367
  end
368

369 370 371 372 373 374 375 376
  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

377 378 379 380 381 382 383 384 385 386
  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

387
  def test_id_converted_to_string
388
    get :test_params, :id => 20, :foo => Object.new
389 390 391 392 393
    assert_kind_of String, @request.path_parameters['id']
  end

  def test_array_path_parameter_handled_properly
    with_routing do |set|
394 395 396
      set.draw do |map|
        map.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params'
        map.connect ':controller/:action/:id'
397
      end
398

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
      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
417

418 419 420 421
    begin
      with_routing { raise 'fail' }
      fail 'Should not be here.'
    rescue RuntimeError
422
    end
423

424 425
    assert ActionController::Routing::Routes
    assert_equal routes_id, ActionController::Routing::Routes.object_id
426
  end
427 428 429 430 431 432 433 434 435

  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
436

437 438 439 440 441
  def test_header_properly_reset_after_remote_http_request
    xhr :get, :test_params
    assert_nil @request.env['HTTP_X_REQUESTED_WITH']
  end

442 443 444 445 446 447
   def test_header_properly_reset_after_get_request
    get :test_params
    @request.recycle!
    assert_nil @request.instance_variable_get("@request_method")
  end

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  %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
464

465
  FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
466

467 468 469 470
  def test_test_uploaded_file
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
471

472 473 474 475 476 477
    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
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  
  def test_test_uploaded_file_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
    
    binary_uploaded_file = ActionController::TestUploadedFile.new(path, content_type, :binary)
    assert_equal File.open(path, 'rb').read, binary_uploaded_file.read
    
    plain_uploaded_file = ActionController::TestUploadedFile.new(path, content_type)
    assert_equal File.open(path, 'r').read, plain_uploaded_file.read
  end

  def test_fixture_file_upload_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/jpg'
    
    binary_file_upload = fixture_file_upload(path, content_type, :binary)
    assert_equal File.open(path, 'rb').read, binary_file_upload.read
    
    plain_file_upload = fixture_file_upload(path, content_type)
    assert_equal File.open(path, 'r').read, plain_file_upload.read
  end
502

503 504
  def test_fixture_file_upload
    post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
J
Jeremy Kemper 已提交
505
    assert_equal '159528', @response.body
506
  end
507

508 509 510
  def test_test_uploaded_file_exception_when_file_doesnt_exist
    assert_raise(RuntimeError) { ActionController::TestUploadedFile.new('non_existent_file') }
  end
511

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  def test_assert_follow_redirect_to_same_controller
    with_foo_routing do |set|
      get :redirect_to_same_controller
      assert_response :redirect
      assert_redirected_to :controller => 'test_test/test', :action => 'test_uri', :id => 5
      assert_nothing_raised { follow_redirect }
    end
  end

  def test_assert_follow_redirect_to_different_controller
    with_foo_routing do |set|
      get :redirect_to_different_controller
      assert_response :redirect
      assert_redirected_to :controller => 'fail', :id => 5
      assert_raise(RuntimeError) { follow_redirect }
    end
  end

530 531 532 533 534 535 536 537 538 539 540 541 542 543
  def test_redirect_url_only_cares_about_location_header
    get :create
    assert_response :created

    # Redirect url doesn't care that it wasn't a :redirect response.
    assert_equal 'created resource', @response.redirect_url
    assert_equal @response.redirect_url, redirect_to_url

    # Must be a :redirect response.
    assert_raise(Test::Unit::AssertionFailedError) do
      assert_redirected_to 'created resource'
    end
  end

544 545 546
  protected
    def with_foo_routing
      with_routing do |set|
547 548 549
        set.draw do |map|
          map.generate_url 'foo', :controller => 'test'
          map.connect      ':controller/:action/:id'
550 551 552 553
        end
        yield set
      end
    end
554
end
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582


class CleanBacktraceTest < Test::Unit::TestCase
  def test_should_reraise_the_same_object
    exception = Test::Unit::AssertionFailedError.new('message')
    clean_backtrace { raise exception }
  rescue => caught
    assert_equal exception.object_id, caught.object_id
    assert_equal exception.message, caught.message
  end

  def test_should_clean_assertion_lines_from_backtrace
    path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller")
    exception = Test::Unit::AssertionFailedError.new('message')
    exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
    clean_backtrace { raise exception }
  rescue => caught
    assert_equal ["#{path}/abc"], caught.backtrace
  end

  def test_should_only_clean_assertion_failure_errors
    clean_backtrace do
      raise "can't touch this", [File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/assertions/abc")]
    end
  rescue => caught
    assert !caught.backtrace.empty?
  end
end