test_case_test.rb 32.8 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6
require "abstract_unit"
require "controller/fake_controllers"
require "active_support/json/decoding"
require "rails/engine"
7

8
class TestCaseTest < ActionController::TestCase
S
Shuhei Kitagawa 已提交
9
  def self.fixture_path; end
10

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

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

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

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

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

37 38
    def reset_the_session
      reset_session
39
      render plain: "ignore me"
40 41
    end

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

47
    def render_body
48
      render plain: request.body.read
49 50
    end

51
    def test_params
52
      render plain: ::JSON.dump(params.to_unsafe_h)
53 54
    end

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

    def test_request_parameters
60
      render plain: request.request_parameters.inspect
61 62
    end

63
    def test_uri
64
      render plain: request.fullpath
65
    end
66

67
    def test_format
68
      render plain: request.format
69 70
    end

71
    def test_query_string
72
      render plain: request.query_string
73 74
    end

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

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

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

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

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

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

122
    def test_file_upload
123
      render plain: params[:file].size
124
    end
125

126
    def test_send_file
B
bogdanvlviv 已提交
127
      send_file(__FILE__)
128 129
    end

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

    def redirect_to_different_controller
135
      redirect_to controller: "fail", id: 5
136 137
    end

138
    def create
139
      head :created, location: "/resource"
140 141
    end

142 143 144 145
    def render_cookie
      render plain: cookies["foo"]
    end

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

151 152 153 154 155 156 157 158
    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

159
    def boom
160
      raise "boom!"
161 162
    end

163 164 165
    private

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

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

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

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

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

199 200 201
  def test_assert_select_without_body
    get :test_without_body

202 203
    assert_select "body", 0
    assert_select "div.foo"
204 205 206 207 208
  end

  def test_assert_select_with_body
    get :test_with_body

209
    assert_select "body.foo"
210 211
  end

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

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

223
    assert_equal params.to_query, @response.body
224 225 226
  end

  def test_params_round_trip
B
bogdanvlviv 已提交
227
    params = { "foo" => { "contents" => [{ "name" => "gorby", "id" => "123" }, { "name" => "puff", "d" => "true" }] } }
228 229 230 231
    post :test_params, params: params.dup

    controller_info = { "controller" => "test_case_test/test", "action" => "test_params" }
    assert_equal params.merge(controller_info), JSON.parse(@response.body)
232 233
  end

234 235 236 237 238 239 240 241 242 243 244 245 246
  def test_handle_to_params
    klass = Class.new do
      def to_param
        "bar"
      end
    end

    post :test_params, params: { foo: klass.new }

    assert_equal JSON.parse(@response.body)["foo"], "bar"
  end


247
  def test_body_stream
248
    params = Hash[:page, { name: "page name" }, "some key", 123]
249

250 251
    post :render_body, params: params.dup

252
    assert_equal params.to_query, @response.body
253 254
  end

255
  def test_document_body_and_params_with_post
256
    post :test_params, params: { id: 1 }
