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

6
class TestCaseTest < ActionController::TestCase
7 8
  def self.fixture_path; end;

9
  class TestController < ActionController::Base
10
    def no_op
11
      render plain: "dummy"
12 13
    end

14 15
    def set_flash
      flash["test"] = ">#{flash["test"]}<"
16
      render plain: "ignore me"
17
    end
18

19 20
    def delete_flash
      flash.delete("test")
21
      render plain: "ignore me"
22 23
    end

24 25
    def set_flash_now
      flash.now["test_now"] = ">#{flash["test_now"]}<"
26
      render plain: "ignore me"
27 28
    end

29
    def set_session
30 31 32
      session["string"] = "A wonder"
      session[:symbol] = "it works"
      render plain: "Success"
33 34
    end

35 36
    def reset_the_session
      reset_session
37
      render plain: "ignore me"
38 39
    end

40
    def render_raw_post
41
      raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
42
      render plain: request.raw_post
43 44
    end

45
    def render_body
46
      render plain: request.body.read
47 48
    end

49
    def test_params
50
      render plain: ::JSON.dump(params.to_unsafe_h)
51 52
    end

53
    def test_query_parameters
54
      render plain: ::JSON.dump(request.query_parameters)
55 56 57
    end

    def test_request_parameters
58
      render plain: request.request_parameters.inspect
59 60
    end

61
    def test_uri
62
      render plain: request.fullpath
63
    end
64

65
    def test_format
66
      render plain: request.format
67 68
    end

69
    def test_query_string
70
      render plain: request.query_string
71 72
    end

A
Andrew White 已提交
73
    def test_protocol
74
      render plain: request.protocol
A
Andrew White 已提交
75 76
    end

77
    def test_headers
78
      render plain: ::JSON.dump(request.headers.env)
79 80
    end

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

102
    def test_xml_output
M
Matthew Draper 已提交
103
      response.content_type = params[:response_as]
104
      render plain: <<XML
105 106
<?xml version="1.0" encoding="UTF-8"?>
<root>
M
Matthew Draper 已提交
107
  <area><p>area is an empty tag in HTML, so it won't contain this content</p></area>
108 109 110
</root>
XML
    end
111

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

    def test_remote_addr
117
      render plain: (request.remote_addr || "not specified")
118
    end
119

120
    def test_file_upload
121
      render plain: params[:file].size
122
    end
123

124 125 126 127
    def test_send_file
      send_file(File.expand_path(__FILE__))
    end

128
    def redirect_to_same_controller
129
      redirect_to controller: "test", action: "test_uri", id: 5
130 131 132
    end

    def redirect_to_different_controller
133
      redirect_to controller: "fail", id: 5
134 135
    end

136
    def create
137
      head :created, location: "/resource"
138 139
    end

140 141 142 143
    def render_cookie
      render plain: cookies["foo"]
    end

144 145
    def delete_cookie
      cookies.delete("foo")
146
      render plain: "ok"
147 148
    end

149 150 151 152 153 154 155 156
    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

157
    def boom
158
      raise "boom!"
159 160
    end

161 162 163
    private

      def generate_url(opts)
164
        url_for(opts.merge(action: "test_uri"))
165
      end
166 167 168
  end

  def setup
169
    super
170
    @controller = TestController.new
171
    @request.delete_header "PATH_INFO"
172 173
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
174
        ActiveSupport::Deprecation.silence do
175
          get ":controller(/:action(/:id))"
176
        end
177 178
      end
    end
179 180
  end

181
  class DefaultUrlOptionsCachingController < ActionController::Base
182
    before_action { @dynamic_opt = "opt" }
183 184

    def test_url_options_reset
185
      render plain: url_for
186 187 188 189 190 191 192 193 194 195 196
    end

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

197 198 199
  def test_assert_select_without_body
    get :test_without_body

200 201
    assert_select "body", 0
    assert_select "div.foo"
202 203 204 205 206
  end

  def test_assert_select_with_body
    get :test_with_body

207
    assert_select "body.foo"
