test_case_test.rb 28.7 KB
Newer Older
1 2
require 'abstract_unit'
require 'controller/fake_controllers'
3
require 'active_support/json/decoding'
4

5
class TestCaseTest < ActionController::TestCase
6
  class TestController < ActionController::Base
7 8 9 10
    def no_op
      render :text => 'dummy'
    end

11 12
    def set_flash
      flash["test"] = ">#{flash["test"]}<"
13
      render :text => 'ignore me'
14
    end
15

16 17 18 19 20
    def set_flash_now
      flash.now["test_now"] = ">#{flash["test_now"]}<"
      render :text => 'ignore me'
    end

21 22 23 24 25 26
    def set_session
      session['string'] = 'A wonder'
      session[:symbol] = 'it works'
      render :text => 'Success'
    end

27 28 29 30 31
    def reset_the_session
      reset_session
      render :text => 'ignore me'
    end

32
    def render_raw_post
33
      raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
34 35 36
      render :text => request.raw_post
    end

37 38 39 40
    def render_body
      render :text => request.body.read
    end

41 42
    def test_params
      render :text => params.inspect
43 44
    end

45
    def test_uri
46
      render :text => request.fullpath
47
    end
48

49 50 51 52
    def test_format
      render :text => request.format
    end

53 54 55 56
    def test_query_string
      render :text => request.query_string
    end

A
Andrew White 已提交
57 58 59 60
    def test_protocol
      render :text => request.protocol
    end

61
    def test_headers
62
      render text: request.headers.env.to_json
63 64
    end

65
    def test_html_output
66
      render :text => <<HTML
67 68
<html>
  <body>
69
    <a href="/"><img src="/images/button.png" /></a>
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    <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
J
Joshua Peek 已提交
85

86 87 88 89 90 91 92 93 94
    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
95

96
    def test_only_one_param
97 98 99 100 101
      render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
    end

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

104 105 106
    def test_file_upload
      render :text => params[:file].size
    end
107

108 109 110 111
    def test_send_file
      send_file(File.expand_path(__FILE__))
    end

112 113 114 115 116 117 118 119
    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

120
    def create
J
Jeremy Kemper 已提交
121
      head :created, :location => 'created resource'
122 123
    end

124 125 126 127 128
    def delete_cookie
      cookies.delete("foo")
      render :nothing => true
    end

129 130
    def test_assigns
      @foo = "foo"
131
      @foo_hash = {:foo => :bar}
132 133 134
      render :nothing => true
    end

135 136 137 138 139
    private

      def generate_url(opts)
        url_for(opts.merge(:action => "test_uri"))
      end
140 141 142
  end

  def setup
143
    super
144 145 146
    @controller = TestController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
C
Carl Lerche 已提交
147
    @request.env['PATH_INFO'] = nil
148 149
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
150
        get ':controller(/:action(/:id))'
151 152
      end
    end
153 154
  end

155 156 157 158 159 160 161 162 163 164 165
  class ViewAssignsController < ActionController::Base
    def test_assigns
      @foo = "foo"
      render :nothing => true
    end

    def view_assigns
      { "bar" => "bar" }
    end
  end

166
  def test_raw_post_handling
167
    params = Hash[:page, {:name => 'page name'}, 'some key', 123]
168
    post :render_raw_post, params.dup
169

170 171 172 173
    assert_equal params.to_query, @response.body
  end

  def test_body_stream
174
    params = Hash[:page, { :name => 'page name' }, 'some key', 123]
175

176
    post :render_body, params.dup
177 178

    assert_equal params.to_query, @response.body
179
  end
180

181 182
  def test_document_body_and_params_with_post
    post :test_params, :id => 1
183
    assert_equal("{\"id\"=>\"1\", \"controller\"=>\"test_case_test/test\", \"action\"=>\"test_params\"}", @response.body)
184
  end
185

186 187 188 189
  def test_document_body_with_post
    post :render_body, "document body"
    assert_equal "document body", @response.body
  end
190

191 192 193 194
  def test_document_body_with_put
    put :render_body, "document body"
    assert_equal "document body", @response.body
  end
195

196 197 198 199 200
  def test_head
    head :test_params
    assert_equal 200, @response.status
  end

201 202 203 204
  def test_head_params_as_sting
    assert_raise(NoMethodError) { head :test_params, "document body", :id => 10 }
  end

205 206
  def test_process_without_flash
    process :set_flash
207
    assert_equal '><', flash['test']
208 209
  end

210
  def test_process_with_flash
211
    process :set_flash, "GET", nil, nil, { "test" => "value" }
