test_case_test.rb 32.1 KB
Newer Older
1 2
require 'abstract_unit'
require 'controller/fake_controllers'
3
require 'active_support/json/decoding'
4
require 'rails/engine'
5

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

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

17 18 19 20 21
    def delete_flash
      flash.delete("test")
      render :text => 'ignore me'
    end

22 23
    def set_flash_now
      flash.now["test_now"] = ">#{flash["test_now"]}<"
24
      render text: 'ignore me'
25 26
    end

27 28 29
    def set_session
      session['string'] = 'A wonder'
      session[:symbol] = 'it works'
30
      render text: 'Success'
31 32
    end

33 34
    def reset_the_session
      reset_session
35
      render text: 'ignore me'
36 37
    end

38
    def render_raw_post
39
      raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
40
      render text: request.raw_post
41 42
    end

43
    def render_body
44
      render text: request.body.read
45 46
    end

47
    def test_params
48
      render text: ::JSON.dump(params.to_unsafe_h)
49 50
    end

51
    def test_query_parameters
52
      render text: ::JSON.dump(request.query_parameters)
53 54 55 56 57 58
    end

    def test_request_parameters
      render text: request.request_parameters.inspect
    end

59
    def test_uri
60
      render text: request.fullpath
61
    end
62

63
    def test_format
64
      render text: request.format
65 66
    end

67
    def test_query_string
68
      render text: request.query_string
69 70
    end

A
Andrew White 已提交
71
    def test_protocol
72
      render text: request.protocol
A
Andrew White 已提交
73 74
    end

75
    def test_headers
76
      render text: request.headers.env.to_json
77 78
    end

79
    def test_html_output
80
      render text: <<HTML
81 82
<html>
  <body>
83
    <a href="/"><img src="/images/button.png" /></a>
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    <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 已提交
99

100 101
    def test_xml_output
      response.content_type = "application/xml"
102
      render text: <<XML
103 104 105 106 107 108
<?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
109

110
    def test_only_one_param