208 209
  end

210 211 212
  def test_url_options_reset
    @controller = DefaultUrlOptionsCachingController.new
    get :test_url_options_reset
213
    assert_nil @request.params["dynamic_opt"]
214 215 216
    assert_match(/dynamic_opt=opt/, @response.body)
  end

217
  def test_raw_post_handling
218
    params = Hash[:page, { name: "page name" }, "some key", 123]
219
    post :render_raw_post, params: params.dup
220

221 222 223 224
    assert_equal params.to_query, @response.body
  end

  def test_body_stream
225
    params = Hash[:page, { name: "page name" }, "some key", 123]
226

227 228 229 230 231
    post :render_body, params: params.dup

    assert_equal params.to_query, @response.body
  end

232
  def test_document_body_and_params_with_post
233
    post :test_params, params: { id: 1 }
234
    assert_equal({ "id" => "1", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
235
  end
236

237
  def test_document_body_with_post
238 239 240 241
    post :render_body, body: "document body"
    assert_equal "document body", @response.body
  end

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

247 248 249 250 251
  def test_head
    head :test_params
    assert_equal 200, @response.status
  end

252 253
  def test_process_without_flash
    process :set_flash
254
    assert_equal "><", flash["test"]
255 256
  end

257
  def test_process_with_flash
258 259 260
    process :set_flash,
      method: "GET",
      flash: { "test" => "value" }
261
    assert_equal ">value<", flash["test"]
262
  end
263

264
  def test_process_with_flash_now
265 266 267
    process :set_flash_now,
      method: "GET",
      flash: { "test_now" => "value_now" }
268
    assert_equal ">value_now<", flash["test_now"]
269 270
  end

271 272 273 274 275 276 277
  def test_process_delete_flash
    process :set_flash
    process :delete_flash
    assert_empty flash
    assert_empty session
  end

278 279
  def test_process_with_session
    process :set_session
280 281 282 283
    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"
284 285
  end

286
  def test_process_with_session_kwarg
287 288 289 290 291
    process :no_op, method: "GET", session: { "string" => "value1", symbol: "value2" }
    assert_equal "value1", session["string"]
    assert_equal "value1", session[:string]
    assert_equal "value2", session["symbol"]
    assert_equal "value2", session[:symbol]
292 293
  end

294
  def test_process_merges_session_arg
295 296 297 298
    session[:foo] = "bar"
    get :no_op, session: { bar: "baz" }
    assert_equal "bar", session[:foo]
    assert_equal "baz", session[:bar]
299 300 301
  end

  def test_merged_session_arg_is_retained_across_requests
302 303
    get :no_op, session: { foo: "bar" }
    assert_equal "bar", session[:foo]
304
    get :no_op
305
    assert_equal "bar", session[:foo]
306 307 308
  end

  def test_process_overwrites_existing_session_arg
309 310 311
    session[:foo] = "bar"
    get :no_op, session: { foo: "baz" }
    assert_equal "baz", session[:foo]
312 313
  end

314 315 316 317 318 319 320 321 322 323 324 325
  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

326 327 328 329 330 331
  def test_response_and_request_have_nice_accessors
    process :no_op
    assert_equal @response, response
    assert_equal @request, request
  end

332 333
  def test_process_with_request_uri_with_no_params
    process :test_uri
334
    assert_equal "/test_case_test/test/test_uri", @response.body
335 336
  end

337 338 339 340 341
  def test_process_with_symbol_method
    process :test_uri, method: :get
    assert_equal "/test_case_test/test/test_uri", @response.body
  end

342
  def test_process_with_request_uri_with_params
343 344 345 346
    process :test_uri,
      method: "GET",
      params: { id: 7 }

347
    assert_equal "/test_case_test/test/test_uri/7", @response.body
348
  end
349

350
  def test_process_with_request_uri_with_params_with_explicit_uri
351
    @request.env["PATH_INFO"] = "/explicit/uri"
352
    process :test_uri, method: "GET", params: { id: 7 }
353
    assert_equal "/explicit/uri", @response.body
354 355
  end

356
  def test_process_with_query_string
357 358
    process :test_query_string,
      method: "GET",
359
      params: { q: "test" }
360 361 362 363
    assert_equal "q=test", @response.body
  end

  def test_process_with_query_string_with_explicit_uri
364 365
    @request.env["PATH_INFO"] = "/explicit/uri"
    @request.env["QUERY_STRING"] = "q=test?extra=question"
366 367 368 369
    process :test_query_string
    assert_equal "q=test?extra=question", @response.body
  end

370
  def test_multiple_calls
371
    process :test_only_one_param, method: "GET", params: { left: true }
372
    assert_equal "OK", @response.body
373
    process :test_only_one_param, method: "GET", params: { right: true }
374
    assert_equal "OK", @response.body
375
  end
376

M
Matthew Draper 已提交
377 378
  def test_should_impose_childless_html_tags_in_html
    process :test_xml_output, params: { response_as: "text/html" }
379

M
Matthew Draper 已提交
380 381 382 383 384 385
    # <area> auto-closes, so the <p> becomes a sibling
    assert_select "root > area + p"
  end

  def test_should_not_impose_childless_html_tags_in_xml
    process :test_xml_output, params: { response_as: "application/xml" }
386

M
Matthew Draper 已提交
387 388
    # <area> is not special, so the <p> is its child
    assert_select "root > area > p"
389
  end
390

391
  def test_assert_generates
392
    assert_generates "controller/action/5", controller: "controller", action: "action", id: "5"
393 394 395
    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"
396
    assert_generates "controller/action/7", { id: "7" }, { controller: "controller", action: "action", name: "bob" }, {}
397
  end
398

399
  def test_assert_routing
400
    assert_routing "content", controller: "content", action: "index"
401 402
  end

403 404
  def test_assert_routing_with_method
    with_routing do |set|
405
      set.draw { resources(:content) }
406
      assert_routing({ method: "post", path: "content" }, controller: "content", action: "create")
407 408 409
    end
  end

410
  def test_assert_routing_in_module
411 412 413
    with_routing do |set|
      set.draw do
        namespace :admin do
414
          get "user" => "user#index"
415 416 417
        end
      end

418
      assert_routing "admin/user", controller: "admin/user", action: "index"
419
    end
420
  end
421

422 423
  def test_assert_routing_with_glob
    with_routing do |set|
424
      set.draw { get("*path" => "pages#show") }
425
      assert_routing("/company/about", controller: "pages", action: "show", path: "company/about")
426 427
    end
  end
428

429
  def test_params_passing
430 431 432
    get :test_params, params: {
      page: {
        name: "Page name",
433 434 435
        month: "4",
        year: "2004",
        day: "6"
436 437
      }
    }
438
    parsed_params = ::JSON.parse(@response.body)
439
    assert_equal(
440
      {
441 442
        "controller" => "test_case_test/test", "action" => "test_params",
        "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" }
443
      },
444 445 446 447
      parsed_params
    )
  end

448
  def test_query_param_named_action
449
    get :test_query_parameters, params: { action: "foobar" }
450
    parsed_params = JSON.parse(@response.body)
451
    assert_equal({ "action" => "foobar" }, parsed_params)
452 453 454
  end

  def test_request_param_named_action
455
    post :test_request_parameters, params: { action: "foobar" }
456
    parsed_params = eval(@response.body)
457
    assert_equal({ "action" => "foobar" }, parsed_params)
458 459
  end

460 461 462 463
  def test_kwarg_params_passing_with_session_and_flash
    get :test_params, params: {
      page: {
        name: "Page name",
464 465 466
        month: "4",
        year: "2004",
        day: "6"
467
      }
468
    }, session: { "foo" => "bar" }, flash: { notice: "created" }
469

470
    parsed_params = ::JSON.parse(@response.body)
471
    assert_equal(
472 473
      { "controller" => "test_case_test/test", "action" => "test_params",
       "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" } },
474 475
      parsed_params
    )