257
    assert_equal({ "id" => "1", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
258
  end
259

260
  def test_document_body_with_post
261 262 263 264
    post :render_body, body: "document body"
    assert_equal "document body", @response.body
  end

265
  def test_document_body_with_put
266 267 268 269
    put :render_body, body: "document body"
    assert_equal "document body", @response.body
  end

270 271 272 273 274
  def test_head
    head :test_params
    assert_equal 200, @response.status
  end

275 276
  def test_process_without_flash
    process :set_flash
277
    assert_equal "><", flash["test"]
278 279
  end

280
  def test_process_with_flash
281 282 283
    process :set_flash,
      method: "GET",
      flash: { "test" => "value" }
284
    assert_equal ">value<", flash["test"]
285
  end
286

287
  def test_process_with_flash_now
288 289 290
    process :set_flash_now,
      method: "GET",
      flash: { "test_now" => "value_now" }
291
    assert_equal ">value_now<", flash["test_now"]
292 293
  end

294 295 296 297 298 299 300
  def test_process_delete_flash
    process :set_flash
    process :delete_flash
    assert_empty flash
    assert_empty session
  end

301 302
  def test_process_with_session
    process :set_session
303 304 305 306
    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"
307 308
  end

309
  def test_process_with_session_kwarg
310 311 312 313 314
    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]
315 316
  end

317
  def test_process_merges_session_arg
318 319 320 321
    session[:foo] = "bar"
    get :no_op, session: { bar: "baz" }
    assert_equal "bar", session[:foo]
    assert_equal "baz", session[:bar]
322 323 324
  end

  def test_merged_session_arg_is_retained_across_requests
325 326
    get :no_op, session: { foo: "bar" }
    assert_equal "bar", session[:foo]
327
    get :no_op
328
    assert_equal "bar", session[:foo]
329 330 331
  end

  def test_process_overwrites_existing_session_arg
332 333 334
    session[:foo] = "bar"
    get :no_op, session: { foo: "baz" }
    assert_equal "baz", session[:foo]
335 336
  end

337 338 339 340 341 342 343 344 345 346 347 348
  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

349 350 351 352 353 354
  def test_response_and_request_have_nice_accessors
    process :no_op
    assert_equal @response, response
    assert_equal @request, request
  end

355 356
  def test_process_with_request_uri_with_no_params
    process :test_uri
357
    assert_equal "/test_case_test/test/test_uri", @response.body
358 359
  end

360 361 362 363 364
  def test_process_with_symbol_method
    process :test_uri, method: :get
    assert_equal "/test_case_test/test/test_uri", @response.body
  end

365
  def test_process_with_request_uri_with_params
366 367 368 369
    process :test_uri,
      method: "GET",
      params: { id: 7 }

370
    assert_equal "/test_case_test/test/test_uri/7", @response.body
371
  end
372

373
  def test_process_with_request_uri_with_params_with_explicit_uri
374
    @request.env["PATH_INFO"] = "/explicit/uri"
375
    process :test_uri, method: "GET", params: { id: 7 }
376
    assert_equal "/explicit/uri", @response.body
377 378
  end

379
  def test_process_with_query_string
380 381
    process :test_query_string,
      method: "GET",
382
      params: { q: "test" }
383 384 385 386
    assert_equal "q=test", @response.body
  end

  def test_process_with_query_string_with_explicit_uri
387 388
    @request.env["PATH_INFO"] = "/explicit/uri"
    @request.env["QUERY_STRING"] = "q=test?extra=question"
389 390 391 392
    process :test_query_string
    assert_equal "q=test?extra=question", @response.body
  end

393
  def test_multiple_calls
394
    process :test_only_one_param, method: "GET", params: { left: true }
395
    assert_equal "OK", @response.body
396
    process :test_only_one_param, method: "GET", params: { right: true }
397
    assert_equal "OK", @response.body
398
  end
399

M
Matthew Draper 已提交
400 401
  def test_should_impose_childless_html_tags_in_html
    process :test_xml_output, params: { response_as: "text/html" }
402

M
Matthew Draper 已提交
403 404 405 406 407 408
    # <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" }
409

M
Matthew Draper 已提交
410 411
    # <area> is not special, so the <p> is its child
    assert_select "root > area > p"
412
  end
413

414
  def test_assert_generates
415
    assert_generates "controller/action/5", controller: "controller", action: "action", id: "5"
K
Koichi ITO 已提交
416 417 418
    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" }
419
    assert_generates "controller/action/7", { id: "7" }, { controller: "controller", action: "action", name: "bob" }, {}
420
  end
421

422
  def test_assert_routing
423
    assert_routing "content", controller: "content", action: "index"
424 425
  end

426 427
  def test_assert_routing_with_method
    with_routing do |set|
428
      set.draw { resources(:content) }
K
Koichi ITO 已提交
429
      assert_routing({ method: "post", path: "content" }, { controller: "content", action: "create" })
430 431 432
    end
  end

433
  def test_assert_routing_in_module
434 435 436
    with_routing do |set|
      set.draw do
        namespace :admin do
437
          get "user" => "user#index"
438 439 440
        end
      end

441
      assert_routing "admin/user", controller: "admin/user", action: "index"
442
    end
443
  end
444

445 446
  def test_assert_routing_with_glob
    with_routing do |set|
447
      set.draw { get("*path" => "pages#show") }
448
      assert_routing("/company/about", controller: "pages", action: "show", path: "company/about")
449 450
    end
  end
451

452
  def test_params_passing
453 454 455
    get :test_params, params: {
      page: {
        name: "Page name",
456 457 458
        month: "4",
        year: "2004",
        day: "6"
459 460
      }
    }
461
    parsed_params = ::JSON.parse(@response.body)
462
    assert_equal(
463
      {
464 465
        "controller" => "test_case_test/test", "action" => "test_params",
        "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" }
466
      },
467 468 469 470
      parsed_params
    )
  end