111
      render text: (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
112 113 114
    end

    def test_remote_addr
115
      render text: (request.remote_addr || "not specified")
116
    end
117

118
    def test_file_upload
119
      render text: params[:file].size
120
    end
121

122 123 124 125
    def test_send_file
      send_file(File.expand_path(__FILE__))
    end

126
    def redirect_to_same_controller
127
      redirect_to controller: 'test', action: 'test_uri', id: 5
128 129 130
    end

    def redirect_to_different_controller
131
      redirect_to controller: 'fail', id: 5
132 133
    end

134
    def create
135
      head :created, location: 'created resource'
136 137
    end

138 139
    def delete_cookie
      cookies.delete("foo")
140
      head :ok
141 142
    end

143 144 145 146 147 148 149 150
    def test_without_body
      render html: '<div class="foo"></div>'.html_safe
    end

    def test_with_body
      render html: '<body class="foo"></body>'.html_safe
    end

151 152 153
    private

      def generate_url(opts)
154
        url_for(opts.merge(action: "test_uri"))
155
      end
156 157 158
  end

  def setup
159
    super
160
    @controller = TestController.new
C
Carl Lerche 已提交
161
    @request.env['PATH_INFO'] = nil
162 163
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
164
        get ':controller(/:action(/:id))'
165 166
      end
    end
167 168
  end

169
  class DefaultUrlOptionsCachingController < ActionController::Base
170
    before_action { @dynamic_opt = 'opt' }
171 172 173 174 175 176 177 178 179 180 181 182 183 184

    def test_url_options_reset
      render text: url_for(params)
    end

    def default_url_options
      if defined?(@dynamic_opt)
        super.merge dynamic_opt: @dynamic_opt
      else
        super
      end
    end
  end

185 186 187 188 189 190 191 192 193 194 195 196 197
  def test_assert_select_without_body
    get :test_without_body

    assert_select 'body', 0
    assert_select 'div.foo'
  end

  def test_assert_select_with_body
    get :test_with_body

    assert_select 'body.foo'
  end

198 199 200 201 202 203 204
  def test_url_options_reset
    @controller = DefaultUrlOptionsCachingController.new
    get :test_url_options_reset
    assert_nil @request.params['dynamic_opt']
    assert_match(/dynamic_opt=opt/, @response.body)
  end

205
  def test_raw_post_handling
206
    params = Hash[:page, { name: 'page name' }, 'some key', 123]
207
    post :render_raw_post, params: params.dup
208

209 210 211 212
    assert_equal params.to_query, @response.body
  end

  def test_body_stream
213
    params = Hash[:page, { name: 'page name' }, 'some key', 123]
214

215 216 217 218 219 220 221 222 223
    post :render_body, params: params.dup

    assert_equal params.to_query, @response.body
  end

  def test_deprecated_body_stream
    params = Hash[:page, { name: 'page name' }, 'some key', 123]

    assert_deprecated { post :render_body, params.dup }
224 225

    assert_equal params.to_query, @response.body
226
  end
227

228
  def test_document_body_and_params_with_post
229
    post :test_params, params: { id: 1 }
230
    assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
231
  end
232

233
  def test_document_body_with_post
234 235 236 237 238 239
    post :render_body, body: "document body"
    assert_equal "document body", @response.body
  end

  def test_deprecated_document_body_with_post
    assert_deprecated { post :render_body, "document body" }
240 241
    assert_equal "document body", @response.body
  end
242

243
  def test_document_body_with_put
244 245 246 247 248 249
    put :render_body, body: "document body"
    assert_equal "document body", @response.body
  end

  def test_deprecated_document_body_with_put
    assert_deprecated { put :render_body, "document body" }
250 251
    assert_equal "document body", @response.body
  end
252

253 254 255 256 257
  def test_head
    head :test_params
    assert_equal 200, @response.status
  end

258 259
  def test_process_without_flash
    process :set_flash
260
    assert_equal '><', flash['test']
261 262
  end

263 264 265 266 267
  def test_deprecated_process_with_flash
    assert_deprecated { process :set_flash, "GET", nil, nil, { "test" => "value" } }
    assert_equal '>value<', flash['test']
  end

268
  def test_process_with_flash
269 270 271
    process :set_flash,
      method: "GET",
      flash: { "test" => "value" }
272
    assert_equal '>value<', flash['test']
273
  end
274

275 276 277 278 279
  def test_deprecated_process_with_flash_now
    assert_deprecated { process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" } }
    assert_equal '>value_now<', flash['test_now']
  end

280
  def test_process_with_flash_now
281 282 283
    process :set_flash_now,
      method: "GET",
      flash: { "test_now" => "value_now" }
284 285 286
    assert_equal '>value_now<', flash['test_now']
  end

287 288 289 290 291 292 293
  def test_process_delete_flash
    process :set_flash
    process :delete_flash
    assert_empty flash
    assert_empty session
  end

294 295 296 297 298 299 300 301 302
  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
303 304 305 306 307 308 309 310 311
    assert_deprecated { process :no_op, "GET", nil, { 'string' => 'value1', symbol: 'value2' } }
    assert_equal 'value1', session['string']
    assert_equal 'value1', session[:string]
    assert_equal 'value2', session['symbol']
    assert_equal 'value2', session[:symbol]
  end

  def test_process_with_session_kwarg
    process :no_op, method: "GET", session: { 'string' => 'value1', symbol: 'value2' }
312 313 314 315 316 317
    assert_equal 'value1', session['string']
    assert_equal 'value1', session[:string]
    assert_equal 'value2', session['symbol']
    assert_equal 'value2', session[:symbol]
  end

318 319 320 321 322 323 324 325 326
  def test_deprecated_process_merges_session_arg
    session[:foo] = 'bar'
    assert_deprecated {
      get :no_op, nil, { bar: 'baz' }
    }
    assert_equal 'bar', session[:foo]
    assert_equal 'baz', session[:bar]
  end

327 328
  def test_process_merges_session_arg
    session[:foo] = 'bar'
329
    get :no_op, session: { bar: 'baz' }
330 331 332 333
    assert_equal 'bar', session[:foo]
    assert_equal 'baz', session[:bar]
  end

334 335 336 337 338 339 340 341 342
  def test_deprecated_merged_session_arg_is_retained_across_requests
    assert_deprecated {
      get :no_op, nil, { foo: 'bar' }
    }
    assert_equal 'bar', session[:foo]
    get :no_op
    assert_equal 'bar', session[:foo]
  end

343
  def test_merged_session_arg_is_retained_across_requests
344
    get :no_op, session: { foo: 'bar' }
345 346 347 348 349 350 351
    assert_equal 'bar', session[:foo]
    get :no_op
    assert_equal 'bar', session[:foo]
  end

  def test_process_overwrites_existing_session_arg
    session[:foo] = 'bar'
352
    get :no_op, session: { foo: 'baz' }
353 354 355
    assert_equal 'baz', session[:foo]
  end

356 357 358 359 360 361 362 363 364 365 366 367
  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

368 369 370 371 372 373
  def test_response_and_request_have_nice_accessors
    process :no_op
    assert_equal @response, response
    assert_equal @request, request
  end

374 375
  def test_process_with_request_uri_with_no_params
    process :test_uri
376
    assert_equal "/test_case_test/test/test_uri", @response.body
377 378
  end

379 380 381 382 383 384
  def test_process_with_symbol_method
    process :test_uri, method: :get
    assert_equal "/test_case_test/test/test_uri", @response.body
  end

  def test_deprecated_process_with_request_uri_with_params
385
    assert_deprecated { process :test_uri, "GET", id: 7 }
386 387 388
    assert_equal "/test_case_test/test/test_uri/7", @response.body
  end

389
  def test_process_with_request_uri_with_params
390 391 392 393
    process :test_uri,
      method: "GET",
      params: { id: 7 }

394
    assert_equal "/test_case_test/test/test_uri/7", @response.body
395
  end
396

397 398 399 400 401 402
  def test_deprecated_process_with_request_uri_with_params_with_explicit_uri
    @request.env['PATH_INFO'] = "/explicit/uri"
    assert_deprecated { process :test_uri, "GET", id: 7 }
    assert_equal "/explicit/uri", @response.body
  end

403
  def test_process_with_request_uri_with_params_with_explicit_uri
C
Carl Lerche 已提交
404
    @request.env['PATH_INFO'] = "/explicit/uri"
405
    process :test_uri, method: "GET", params: { id: 7 }
406
    assert_equal "/explicit/uri", @response.body
407 408
  end

409
  def test_process_with_query_string
410 411 412
    process :test_query_string,
      method: "GET",
      params: { q: 'test' }
413 414 415 416
    assert_equal "q=test", @response.body
  end

  def test_process_with_query_string_with_explicit_uri
C
Carl Lerche 已提交
417 418
    @request.env['PATH_INFO'] = '/explicit/uri'
    @request.env['QUERY_STRING'] = 'q=test?extra=question'
419 420 421 422
    process :test_query_string
    assert_equal "q=test?extra=question", @response.body
  end

423
  def test_multiple_calls
424
    process :test_only_one_param, method: "GET", params: { left: true }
425
    assert_equal "OK", @response.body
426
    process :test_only_one_param, method: "GET", params: { right: true }
427
    assert_equal "OK", @response.body
428
  end
429

430 431 432 433 434 435 436 437 438 439 440 441 442
  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
443

444
  def test_assert_generates
445
    assert_generates 'controller/action/5', controller: 'controller', action: 'action', id: '5'
446 447 448 449
    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" }, {}
450
  end
451

452
  def test_assert_routing
453
    assert_routing 'content', controller: 'content', action: 'index'
454 455
  end

456 457
  def test_assert_routing_with_method
    with_routing do |set|
458
      set.draw { resources(:content) }
459
      assert_routing({ method: 'post', path: 'content' }, { controller: 'content', action: 'create' })
460 461 462
    end
  end

463
  def test_assert_routing_in_module
464 465 466
    with_routing do |set|
      set.draw do
        namespace :admin do
467
          get 'user' => 'user#index'
468 469 470
        end
      end

471
      assert_routing 'admin/user', controller: 'admin/user', action: 'index'
472
    end
473
  end
474

475 476
  def test_assert_routing_with_glob
    with_routing do |set|
477
      set.draw { get('*path' => "pages#show") }
478
      assert_routing('/company/about', { controller: 'pages', action: 'show', path: 'company/about' })
479 480
    end
  end
481

482 483
  def test_deprecated_params_passing
    assert_deprecated {
484
      get :test_params, page: { name: "Page name", month: '4', year: '2004', day: '6' }
485
    }
486
    parsed_params = ::JSON.parse(@response.body)
487
    assert_equal(
488 489 490 491
      {
        'controller' => 'test_case_test/test', 'action' => 'test_params',
        'page' => { 'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6' }
      },
492 493 494 495
      parsed_params
    )
  end

496
  def test_params_passing
497 498 499 500 501 502 503 504
    get :test_params, params: {
      page: {
        name: "Page name",
        month: '4',
        year: '2004',
        day: '6'
      }
    }
505
    parsed_params = ::JSON.parse(@response.body)
506
    assert_equal(
507 508 509 510
      {
        'controller' => 'test_case_test/test', 'action' => 'test_params',
        'page' => { 'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6' }
      },
511 512 513 514
      parsed_params
    )
  end

515 516
  def test_query_param_named_action
    get :test_query_parameters, params: {action: 'foobar'}
517 518
    parsed_params = JSON.parse(@response.body)
    assert_equal({'action' => 'foobar'}, parsed_params)
519 520 521 522 523 524 525 526
  end

  def test_request_param_named_action
    post :test_request_parameters, params: {action: 'foobar'}
    parsed_params = eval(@response.body)
    assert_equal({'action' => 'foobar'}, parsed_params)
  end

527 528 529 530 531 532 533 534 535 536
  def test_kwarg_params_passing_with_session_and_flash
    get :test_params, params: {
      page: {
        name: "Page name",
        month: '4',
        year: '2004',
        day: '6'
      }
    }, session: { 'foo' => 'bar' }, flash: { notice: 'created' }

537
    parsed_params = ::JSON.parse(@response.body)
538
    assert_equal(
539
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
540
       'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
541 542
      parsed_params
    )
543 544 545

    assert_equal 'bar', session[:foo]
    assert_equal 'created', flash[:notice]
546 547 548
  end

  def test_params_passing_with_fixnums
549 550 551
    get :test_params, params: {
      page: { name: "Page name", month: 4, year: 2004, day: 6 }
    }
552
    parsed_params = ::JSON.parse(@response.body)
553
    assert_equal(
554
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
555
       'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
556 557 558 559
      parsed_params
    )
  end

560
  def test_params_passing_with_fixnums_when_not_html_request
561
    get :test_params, params: { format: 'json', count: 999 }
562
    parsed_params = ::JSON.parse(@response.body)
563 564
    assert_equal(
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
565
       'format' => 'json', 'count' => '999' },
566 567 568 569 570
      parsed_params
    )
  end

  def test_params_passing_path_parameter_is_string_when_not_html_request
571
    get :test_params, params: { format: 'json', id: 1 }
572
    parsed_params = ::JSON.parse(@response.body)
573 574 575 576 577 578 579 580 581
    assert_equal(
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
       'format' => 'json', 'id' => '1' },
      parsed_params
    )
  end

  def test_deprecated_params_passing_path_parameter_is_string_when_not_html_request
    assert_deprecated { get :test_params, format: 'json', id: 1 }