476

477 478
    assert_equal "bar", session[:foo]
    assert_equal "created", flash[:notice]
479 480
  end

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

493
  def test_params_passing_with_integers_when_not_html_request
494
    get :test_params, params: { format: "json", count: 999 }
495
    parsed_params = ::JSON.parse(@response.body)
496
    assert_equal(
497
      { "controller" => "test_case_test/test", "action" => "test_params",
498
       "format" => "json", "count" => "999" },
499 500 501 502 503
      parsed_params
    )
  end

  def test_params_passing_path_parameter_is_string_when_not_html_request
504
    get :test_params, params: { format: "json", id: 1 }
505
    parsed_params = ::JSON.parse(@response.body)
506
    assert_equal(
507
      { "controller" => "test_case_test/test", "action" => "test_params",
508
       "format" => "json", "id" => "1" },
509 510 511 512
      parsed_params
    )
  end

513 514
  def test_params_passing_with_frozen_values
    assert_nothing_raised do
515
      get :test_params, params: {
516
        frozen: "icy".freeze, frozens: ["icy".freeze].freeze, deepfreeze: { frozen: "icy".freeze }.freeze
517
      }
518
    end
519
    parsed_params = ::JSON.parse(@response.body)
520
    assert_equal(
521 522
      { "controller" => "test_case_test/test", "action" => "test_params",
       "frozen" => "icy", "frozens" => ["icy"], "deepfreeze" => { "frozen" => "icy" } },
523 524 525 526
      parsed_params
    )
  end