212
    assert_equal '>value<', flash['test']
213
  end
214

215
  def test_process_with_flash_now
216
    process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" }
217 218 219
    assert_equal '>value_now<', flash['test_now']
  end

220 221 222 223 224 225 226 227 228
  def test_process_with_session
    process :set_session
    assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
    assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access"
    assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access"
    assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
  end

  def test_process_with_session_arg
229
    process :no_op, "GET", nil, { 'string' => 'value1', :symbol => 'value2' }
230 231 232 233 234 235
    assert_equal 'value1', session['string']
    assert_equal 'value1', session[:string]
    assert_equal 'value2', session['symbol']
    assert_equal 'value2', session[:symbol]
  end

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  def test_process_merges_session_arg
    session[:foo] = 'bar'
    get :no_op, nil, { :bar => 'baz' }
    assert_equal 'bar', session[:foo]
    assert_equal 'baz', session[:bar]
  end

  def test_merged_session_arg_is_retained_across_requests
    get :no_op, nil, { :foo => 'bar' }
    assert_equal 'bar', session[:foo]
    get :no_op
    assert_equal 'bar', session[:foo]
  end

  def test_process_overwrites_existing_session_arg
    session[:foo] = 'bar'
    get :no_op, nil, { :foo => 'baz' }
    assert_equal 'baz', session[:foo]
  end

256 257 258 259 260 261 262 263 264 265 266 267
  def test_session_is_cleared_from_controller_after_reset_session
    process :set_session
    process :reset_the_session
    assert_equal Hash.new, @controller.session.to_hash
  end

  def test_session_is_cleared_from_request_after_reset_session
    process :set_session
    process :reset_the_session
    assert_equal Hash.new, @request.session.to_hash
  end

268 269 270 271 272 273
  def test_response_and_request_have_nice_accessors
    process :no_op
    assert_equal @response, response
    assert_equal @request, request
  end

274 275
  def test_process_with_request_uri_with_no_params
    process :test_uri
276
    assert_equal "/test_case_test/test/test_uri", @response.body
277 278 279
  end

  def test_process_with_request_uri_with_params
280
    process :test_uri, "GET", :id => 7
281
    assert_equal "/test_case_test/test/test_uri/7", @response.body
282
  end
283

284
  def test_process_with_request_uri_with_params_with_explicit_uri
C
Carl Lerche 已提交
285
    @request.env['PATH_INFO'] = "/explicit/uri"
286
    process :test_uri, "GET", :id => 7
287
    assert_equal "/explicit/uri", @response.body
288 289
  end

290
  def test_process_with_query_string
291
    process :test_query_string, "GET", :q => 'test'
292 293 294 295
    assert_equal "q=test", @response.body
  end

  def test_process_with_query_string_with_explicit_uri
C
Carl Lerche 已提交
296 297
    @request.env['PATH_INFO'] = '/explicit/uri'
    @request.env['QUERY_STRING'] = 'q=test?extra=question'
298 299 300 301
    process :test_query_string
    assert_equal "q=test?extra=question", @response.body
  end

302
  def test_multiple_calls
303
    process :test_only_one_param, "GET", :left => true
304
    assert_equal "OK", @response.body
305
    process :test_only_one_param, "GET", :right => true
306
    assert_equal "OK", @response.body
307
  end
308

309 310 311 312 313 314 315 316 317
  def test_assigns
    process :test_assigns
    # assigns can be accessed using assigns(key)
    # or assigns[key], where key is a string or
    # a symbol
    assert_equal "foo", assigns(:foo)
    assert_equal "foo", assigns("foo")
    assert_equal "foo", assigns[:foo]
    assert_equal "foo", assigns["foo"]
318 319 320 321

    # but the assigned variable should not have its own keys stringified
    expected_hash = { :foo => :bar }
    assert_equal expected_hash, assigns(:foo_hash)
322 323
  end

324 325 326 327 328 329 330 331 332
  def test_view_assigns
    @controller = ViewAssignsController.new
    process :test_assigns
    assert_equal nil, assigns(:foo)
    assert_equal nil, assigns[:foo]
    assert_equal "bar", assigns(:bar)
    assert_equal "bar", assigns[:bar]
  end

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  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" }
365 366
    # there is no tag with a child 'strong' tag
    assert_no_tag :child => { :tag => "strong" }
367 368 369 370 371 372 373 374 375 376 377 378 379 380
  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

381
    # there is a tag with a descendant 'li' tag
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    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

408
    # there is a tag preceding a tag with id 'bar'