471
  def test_query_param_named_action
472
    get :test_query_parameters, params: { action: "foobar" }
473
    parsed_params = JSON.parse(@response.body)
474
    assert_equal({ "action" => "foobar" }, parsed_params)
475 476 477
  end

  def test_request_param_named_action
478
    post :test_request_parameters, params: { action: "foobar" }
479
    parsed_params = eval(@response.body)
480
    assert_equal({ "action" => "foobar" }, parsed_params)
481 482
  end

483 484 485 486
  def test_kwarg_params_passing_with_session_and_flash
    get :test_params, params: {
      page: {
        name: "Page name",
487 488 489
        month: "4",
        year: "2004",
        day: "6"
490
      }
491
    }, session: { "foo" => "bar" }, flash: { notice: "created" }
492

493
    parsed_params = ::JSON.parse(@response.body)
494
    assert_equal(
495 496
      { "controller" => "test_case_test/test", "action" => "test_params",
       "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" } },
497 498
      parsed_params
    )
499

500 501
    assert_equal "bar", session[:foo]
    assert_equal "created", flash[:notice]
502 503
  end

504
  def test_params_passing_with_integer
505 506 507
    get :test_params, params: {
      page: { name: "Page name", month: 4, year: 2004, day: 6 }
    }
508
    parsed_params = ::JSON.parse(@response.body)
509
    assert_equal(
510 511
      { "controller" => "test_case_test/test", "action" => "test_params",
       "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" } },
512 513 514 515
      parsed_params
    )
  end

516
  def test_params_passing_with_integers_when_not_html_request
517
    get :test_params, params: { format: "json", count: 999 }
518
    parsed_params = ::JSON.parse(@response.body)
519
    assert_equal(
520
      { "controller" => "test_case_test/test", "action" => "test_params",
521
       "format" => "json", "count" => "999" },
522 523 524 525 526
      parsed_params
    )
  end

  def test_params_passing_path_parameter_is_string_when_not_html_request
527
    get :test_params, params: { format: "json", id: 1 }
528
    parsed_params = ::JSON.parse(@response.body)
529
    assert_equal(
530
      { "controller" => "test_case_test/test", "action" => "test_params",
531
       "format" => "json", "id" => "1" },
532 533 534 535
      parsed_params
    )
  end

536 537
  def test_params_passing_with_frozen_values
    assert_nothing_raised do
538
      get :test_params, params: {
539
        frozen: "icy".freeze, frozens: ["icy".freeze].freeze, deepfreeze: { frozen: "icy".freeze }.freeze
540
      }
541
    end
542
    parsed_params = ::JSON.parse(@response.body)
543
    assert_equal(
544 545
      { "controller" => "test_case_test/test", "action" => "test_params",
       "frozen" => "icy", "frozens" => ["icy"], "deepfreeze" => { "frozen" => "icy" } },
546 547 548 549
      parsed_params
    )
  end

550
  def test_params_passing_doesnt_modify_in_place
551
    page = { name: "Page name", month: 4, year: 2004, day: 6 }