527
  def test_params_passing_doesnt_modify_in_place
528
    page = { name: "Page name", month: 4, year: 2004, day: 6 }
529
    get :test_params, params: { page: page }
530 531 532
    assert_equal 2004, page[:year]
  end

533
  test "set additional HTTP headers" do
534 535
    @request.headers["Referer"] = "http://nohost.com/home"
    @request.headers["Content-Type"] = "application/rss+xml"
536
    get :test_headers
537
    parsed_env = ActiveSupport::JSON.decode(@response.body)
538 539 540 541 542
    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
543 544
    @request.headers["HTTP_REFERER"] = "http://example.com/about"
    @request.headers["CONTENT_TYPE"] = "application/json"
545
    get :test_headers
546
    parsed_env = ActiveSupport::JSON.decode(@response.body)
547 548 549 550
    assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
    assert_equal "application/json", parsed_env["CONTENT_TYPE"]
  end

551 552 553 554 555 556 557 558 559
  def test_using_as_json_sets_request_content_type_to_json
    post :render_body, params: { bool_value: true, str_value: "string", num_value: 2 }, as: :json

    assert_equal "application/json", @request.headers["CONTENT_TYPE"]
    assert_equal true, @request.request_parameters[:bool_value]
    assert_equal "string", @request.request_parameters[:str_value]
    assert_equal 2, @request.request_parameters[:num_value]
  end

560 561 562 563 564
  def test_using_as_json_sets_format_json
    post :render_body, params: { bool_value: true, str_value: "string", num_value: 2 }, as: :json
    assert_equal "json", @request.format
  end

565
  def test_mutating_content_type_headers_for_plain_text_files_sets_the_header
566 567
    @request.headers["Content-Type"] = "text/plain"
    post :render_body, params: { name: "foo.txt" }
568

569 570 571
    assert_equal "text/plain", @request.headers["Content-type"]
    assert_equal "foo.txt", @request.request_parameters[:name]
    assert_equal "render_body", @request.path_parameters[:action]
572 573 574
  end

  def test_mutating_content_type_headers_for_html_files_sets_the_header
575 576
    @request.headers["Content-Type"] = "text/html"
    post :render_body, params: { name: "foo.html" }
577

578 579 580
    assert_equal "text/html", @request.headers["Content-type"]
    assert_equal "foo.html", @request.request_parameters[:name]
    assert_equal "render_body", @request.path_parameters[:action]