409
    assert_tag :before => { :attributes => { :id => "bar" } }
410
    # there is no tag preceding a 'form' tag
411 412 413 414 415 416 417 418
    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 }
419 420
    # in particular, there is a <ul> tag with two children (a nameless pair of <li>s)
    assert_tag :tag => 'ul', :children => { :count => 2 }
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    # 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'
447
    assert_tag :children => { :count => 1,
448 449 450 451 452 453 454 455 456
                              :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"
457
    assert_tag :content => /Name/
458
    # the output does not contain the string "test"
459
    assert_no_tag :content => /test/
460
  end
461

462
  def test_assert_tag_multiple
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    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
478

479 480
  def test_assert_tag_children_without_content
    process :test_html_output
481

482 483 484 485 486 487 488 489 490 491 492 493
    # 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
J
Joshua Peek 已提交
494

495 496 497 498 499 500 501 502 503 504 505 506 507
  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
508

509 510 511 512 513 514 515 516 517 518
  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

519 520 521 522 523 524 525
  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

526
  def test_assert_generates
527
    assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
528 529 530 531
    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"}, {}
532
  end
533

534 535 536 537
  def test_assert_routing
    assert_routing 'content', :controller => 'content', :action => 'index'
  end

538 539
  def test_assert_routing_with_method
    with_routing do |set|
540
      set.draw { resources(:content) }
541 542 543 544
      assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
    end
  end

545
  def test_assert_routing_in_module
546 547 548
    with_routing do |set|
      set.draw do
        namespace :admin do
549
          get 'user' => 'user#index'
550 551 552 553 554
        end
      end

      assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
    end
555
  end
556

557 558
  def test_assert_routing_with_glob
    with_routing do |set|
559
      set.draw { get('*path' => "pages#show") }
560 561 562
      assert_routing('/company/about', { :controller => 'pages', :action => 'show', :path => 'company/about' })
    end
  end
563

564 565 566 567
  def test_params_passing
    get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
    parsed_params = eval(@response.body)
    assert_equal(
568
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
569
       'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
570 571 572 573 574 575 576 577
      parsed_params
    )
  end

  def test_params_passing_with_fixnums
    get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6}
    parsed_params = eval(@response.body)
    assert_equal(
578
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
579
       'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
580 581 582 583
      parsed_params
    )
  end

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  def test_params_passing_with_fixnums_when_not_html_request
    get :test_params, :format => 'json', :count => 999
    parsed_params = eval(@response.body)
    assert_equal(
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
       'format' => 'json', 'count' => 999 },
      parsed_params
    )
  end

  def test_params_passing_path_parameter_is_string_when_not_html_request
    get :test_params, :format => 'json', :id => 1
    parsed_params = eval(@response.body)
    assert_equal(
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
       'format' => 'json', 'id' => '1' },
      parsed_params
    )
  end

604 605
  def test_params_passing_with_frozen_values
    assert_nothing_raised do
606
      get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze, :deepfreeze => { :frozen => 'icy'.freeze }.freeze
607 608 609
    end
    parsed_params = eval(@response.body)
    assert_equal(
610
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
611
       'frozen' => 'icy', 'frozens' => ['icy'], 'deepfreeze' => { 'frozen' => 'icy' }},
612 613 614 615
      parsed_params
    )
  end

616 617 618 619 620 621
  def test_params_passing_doesnt_modify_in_place
    page = {:name => "Page name", :month => 4, :year => 2004, :day => 6}
    get :test_params, :page => page
    assert_equal 2004, page[:year]
  end

622 623 624 625
  test "set additional HTTP headers" do
    @request.headers['Referer'] = "http://nohost.com/home"
    @request.headers['Content-Type'] = "application/rss+xml"
    get :test_headers
626
    parsed_env = ActiveSupport::JSON.decode(@response.body)
627 628 629 630 631 632 633 634
    assert_equal "http://nohost.com/home", parsed_env["HTTP_REFERER"]
    assert_equal "application/rss+xml", parsed_env["CONTENT_TYPE"]
  end

  test "set additional env variables" do
    @request.headers['HTTP_REFERER'] = "http://example.com/about"
    @request.headers['CONTENT_TYPE'] = "application/json"
    get :test_headers
635
    parsed_env = ActiveSupport::JSON.decode(@response.body)
636 637 638 639
    assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
    assert_equal "application/json", parsed_env["CONTENT_TYPE"]
  end

640
  def test_id_converted_to_string
641
    get :test_params, :id => 20, :foo => Object.new