582
    parsed_params = ::JSON.parse(@response.body)
583 584 585 586 587 588 589
    assert_equal(
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
       'format' => 'json', 'id' => '1' },
      parsed_params
    )
  end

590 591
  def test_params_passing_with_frozen_values
    assert_nothing_raised do
592 593 594
      get :test_params, params: {
        frozen: 'icy'.freeze, frozens: ['icy'.freeze].freeze, deepfreeze: { frozen: 'icy'.freeze }.freeze
      }
595
    end
596
    parsed_params = ::JSON.parse(@response.body)
597
    assert_equal(
598
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
599
       'frozen' => 'icy', 'frozens' => ['icy'], 'deepfreeze' => { 'frozen' => 'icy' }},
600 601 602 603
      parsed_params
    )
  end

604
  def test_params_passing_doesnt_modify_in_place
605
    page = { name: "Page name", month: 4, year: 2004, day: 6 }
606
    get :test_params, params: { page: page }
607 608 609
    assert_equal 2004, page[:year]
  end

610 611 612 613
  test "set additional HTTP headers" do
    @request.headers['Referer'] = "http://nohost.com/home"
    @request.headers['Content-Type'] = "application/rss+xml"
    get :test_headers
614
    parsed_env = ActiveSupport::JSON.decode(@response.body)