581 582 583 584
  end

  def test_mutating_content_type_headers_for_non_registered_mime_type_raises_an_error
    assert_raises(RuntimeError) do
585 586
      @request.headers["Content-Type"] = "type/fake"
      post :render_body, params: { name: "foo.fake" }
587 588 589
    end
  end

590
  def test_id_converted_to_string
591 592 593 594 595 596
    get :test_params, params: {
      id: 20, foo: Object.new
    }
    assert_kind_of String, @request.path_parameters[:id]
  end

597 598
  def test_array_path_parameter_handled_properly
    with_routing do |set|
599
      set.draw do
600
        get "file/*path", to: "test_case_test/test#test_params"
601 602

        ActiveSupport::Deprecation.silence do
603
          get ":controller/:action"
604
        end
605
      end
606

607 608 609
      get :test_params, params: { path: ["hello", "world"] }
      assert_equal ["hello", "world"], @request.path_parameters[:path]
      assert_equal "hello/world", @request.path_parameters[:path].to_param
610 611 612 613
    end
  end

  def test_assert_realistic_path_parameters
614
    get :test_params, params: { id: 20, foo: Object.new }
615

616
    # All elements of path_parameters should use Symbol keys
617
    @request.path_parameters.each_key do |key|
618
      assert_kind_of Symbol, key
619 620 621 622
    end
  end

  def test_with_routing_places_routes_back
J
Joshua Peek 已提交
623 624
    assert @routes
    routes_id = @routes.object_id
625

626
    begin
627 628
      with_routing { raise "fail" }
      fail "Should not be here."
629
    rescue RuntimeError
630
    end
631

J
Joshua Peek 已提交
632 633
    assert @routes
    assert_equal routes_id, @routes.object_id
634
  end
635 636 637 638 639 640 641 642 643

  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
644

645
  def test_header_properly_reset_after_remote_http_request
646
    get :test_params, xhr: true
647 648
    assert_nil @request.env["HTTP_X_REQUESTED_WITH"]
    assert_nil @request.env["HTTP_ACCEPT"]
649 650
  end

651
  def test_xhr_with_params
652
    get :test_params, params: { id: 1 }, xhr: true
653