642 643 644 645 646
    assert_kind_of String, @request.path_parameters['id']
  end

  def test_array_path_parameter_handled_properly
    with_routing do |set|
647
      set.draw do
648 649
        get 'file/*path', :to => 'test_case_test/test#test_params'
        get ':controller/:action'
650
      end
651

652 653
      get :test_params, :path => ['hello', 'world']
      assert_equal ['hello', 'world'], @request.path_parameters['path']
654
      assert_equal 'hello/world', @request.path_parameters['path'].to_param
655 656 657 658 659 660 661 662 663 664 665 666 667
    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
J
Joshua Peek 已提交
668 669
    assert @routes
    routes_id = @routes.object_id
670

671 672 673 674
    begin
      with_routing { raise 'fail' }
      fail 'Should not be here.'
    rescue RuntimeError
675
    end
676

J
Joshua Peek 已提交
677 678
    assert @routes
    assert_equal routes_id, @routes.object_id
679
  end
680 681 682 683 684 685 686 687 688

  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
689

690 691 692 693 694
  def test_header_properly_reset_after_remote_http_request
    xhr :get, :test_params
    assert_nil @request.env['HTTP_X_REQUESTED_WITH']
  end

J
Joshua Peek 已提交
695
  def test_header_properly_reset_after_get_request
696 697 698 699 700
    get :test_params
    @request.recycle!
    assert_nil @request.instance_variable_get("@request_method")
  end

701 702 703 704 705
  def test_params_reset_after_post_request
    post :no_op, :foo => "bar"
    assert_equal "bar", @request.params[:foo]
    @request.recycle!
    post :no_op
706
    assert @request.params[:foo].blank?
707 708
  end

709 710 711 712 713 714 715 716
  def test_symbolized_path_params_reset_after_request
    get :test_params, :id => "foo"
    assert_equal "foo", @request.symbolized_path_parameters[:id]
    @request.recycle!
    get :test_params
    assert_nil @request.symbolized_path_parameters[:id]
  end

A
Andrew White 已提交
717 718 719 720 721 722 723 724 725 726 727 728 729
  def test_request_protocol_is_reset_after_request
    get :test_protocol
    assert_equal "http://", @response.body

    @request.env["HTTPS"] = "on"
    get :test_protocol
    assert_equal "https://", @response.body

    @request.env.delete("HTTPS")
    get :test_protocol
    assert_equal "http://", @response.body
  end

730 731 732 733 734 735 736 737 738 739 740 741 742 743
  def test_request_format
    get :test_format, :format => 'html'
    assert_equal 'text/html', @response.body

    get :test_format, :format => 'json'
    assert_equal 'application/json', @response.body

    get :test_format, :format => 'xml'
    assert_equal 'application/xml', @response.body

    get :test_format
    assert_equal 'text/html', @response.body
  end

744
  def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
745
    cookies['foo'] = 'bar'
746 747 748 749 750
    get :no_op
    assert_equal 'bar', cookies['foo']
  end

  def test_should_detect_if_cookie_is_deleted
751
    cookies['foo'] = 'bar'
752 753 754 755
    get :delete_cookie
    assert_nil cookies['foo']
  end

756 757 758 759 760 761 762 763
  %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