615 616 617 618 619 620 621 622
    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
623
    parsed_env = ActiveSupport::JSON.decode(@response.body)
624 625 626 627
    assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
    assert_equal "application/json", parsed_env["CONTENT_TYPE"]
  end

628
  def test_id_converted_to_string
629 630 631 632 633 634 635 636
    get :test_params, params: {
      id: 20, foo: Object.new
    }
    assert_kind_of String, @request.path_parameters[:id]
  end

  def test_deprecared_id_converted_to_string
    assert_deprecated { get :test_params, id: 20, foo: Object.new}
637
    assert_kind_of String, @request.path_parameters[:id]
638 639 640 641
  end

  def test_array_path_parameter_handled_properly
    with_routing do |set|
642
      set.draw do
643
        get 'file/*path', to: 'test_case_test/test#test_params'
644
        get ':controller/:action'
645
      end
646

647
      get :test_params, params: { path: ['hello', 'world'] }
648 649
      assert_equal ['hello', 'world'], @request.path_parameters[:path]
      assert_equal 'hello/world', @request.path_parameters[:path].to_param
650 651 652 653
    end
  end

  def test_assert_realistic_path_parameters
654
    get :test_params, params: { id: 20, foo: Object.new }
655

656
    # All elements of path_parameters should use Symbol keys