552
    get :test_params, params: { page: page }
553 554 555
    assert_equal 2004, page[:year]
  end

556
  test "set additional HTTP headers" do
557 558
    @request.headers["Referer"] = "http://nohost.com/home"
    @request.headers["Content-Type"] = "application/rss+xml"
559
    get :test_headers
560
    parsed_env = ActiveSupport::JSON.decode(@response.body)
561 562 563 564 565
    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
566 567
    @request.headers["HTTP_REFERER"] = "http://example.com/about"
    @request.headers["CONTENT_TYPE"] = "application/json"
568
    get :test_headers
569
    parsed_env = ActiveSupport::JSON.decode(@response.body)
570 571 572 573
    assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
    assert_equal "application/json", parsed_env["CONTENT_TYPE"]
  end

574 575 576 577 578 579 580 581 582
  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

583 584 585 586 587
  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

588
  def test_mutating_content_type_headers_for_plain_text_files_sets_the_header
589 590
    @request.headers["Content-Type"] = "text/plain"
    post :render_body, params: { name: "foo.txt" }
591

592 593 594
    assert_equal "text/plain", @request.headers["Content-type"]
    assert_equal "foo.txt", @request.request_parameters[:name]
    assert_equal "render_body", @request.path_parameters[:action]
595 596 597
  end

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

601 602 603
    assert_equal "text/html", @request.headers["Content-type"]
    assert_equal "foo.html", @request.request_parameters[:name]
    assert_equal "render_body", @request.path_parameters[:action]
604 605 606 607
  end

  def test_mutating_content_type_headers_for_non_registered_mime_type_raises_an_error
    assert_raises(RuntimeError) do
608 609
      @request.headers["Content-Type"] = "type/fake"
      post :render_body, params: { name: "foo.fake" }
610 611 612
    end
  end

613
  def test_id_converted_to_string
614 615 616 617 618 619
    get :test_params, params: {
      id: 20, foo: Object.new
    }
    assert_kind_of String, @request.path_parameters[:id]
  end

620 621
  def test_array_path_parameter_handled_properly
    with_routing do |set|
622
      set.draw do
623
        get "file/*path", to: "test_case_test/test#test_params"
624 625

        ActiveSupport::Deprecation.silence do
626
          get ":controller/:action"
627
        end
628
      end
629

630 631 632
      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
633 634 635 636
    end
  end

  def test_assert_realistic_path_parameters
637
    get :test_params, params: { id: 20, foo: Object.new }
638

639
    # All elements of path_parameters should use Symbol keys
640
    @request.path_parameters.each_key do |key|
641
      assert_kind_of Symbol, key
642 643 644 645
    end
  end

  def test_with_routing_places_routes_back
J
Joshua Peek 已提交
646 647
    assert @routes
    routes_id = @routes.object_id
648

649
    begin
650 651
      with_routing { raise "fail" }
      fail "Should not be here."
652
    rescue RuntimeError
653
    end
654

J
Joshua Peek 已提交
655 656
    assert @routes
    assert_equal routes_id, @routes.object_id
657
  end
658 659 660 661 662 663 664 665 666

  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
667

668
  def test_header_properly_reset_after_remote_http_request
669
    get :test_params, xhr: true
670 671
    assert_nil @request.env["HTTP_X_REQUESTED_WITH"]
    assert_nil @request.env["HTTP_ACCEPT"]
672 673
  end

674
  def test_xhr_with_params
675
    get :test_params, params: { id: 1 }, xhr: true
676