764
          assert_match(%r{@#{variable} is nil}, error.message)
765 766 767 768 769 770
        rescue => error
          assert false, "expected RuntimeError, got #{error.class}"
        end
      end
    end
  end
771

772
  FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
773

774 775
  READ_BINARY = 'rb:binary'
  READ_PLAIN = 'r:binary'
776

777 778 779 780
  def test_test_uploaded_file
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
781
    expected = File.read(path)
782
    expected.force_encoding(Encoding::BINARY)
783

J
Joshua Peek 已提交
784
    file = Rack::Test::UploadedFile.new(path, content_type)
785 786 787
    assert_equal filename, file.original_filename
    assert_equal content_type, file.content_type
    assert_equal file.path, file.local_path
788
    assert_equal expected, file.read
789 790 791 792 793

    new_content_type = "new content_type"
    file.content_type = new_content_type
    assert_equal new_content_type, file.content_type

794
  end
J
Joshua Peek 已提交
795

796
  def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
797
    TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
798 799 800 801 802

    uploaded_file = fixture_file_upload('/mona_lisa.jpg', 'image/png')
    assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
  end

803 804 805 806
  def test_test_uploaded_file_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
J
Joshua Peek 已提交
807

J
Joshua Peek 已提交
808
    binary_uploaded_file = Rack::Test::UploadedFile.new(path, content_type, :binary)
809
    assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read
J
Joshua Peek 已提交
810

J
Joshua Peek 已提交
811
    plain_uploaded_file = Rack::Test::UploadedFile.new(path, content_type)
812
    assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
813 814 815 816 817 818
  end

  def test_fixture_file_upload_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/jpg'
J
Joshua Peek 已提交
819

820
    binary_file_upload = fixture_file_upload(path, content_type, :binary)
821
    assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
J
Joshua Peek 已提交
822

823
    plain_file_upload = fixture_file_upload(path, content_type)
824
    assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
825
  end
826

827 828
  def test_fixture_file_upload
    post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
J
Jeremy Kemper 已提交
829
    assert_equal '159528', @response.body
830
  end
831

832 833 834 835 836 837 838 839 840 841 842 843
  def test_fixture_file_upload_relative_to_fixture_path
    TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
    uploaded_file = fixture_file_upload("mona_lisa.jpg", "image/jpg")
    assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
  end

  def test_fixture_file_upload_ignores_nil_fixture_path
    TestCaseTest.stubs(:fixture_path).returns(nil)
    uploaded_file = fixture_file_upload("#{FILES_DIR}/mona_lisa.jpg", "image/jpg")
    assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
  end

844 845 846 847 848 849 850
  def test_action_dispatch_uploaded_file_upload
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    post :test_file_upload, :file => ActionDispatch::Http::UploadedFile.new(:filename => path, :type => "image/jpg", :tempfile => File.open(path))
    assert_equal '159528', @response.body
  end

851
  def test_test_uploaded_file_exception_when_file_doesnt_exist
J
Joshua Peek 已提交
852
    assert_raise(RuntimeError) { Rack::Test::UploadedFile.new('non_existent_file') }
853
  end
854

855 856 857 858 859 860 861 862 863
  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.
864
    assert_raise(ActiveSupport::TestCase::Assertion) do
865 866 867
      assert_redirected_to 'created resource'
    end
  end
868
end
869

870
class InferringClassNameTest < ActionController::TestCase
871 872 873 874 875
  def test_determine_controller_class
    assert_equal ContentController, determine_class("ContentControllerTest")
  end

  def test_determine_controller_class_with_nonsense_name
876
    assert_nil determine_class("HelloGoodBye")
877 878 879
  end

  def test_determine_controller_class_with_sensible_name_where_no_controller_exists
880
    assert_nil determine_class("NoControllerWithThisNameTest")
881 882 883 884 885 886 887 888 889 890
  end

  private
    def determine_class(name)
      ActionController::TestCase.determine_default_controller_class(name)
    end
end

class CrazyNameTest < ActionController::TestCase
  tests ContentController
891

892 893 894 895
  def test_controller_class_can_be_set_manually_not_just_inferred
    assert_equal ContentController, self.class.controller_class
  end
end
896

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
class CrazySymbolNameTest < ActionController::TestCase
  tests :content

  def test_set_controller_class_using_symbol
    assert_equal ContentController, self.class.controller_class
  end
end

class CrazyStringNameTest < ActionController::TestCase
  tests 'content'

  def test_set_controller_class_using_string
    assert_equal ContentController, self.class.controller_class
  end
end

913 914
class NamedRoutesControllerTest < ActionController::TestCase
  tests ContentController
J
Joshua Peek 已提交
915

916 917
  def test_should_be_able_to_use_named_routes_before_a_request_is_done
    with_routing do |set|
918
      set.draw { resources :contents }
919
      assert_equal 'http://test.host/contents/new', new_content_url
920
      assert_equal 'http://test.host/contents/1', content_url(:id => 1)
921 922 923
    end
  end
end
A
Andrew White 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943

class AnonymousControllerTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def index
        render :text => params[:controller]
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
        get ':controller(/:action(/:id))'
      end
    end
  end

  def test_controller_name
    get :index
    assert_equal 'anonymous', @response.body
  end
944
end
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975

class RoutingDefaultsTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def post
        render :text => request.fullpath
      end

      def project
        render :text => request.fullpath
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
        get '/posts/:id', :to => 'anonymous#post', :bucket_type => 'post'
        get '/projects/:id', :to => 'anonymous#project', :defaults => { :bucket_type => 'project' }
      end
    end
  end

  def test_route_option_can_be_passed_via_process
    get :post, :id => 1, :bucket_type => 'post'
    assert_equal '/posts/1', @response.body
  end

  def test_route_default_is_not_required_for_building_request_uri
    get :project, :id => 2
    assert_equal '/projects/2', @response.body
  end
end