657
    @request.path_parameters.each_key do |key|
658
      assert_kind_of Symbol, key
659 660 661 662
    end
  end

  def test_with_routing_places_routes_back
J
Joshua Peek 已提交
663 664
    assert @routes
    routes_id = @routes.object_id
665

666 667 668 669
    begin
      with_routing { raise 'fail' }
      fail 'Should not be here.'
    rescue RuntimeError
670
    end
671

J
Joshua Peek 已提交
672 673
    assert @routes
    assert_equal routes_id, @routes.object_id
674
  end
675 676 677 678 679 680 681 682 683

  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
684

685
  def test_header_properly_reset_after_remote_http_request
686
    get :test_params, xhr: true
687
    assert_nil @request.env['HTTP_X_REQUESTED_WITH']
G
Guo Xiang Tan 已提交
688
    assert_nil @request.env['HTTP_ACCEPT']
689 690
  end

691 692 693
  def test_deprecated_xhr_with_params
    assert_deprecated { xhr :get, :test_params, params: { id: 1 } }

694
    assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
695 696
  end

697
  def test_xhr_with_params
698
    get :test_params, params: { id: 1 }, xhr: true
699

700
    assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
701 702 703
  end

  def test_xhr_with_session
704 705 706 707 708 709 710 711 712 713
    get :set_session, xhr: true

    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_deprecated_xhr_with_session
    assert_deprecated { xhr :get, :set_session }
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728

    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_deprecated_params_reset_between_post_requests
    assert_deprecated { post :no_op, foo: "bar" }
    assert_equal "bar", @request.params[:foo]

    post :no_op
    assert @request.params[:foo].blank?
  end

G
Guo Xiang Tan 已提交
729
  def test_params_reset_between_post_requests
730
    post :no_op, params: { foo: "bar" }
731
    assert_equal "bar", @request.params[:foo]
G
Guo Xiang Tan 已提交
732

733
    post :no_op
734
    assert @request.params[:foo].blank?
735 736
  end

737
  def test_filtered_parameters_reset_between_requests
738
    get :no_op, params: { foo: "bar" }
739 740
    assert_equal "bar", @request.filtered_parameters[:foo]

741
    get :no_op, params: { foo: "baz" }
742 743 744
    assert_equal "baz", @request.filtered_parameters[:foo]
  end