654
    assert_equal({ "id" => "1", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
655 656 657
  end

  def test_xhr_with_session
658 659
    get :set_session, xhr: true

660 661 662 663
    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"
664 665
  end

G
Guo Xiang Tan 已提交
666
  def test_params_reset_between_post_requests
667
    post :no_op, params: { foo: "bar" }
668
    assert_equal "bar", @request.params[:foo]
G
Guo Xiang Tan 已提交
669

670
    post :no_op
671
    assert @request.params[:foo].blank?
672 673
  end

674
  def test_filtered_parameters_reset_between_requests
675
    get :no_op, params: { foo: "bar" }
676 677
    assert_equal "bar", @request.filtered_parameters[:foo]

678
    get :no_op, params: { foo: "baz" }
679 680 681
    assert_equal "baz", @request.filtered_parameters[:foo]
  end

682 683 684 685 686
  def test_path_is_kept_after_the_request
    get :test_params, params: { id: "foo" }
    assert_equal "foo", @request.path
  end

G
Guo Xiang Tan 已提交
687
  def test_path_params_reset_between_request
688
    get :test_params, params: { id: "foo" }
689
    assert_equal "foo", @request.path_parameters[:id]
G
Guo Xiang Tan 已提交
690

691
    get :test_params
692
    assert_nil @request.path_parameters[:id]
693 694
  end

A
Andrew White 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707
  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

708
  def test_request_format
709 710
    get :test_format, params: { format: "html" }
    assert_equal "text/html", @response.body
711

712 713
    get :test_format, params: { format: "json" }
    assert_equal "application/json", @response.body
714

715 716
    get :test_format, params: { format: "xml" }
    assert_equal "application/xml", @response.body
717 718

    get :test_format
719
    assert_equal "text/html", @response.body
720 721
  end

722
  def test_request_format_kwarg
723 724
    get :test_format, format: "html"
    assert_equal "text/html", @response.body
725

726 727
    get :test_format, format: "json"
    assert_equal "application/json", @response.body
728

729 730
    get :test_format, format: "xml"
    assert_equal "application/xml", @response.body
731 732

    get :test_format
733
    assert_equal "text/html", @response.body
734 735 736
  end

  def test_request_format_kwarg_overrides_params
737 738
    get :test_format, format: "json", params: { format: "html" }
    assert_equal "application/json", @response.body
739 740
  end

741
  def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
742
    cookies["foo"] = "bar"
743
    get :no_op
744
    assert_equal "bar", cookies["foo"]
745 746 747
  end

  def test_cookies_should_be_escaped_properly
748
    cookies["foo"] = "+"
749
    get :render_cookie
750
    assert_equal "+", @response.body
751 752 753
  end

  def test_should_detect_if_cookie_is_deleted
754
    cookies["foo"] = "bar"
755
    get :delete_cookie
756
    assert_nil cookies["foo"]
757 758
  end

759
  def test_multiple_mixed_method_process_should_scrub_rack_input
760
    post :test_params, params: { id: 1, foo: "an foo" }
761
    assert_equal({ "id" => "1", "foo" => "an foo", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
762

763
    get :test_params, params: { bar: "an bar" }
764
    assert_equal({ "bar" => "an bar", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
765 766
  end

767 768 769 770 771 772 773 774
  %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
775
          assert_match(%r{@#{variable} is nil}, error.message)
776 777 778 779 780 781
        rescue => error
          assert false, "expected RuntimeError, got #{error.class}"
        end
      end
    end
  end
782

783
  FILES_DIR = File.dirname(__FILE__) + "/../fixtures/multipart"
784

785 786
  READ_BINARY = "rb:binary"
  READ_PLAIN = "r:binary"
787

788
  def test_test_uploaded_file
789
    filename = "ruby_on_rails.jpg"
790
    path = "#{FILES_DIR}/#{filename}"
791
    content_type = "image/png"
792
    expected = File.read(path)
793
    expected.force_encoding(Encoding::BINARY)
794

J
Joshua Peek 已提交
795
    file = Rack::Test::UploadedFile.new(path, content_type)
796 797 798
    assert_equal filename, file.original_filename
    assert_equal content_type, file.content_type
    assert_equal file.path, file.local_path
799
    assert_equal expected, file.read
800 801 802 803

    new_content_type = "new content_type"
    file.content_type = new_content_type
    assert_equal new_content_type, file.content_type
804
  end
J
Joshua Peek 已提交
805

806
  def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
807
    TestCaseTest.stub :fixture_path, FILES_DIR do
808 809
      uploaded_file = fixture_file_upload("/ruby_on_rails.jpg", "image/png")
      assert_equal File.open("#{FILES_DIR}/ruby_on_rails.jpg", READ_PLAIN).read, uploaded_file.read
810
    end
811 812
  end

813
  def test_test_uploaded_file_with_binary
814
    filename = "ruby_on_rails.jpg"
815
    path = "#{FILES_DIR}/#{filename}"
816
    content_type = "image/png"
J
Joshua Peek 已提交
817

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

J
Joshua Peek 已提交
821
    plain_uploaded_file = Rack::Test::UploadedFile.new(path, content_type)
822
    assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
823 824 825
  end

  def test_fixture_file_upload_with_binary
826
    filename = "ruby_on_rails.jpg"
827
    path = "#{FILES_DIR}/#{filename}"
828
    content_type = "image/jpg"
J
Joshua Peek 已提交
829

830
    binary_file_upload = fixture_file_upload(path, content_type, :binary)
831
    assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
J
Joshua Peek 已提交
832

833
    plain_file_upload = fixture_file_upload(path, content_type)
834
    assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
835
  end
836

837
  def test_fixture_file_upload_should_be_able_access_to_tempfile
838
    file = fixture_file_upload(FILES_DIR + "/ruby_on_rails.jpg", "image/jpg")
839 840 841
    assert file.respond_to?(:tempfile), "expected tempfile should respond on fixture file object, got nothing"
  end

842
  def test_fixture_file_upload
843 844
    post :test_file_upload,
      params: {
845
        file: fixture_file_upload(FILES_DIR + "/ruby_on_rails.jpg", "image/jpg")
846
      }
847
    assert_equal "45142", @response.body
848
  end
849

850
  def test_fixture_file_upload_relative_to_fixture_path
851
    TestCaseTest.stub :fixture_path, FILES_DIR do
852 853
      uploaded_file = fixture_file_upload("ruby_on_rails.jpg", "image/jpg")
      assert_equal File.open("#{FILES_DIR}/ruby_on_rails.jpg", READ_PLAIN).read, uploaded_file.read
854
    end
855 856
  end

857 858
  def test_fixture_file_upload_ignores_fixture_path_given_full_path
    TestCaseTest.stub :fixture_path, File.dirname(__FILE__) do
859 860
      uploaded_file = fixture_file_upload("#{FILES_DIR}/ruby_on_rails.jpg", "image/jpg")
      assert_equal File.open("#{FILES_DIR}/ruby_on_rails.jpg", READ_PLAIN).read, uploaded_file.read
861 862 863
    end
  end

864
  def test_fixture_file_upload_ignores_nil_fixture_path
865 866
    uploaded_file = fixture_file_upload("#{FILES_DIR}/ruby_on_rails.jpg", "image/jpg")
    assert_equal File.open("#{FILES_DIR}/ruby_on_rails.jpg", READ_PLAIN).read, uploaded_file.read
867 868
  end

869
  def test_action_dispatch_uploaded_file_upload
870
    filename = "ruby_on_rails.jpg"
871
    path = "#{FILES_DIR}/#{filename}"
872
    post :test_file_upload, params: {
873
      file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
874
    }
875
    assert_equal "45142", @response.body
876 877
  end

878
  def test_test_uploaded_file_exception_when_file_doesnt_exist
879
    assert_raise(RuntimeError) { Rack::Test::UploadedFile.new("non_existent_file") }
880
  end
881

882 883 884 885 886
  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.
887
    assert_equal "/resource", @response.redirect_url
888 889 890
    assert_equal @response.redirect_url, redirect_to_url

    # Must be a :redirect response.
891
    assert_raise(ActiveSupport::TestCase::Assertion) do
892
      assert_redirected_to "/resource"
893 894
    end
  end
895 896 897 898 899 900 901 902 903 904 905

  def test_exception_in_action_reaches_test
    assert_raise(RuntimeError) do
      process :boom, method: "GET"
    end
  end

  def test_request_state_is_cleared_after_exception
    assert_raise(RuntimeError) do
      process :boom,
        method: "GET",
906
        params: { q: "test1" }
907 908 909 910
    end

    process :test_query_string,
      method: "GET",
911
      params: { q: "test2" }
912 913 914

    assert_equal "q=test2", @response.body
  end
915
end
916

917 918 919 920
class ResponseDefaultHeadersTest < ActionController::TestCase
  class TestController < ActionController::Base
    def remove_header
      headers.delete params[:header]
921
      head :ok, "C" => "3"
922
    end
923 924 925 926 927

    # Render a head response, but don't touch default headers
    def leave_alone
      head :ok
    end
928 929
  end

930
  def before_setup
931
    @original = ActionDispatch::Response.default_headers
932
    @defaults = { "A" => "1", "B" => "2" }
933
    ActionDispatch::Response.default_headers = @defaults
934
    super
935 936 937 938 939 940 941 942 943
  end

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

  def setup
    super
    @controller = TestController.new
944
    @request.env["PATH_INFO"] = nil
945 946
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
947
        ActiveSupport::Deprecation.silence do
948
          get ":controller(/:action(/:id))"
949
        end
950 951 952 953 954
      end
    end
  end

  test "response contains default headers" do
955 956
    get :leave_alone

957
    # Response headers start out with the defaults
958
    assert_equal @defaults.merge("Content-Type" => "text/html"), response.headers
959
  end
960

961
  test "response deletes a default header" do
962
    get :remove_header, params: { header: "A" }
963 964 965 966
    assert_response :ok

    # After a request, the response in the test case doesn't have the
    # defaults merged on top again.
967 968 969
    assert_not_includes response.headers, "A"
    assert_includes response.headers, "B"
    assert_includes response.headers, "C"
970 971 972
  end
end

973 974 975 976 977
module EngineControllerTests
  class Engine < ::Rails::Engine
    isolate_namespace EngineControllerTests

    routes.draw do
978
      get "/" => "bar#index"
979 980 981 982 983
    end
  end

  class BarController < ActionController::Base
    def index
984
      render plain: "bar"
985 986 987 988 989 990 991 992
    end
  end

  class BarControllerTest < ActionController::TestCase
    tests BarController

    def test_engine_controller_route
      get :index
993
      assert_equal @response.body, "bar"
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    end
  end

  class BarControllerTestWithExplicitRouteSet < ActionController::TestCase
    tests BarController

    def setup
      @routes = Engine.routes
    end

    def test_engine_controller_route
      get :index
1006
      assert_equal @response.body, "bar"
1007 1008 1009 1010
    end
  end
end

1011
class InferringClassNameTest < ActionController::TestCase
1012 1013 1014 1015 1016
  def test_determine_controller_class
    assert_equal ContentController, determine_class("ContentControllerTest")
  end

  def test_determine_controller_class_with_nonsense_name
1017
    assert_nil determine_class("HelloGoodBye")
1018 1019 1020
  end

  def test_determine_controller_class_with_sensible_name_where_no_controller_exists
1021
    assert_nil determine_class("NoControllerWithThisNameTest")
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
  end

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

class CrazyNameTest < ActionController::TestCase
  tests ContentController
1032

1033 1034 1035 1036
  def test_controller_class_can_be_set_manually_not_just_inferred
    assert_equal ContentController, self.class.controller_class
  end
end
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046
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
1047
  tests "content"
1048 1049 1050 1051 1052 1053

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

1054 1055
class NamedRoutesControllerTest < ActionController::TestCase
  tests ContentController
J
Joshua Peek 已提交
1056

1057 1058
  def test_should_be_able_to_use_named_routes_before_a_request_is_done
    with_routing do |set|
1059
      set.draw { resources :contents }
1060 1061
      assert_equal "http://test.host/contents/new", new_content_url
      assert_equal "http://test.host/contents/1", content_url(id: 1)
1062 1063 1064
    end
  end
end
A
Andrew White 已提交
1065 1066 1067 1068 1069

class AnonymousControllerTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def index
1070
        render plain: params[:controller]
A
Andrew White 已提交
1071 1072 1073 1074 1075
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
1076
        ActiveSupport::Deprecation.silence do
1077
          get ":controller(/:action(/:id))"
1078
        end
A
Andrew White 已提交
1079 1080 1081 1082 1083 1084
      end
    end
  end

  def test_controller_name
    get :index
1085
    assert_equal "anonymous", @response.body
A
Andrew White 已提交
1086
  end
1087
end
1088 1089 1090 1091 1092

class RoutingDefaultsTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def post
1093
        render plain: request.fullpath
1094 1095 1096
      end

      def project
1097
        render plain: request.fullpath
1098 1099 1100 1101 1102
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
1103 1104
        get "/posts/:id", to: "anonymous#post", bucket_type: "post"
        get "/projects/:id", to: "anonymous#project", defaults: { bucket_type: "project" }
1105 1106 1107 1108 1109
      end
    end
  end

  def test_route_option_can_be_passed_via_process
1110
    get :post, params: { id: 1, bucket_type: "post" }
1111
    assert_equal "/posts/1", @response.body
1112 1113 1114
  end

  def test_route_default_is_not_required_for_building_request_uri
1115
    get :project, params: { id: 2 }
1116
    assert_equal "/projects/2", @response.body
1117 1118
  end
end