677
    assert_equal({ "id" => "1", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
678 679 680
  end

  def test_xhr_with_session
681 682
    get :set_session, xhr: true

683 684 685 686
    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"
687 688
  end

G
Guo Xiang Tan 已提交
689
  def test_params_reset_between_post_requests
690
    post :no_op, params: { foo: "bar" }
691
    assert_equal "bar", @request.params[:foo]
G
Guo Xiang Tan 已提交
692

693
    post :no_op
694
    assert_predicate @request.params[:foo], :blank?
695 696
  end

697
  def test_filtered_parameters_reset_between_requests
698
    get :no_op, params: { foo: "bar" }
699 700
    assert_equal "bar", @request.filtered_parameters[:foo]

701
    get :no_op, params: { foo: "baz" }
702 703 704
    assert_equal "baz", @request.filtered_parameters[:foo]
  end

705 706 707 708 709 710 711 712
  def test_raw_post_reset_between_post_requests
    post :no_op, params: { foo: "bar" }
    assert_equal "foo=bar", @request.raw_post

    post :no_op, params: { foo: "baz" }
    assert_equal "foo=baz", @request.raw_post
  end

713 714 715 716 717 718 719 720
  def test_content_length_reset_after_post_request
    post :no_op, params: { foo: "bar" }
    assert_not_equal 0, @request.content_length

    get :no_op
    assert_equal 0, @request.content_length
  end

721 722
  def test_path_is_kept_after_the_request
    get :test_params, params: { id: "foo" }
R
Rafael Mendonça França 已提交
723
    assert_equal "/test_case_test/test/test_params/foo", @request.path
724 725
  end

G
Guo Xiang Tan 已提交
726
  def test_path_params_reset_between_request
727
    get :test_params, params: { id: "foo" }
728
    assert_equal "foo", @request.path_parameters[:id]
G
Guo Xiang Tan 已提交
729

730
    get :test_params
731
    assert_nil @request.path_parameters[:id]
732 733
  end

A
Andrew White 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746
  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

747
  def test_request_format
748 749
    get :test_format, params: { format: "html" }
    assert_equal "text/html", @response.body
750

751 752
    get :test_format, params: { format: "json" }
    assert_equal "application/json", @response.body
753

754 755
    get :test_format, params: { format: "xml" }
    assert_equal "application/xml", @response.body
756 757

    get :test_format
758
    assert_equal "text/html", @response.body
759 760
  end

761
  def test_request_format_kwarg
762 763
    get :test_format, format: "html"
    assert_equal "text/html", @response.body
764

765 766
    get :test_format, format: "json"
    assert_equal "application/json", @response.body
767

768 769
    get :test_format, format: "xml"
    assert_equal "application/xml", @response.body
770 771

    get :test_format
772
    assert_equal "text/html", @response.body
773 774 775
  end

  def test_request_format_kwarg_overrides_params
776 777
    get :test_format, format: "json", params: { format: "html" }
    assert_equal "application/json", @response.body
778 779
  end

780 781 782 783 784 785 786 787
  def test_request_format_kwarg_doesnt_mutate_params
    params = { foo: "bar" }.freeze

    assert_nothing_raised do
      get :test_format, format: "json", params: params
    end
  end

788
  def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
789
    cookies["foo"] = "bar"
790
    get :no_op
791
    assert_equal "bar", cookies["foo"]
792 793 794
  end

  def test_cookies_should_be_escaped_properly
795
    cookies["foo"] = "+"
796
    get :render_cookie
797
    assert_equal "+", @response.body
798 799 800
  end

  def test_should_detect_if_cookie_is_deleted
801
    cookies["foo"] = "bar"
802
    get :delete_cookie
803
    assert_nil cookies["foo"]
804 805
  end

806
  def test_multiple_mixed_method_process_should_scrub_rack_input
807
    post :test_params, params: { id: 1, foo: "an foo" }
808
    assert_equal({ "id" => "1", "foo" => "an foo", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
809

810
    get :test_params, params: { bar: "an bar" }
811
    assert_equal({ "bar" => "an bar", "controller" => "test_case_test/test", "action" => "test_params" }, ::JSON.parse(@response.body))
812 813
  end

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

B
bogdanvlviv 已提交
830
  FILES_DIR = File.expand_path("../fixtures/multipart", __dir__)
831

832 833
  READ_BINARY = "rb:binary"
  READ_PLAIN = "r:binary"
834

835
  def test_test_uploaded_file
836
    filename = "ruby_on_rails.jpg"
837
    path = "#{FILES_DIR}/#{filename}"
838
    content_type = "image/png"
839
    expected = File.read(path)
840
    expected.force_encoding(Encoding::BINARY)
841

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

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

853
  def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
854
    TestCaseTest.stub :fixture_path, FILES_DIR do
855 856
      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
857
    end
858 859
  end

860
  def test_test_uploaded_file_with_binary
861
    filename = "ruby_on_rails.jpg"
862
    path = "#{FILES_DIR}/#{filename}"
863
    content_type = "image/png"
J
Joshua Peek 已提交
864

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

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

  def test_fixture_file_upload_with_binary
873
    filename = "ruby_on_rails.jpg"
874
    path = "#{FILES_DIR}/#{filename}"
875
    content_type = "image/jpg"
J
Joshua Peek 已提交
876

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

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

884
  def test_fixture_file_upload_should_be_able_access_to_tempfile
885
    file = fixture_file_upload(FILES_DIR + "/ruby_on_rails.jpg", "image/jpg")
D
Daniel Colson 已提交
886
    assert_respond_to file, :tempfile
887 888
  end

889
  def test_fixture_file_upload
890 891
    post :test_file_upload,
      params: {
892
        file: fixture_file_upload(FILES_DIR + "/ruby_on_rails.jpg", "image/jpg")
893
      }
894
    assert_equal "45142", @response.body
895
  end
896

897
  def test_fixture_file_upload_relative_to_fixture_path
898
    TestCaseTest.stub :fixture_path, FILES_DIR do
899 900
      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
901
    end
902 903
  end

904
  def test_fixture_file_upload_ignores_fixture_path_given_full_path
B
bogdanvlviv 已提交
905
    TestCaseTest.stub :fixture_path, __dir__ do
906 907
      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
908 909 910
    end
  end

911
  def test_fixture_file_upload_ignores_nil_fixture_path
912 913
    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
914 915
  end

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

925
  def test_test_uploaded_file_exception_when_file_doesnt_exist
926
    assert_raise(RuntimeError) { Rack::Test::UploadedFile.new("non_existent_file") }
927
  end
928

929 930 931 932 933
  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.
934
    assert_equal "/resource", @response.redirect_url
935 936 937
    assert_equal @response.redirect_url, redirect_to_url

    # Must be a :redirect response.
938
    assert_raise(ActiveSupport::TestCase::Assertion) do
939
      assert_redirected_to "/resource"
940 941
    end
  end
942 943 944 945 946 947 948 949 950 951 952

  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",
953
        params: { q: "test1" }
954 955 956 957
    end

    process :test_query_string,
      method: "GET",
958
      params: { q: "test2" }
959 960 961

    assert_equal "q=test2", @response.body
  end
962
end
963

964 965 966 967
class ResponseDefaultHeadersTest < ActionController::TestCase
  class TestController < ActionController::Base
    def remove_header
      headers.delete params[:header]
968
      head :ok, "C" => "3"
969
    end
970 971 972 973 974

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

977
  def before_setup
978
    @original = ActionDispatch::Response.default_headers
979
    @defaults = { "A" => "1", "B" => "2" }
980
    ActionDispatch::Response.default_headers = @defaults
981
    super
982 983 984 985 986 987 988 989 990
  end

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

  def setup
    super
    @controller = TestController.new
991
    @request.env["PATH_INFO"] = nil
992 993
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
994
        ActiveSupport::Deprecation.silence do
995
          get ":controller(/:action(/:id))"
996
        end
997 998 999 1000 1001
      end
    end
  end

  test "response contains default headers" do
1002 1003
    get :leave_alone

1004
    # Response headers start out with the defaults
1005
    assert_equal @defaults.merge("Content-Type" => "text/html"), response.headers
1006
  end
1007

1008
  test "response deletes a default header" do
1009
    get :remove_header, params: { header: "A" }
1010 1011 1012 1013
    assert_response :ok

    # After a request, the response in the test case doesn't have the
    # defaults merged on top again.
1014 1015 1016
    assert_not_includes response.headers, "A"
    assert_includes response.headers, "B"
    assert_includes response.headers, "C"
1017 1018 1019
  end
end

1020 1021 1022 1023 1024
module EngineControllerTests
  class Engine < ::Rails::Engine
    isolate_namespace EngineControllerTests

    routes.draw do
1025
      get "/" => "bar#index"
1026 1027 1028 1029 1030
    end
  end

  class BarController < ActionController::Base
    def index
1031
      render plain: "bar"
1032 1033 1034 1035 1036 1037 1038 1039
    end
  end

  class BarControllerTest < ActionController::TestCase
    tests BarController

    def test_engine_controller_route
      get :index
1040
      assert_equal @response.body, "bar"
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    end
  end

  class BarControllerTestWithExplicitRouteSet < ActionController::TestCase
    tests BarController

    def setup
      @routes = Engine.routes
    end

    def test_engine_controller_route
      get :index
1053
      assert_equal @response.body, "bar"
1054 1055 1056 1057
    end
  end
end

1058
class InferringClassNameTest < ActionController::TestCase
1059 1060 1061 1062 1063
  def test_determine_controller_class
    assert_equal ContentController, determine_class("ContentControllerTest")
  end

  def test_determine_controller_class_with_nonsense_name
1064
    assert_nil determine_class("HelloGoodBye")
1065 1066 1067
  end

  def test_determine_controller_class_with_sensible_name_where_no_controller_exists
1068
    assert_nil determine_class("NoControllerWithThisNameTest")
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
  end

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

class CrazyNameTest < ActionController::TestCase
  tests ContentController
1079

1080 1081 1082 1083
  def test_controller_class_can_be_set_manually_not_just_inferred
    assert_equal ContentController, self.class.controller_class
  end
end
1084

1085 1086 1087 1088 1089 1090 1091 1092 1093
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
1094
  tests "content"
1095 1096 1097 1098 1099 1100

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

1101 1102
class NamedRoutesControllerTest < ActionController::TestCase
  tests ContentController
J
Joshua Peek 已提交
1103

1104 1105
  def test_should_be_able_to_use_named_routes_before_a_request_is_done
    with_routing do |set|
1106
      set.draw { resources :contents }
1107 1108
      assert_equal "http://test.host/contents/new", new_content_url
      assert_equal "http://test.host/contents/1", content_url(id: 1)
1109 1110 1111
    end
  end
end
A
Andrew White 已提交
1112 1113 1114 1115 1116

class AnonymousControllerTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def index
1117
        render plain: params[:controller]
A
Andrew White 已提交
1118 1119 1120 1121 1122
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
1123
        ActiveSupport::Deprecation.silence do
1124
          get ":controller(/:action(/:id))"
1125
        end
A
Andrew White 已提交
1126 1127 1128 1129 1130 1131
      end
    end
  end

  def test_controller_name
    get :index
1132
    assert_equal "anonymous", @response.body
A
Andrew White 已提交
1133
  end
1134
end
1135 1136 1137 1138 1139

class RoutingDefaultsTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def post
1140
        render plain: request.fullpath
1141 1142 1143
      end

      def project
1144
        render plain: request.fullpath
1145 1146 1147 1148 1149
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
1150 1151
        get "/posts/:id", to: "anonymous#post", bucket_type: "post"
        get "/projects/:id", to: "anonymous#project", defaults: { bucket_type: "project" }
1152 1153 1154 1155 1156
      end
    end
  end

  def test_route_option_can_be_passed_via_process
1157
    get :post, params: { id: 1, bucket_type: "post" }
1158
    assert_equal "/posts/1", @response.body
1159 1160 1161
  end

  def test_route_default_is_not_required_for_building_request_uri
1162
    get :project, params: { id: 2 }
1163
    assert_equal "/projects/2", @response.body
1164 1165
  end
end