G
Guo Xiang Tan 已提交
745
  def test_path_params_reset_between_request
746
    get :test_params, params: { id: "foo" }
747
    assert_equal "foo", @request.path_parameters[:id]
G
Guo Xiang Tan 已提交
748

749
    get :test_params
750
    assert_nil @request.path_parameters[:id]
751 752
  end

A
Andrew White 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765
  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

766
  def test_request_format
767
    get :test_format, params: { format: 'html' }
768 769
    assert_equal 'text/html', @response.body

770
    get :test_format, params: { format: 'json' }
771 772
    assert_equal 'application/json', @response.body

773
    get :test_format, params: { format: 'xml' }
774 775 776 777 778 779
    assert_equal 'application/xml', @response.body

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

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
  def test_request_format_kwarg
    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

  def test_request_format_kwarg_overrides_params
    get :test_format, format: 'json', params: { format: 'html' }
    assert_equal 'application/json', @response.body
  end

799
  def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
800
    cookies['foo'] = 'bar'
801 802 803 804 805
    get :no_op
    assert_equal 'bar', cookies['foo']
  end

  def test_should_detect_if_cookie_is_deleted
806
    cookies['foo'] = 'bar'
807 808 809 810
    get :delete_cookie
    assert_nil cookies['foo']
  end

811 812 813 814 815 816 817 818
  %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
819
          assert_match(%r{@#{variable} is nil}, error.message)
820 821 822 823 824 825
        rescue => error
          assert false, "expected RuntimeError, got #{error.class}"
        end
      end
    end
  end
826

827
  FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
828

829 830
  READ_BINARY = 'rb:binary'
  READ_PLAIN = 'r:binary'
831

832 833 834 835
  def test_test_uploaded_file
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
836
    expected = File.read(path)
837
    expected.force_encoding(Encoding::BINARY)
838

J
Joshua Peek 已提交
839
    file = Rack::Test::UploadedFile.new(path, content_type)
840 841 842
    assert_equal filename, file.original_filename
    assert_equal content_type, file.content_type
    assert_equal file.path, file.local_path
843
    assert_equal expected, file.read
844 845 846 847 848

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

849
  end
J
Joshua Peek 已提交
850

851
  def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
852
    TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
853 854 855 856 857

    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

858 859 860 861
  def test_test_uploaded_file_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
J
Joshua Peek 已提交
862

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

J
Joshua Peek 已提交
866
    plain_uploaded_file = Rack::Test::UploadedFile.new(path, content_type)
867
    assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
868 869 870 871 872 873
  end

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

875
    binary_file_upload = fixture_file_upload(path, content_type, :binary)
876
    assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
J
Joshua Peek 已提交
877

878
    plain_file_upload = fixture_file_upload(path, content_type)
879
    assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
880
  end
881

882 883 884 885 886
  def test_fixture_file_upload_should_be_able_access_to_tempfile
    file = fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
    assert file.respond_to?(:tempfile), "expected tempfile should respond on fixture file object, got nothing"
  end

887
  def test_fixture_file_upload
888 889 890 891
    post :test_file_upload,
      params: {
        file: fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
      }
J
Jeremy Kemper 已提交
892
    assert_equal '159528', @response.body
893
  end
894

895 896 897 898 899 900 901 902 903 904 905 906
  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

907 908 909 910
  def test_deprecated_action_dispatch_uploaded_file_upload
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    assert_deprecated {
911
      post :test_file_upload, file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
912 913 914 915
    }
    assert_equal '159528', @response.body
  end

916 917 918
  def test_action_dispatch_uploaded_file_upload
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
919
    post :test_file_upload, params: {
920
      file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
921
    }
922 923 924
    assert_equal '159528', @response.body
  end

925
  def test_test_uploaded_file_exception_when_file_doesnt_exist
J
Joshua Peek 已提交
926
    assert_raise(RuntimeError) { Rack::Test::UploadedFile.new('non_existent_file') }
927
  end
928

929 930 931 932 933 934 935 936 937
  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.
938
    assert_raise(ActiveSupport::TestCase::Assertion) do
939 940 941
      assert_redirected_to 'created resource'
    end
  end
942
end
943

944 945 946 947 948 949 950 951
class ResponseDefaultHeadersTest < ActionController::TestCase
  class TestController < ActionController::Base
    def remove_header
      headers.delete params[:header]
      head :ok, 'C' => '3'
    end
  end

952
  def before_setup
953 954 955
    @original = ActionDispatch::Response.default_headers
    @defaults = { 'A' => '1', 'B' => '2' }
    ActionDispatch::Response.default_headers = @defaults
956
    super
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
  end

  teardown do
    ActionDispatch::Response.default_headers = @original
  end

  def setup
    super
    @controller = TestController.new
    @request.env['PATH_INFO'] = nil
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
        get ':controller(/:action(/:id))'
      end
    end
  end

  test "response contains default headers" do
    # Response headers start out with the defaults
    assert_equal @defaults, response.headers

    get :remove_header, params: { header: 'A' }
    assert_response :ok

    # After a request, the response in the test case doesn't have the
    # defaults merged on top again.
    assert_not_includes response.headers, 'A'
    assert_includes response.headers, 'B'
    assert_includes response.headers, 'C'
  end
end

989 990 991 992 993 994 995 996 997 998 999
module EngineControllerTests
  class Engine < ::Rails::Engine
    isolate_namespace EngineControllerTests

    routes.draw do
      get '/' => 'bar#index'
    end
  end

  class BarController < ActionController::Base
    def index
1000
      render text: 'bar'
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    end
  end

  class BarControllerTest < ActionController::TestCase
    tests BarController

    def test_engine_controller_route
      get :index
      assert_equal @response.body, 'bar'
    end
  end

  class BarControllerTestWithExplicitRouteSet < ActionController::TestCase
    tests BarController

    def setup
      @routes = Engine.routes
    end

    def test_engine_controller_route
      get :index
      assert_equal @response.body, 'bar'
    end
  end
end

1027
class InferringClassNameTest < ActionController::TestCase
1028 1029 1030 1031 1032
  def test_determine_controller_class
    assert_equal ContentController, determine_class("ContentControllerTest")
  end

  def test_determine_controller_class_with_nonsense_name
1033
    assert_nil determine_class("HelloGoodBye")
1034 1035 1036
  end

  def test_determine_controller_class_with_sensible_name_where_no_controller_exists
1037
    assert_nil determine_class("NoControllerWithThisNameTest")
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  end

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

class CrazyNameTest < ActionController::TestCase
  tests ContentController
1048

1049 1050 1051 1052
  def test_controller_class_can_be_set_manually_not_just_inferred
    assert_equal ContentController, self.class.controller_class
  end
end
1053

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
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

1070 1071
class NamedRoutesControllerTest < ActionController::TestCase
  tests ContentController
J
Joshua Peek 已提交
1072

1073 1074
  def test_should_be_able_to_use_named_routes_before_a_request_is_done
    with_routing do |set|
1075
      set.draw { resources :contents }
1076
      assert_equal 'http://test.host/contents/new', new_content_url
1077
      assert_equal 'http://test.host/contents/1', content_url(id: 1)
1078 1079 1080
    end
  end
end
A
Andrew White 已提交
1081 1082 1083 1084 1085

class AnonymousControllerTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def index
1086
        render text: params[:controller]
A
Andrew White 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
      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
1101
end
1102 1103 1104 1105 1106

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

      def project
1111
        render text: request.fullpath
1112 1113 1114 1115 1116
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
1117 1118
        get '/posts/:id', to: 'anonymous#post', bucket_type: 'post'
        get '/projects/:id', to: 'anonymous#project', defaults: { bucket_type: 'project' }
1119 1120 1121 1122 1123
      end
    end
  end

  def test_route_option_can_be_passed_via_process
1124
    get :post, params: { id: 1, bucket_type: 'post'}
1125 1126 1127 1128
    assert_equal '/posts/1', @response.body
  end

  def test_route_default_is_not_required_for_building_request_uri
1129
    get :project, params: { id: 2 }
1130 1131 1132
    assert_equal '/projects/2', @response.body
  end
end