test_case.rb 21.3 KB
Newer Older
1
require 'rack/session/abstract/id'
M
Marcin Olichwirowicz 已提交
2
require 'active_support/core_ext/hash/conversions'
3
require 'active_support/core_ext/object/to_query'
4
require 'active_support/core_ext/module/anonymous'
A
Akira Matsuda 已提交
5
require 'active_support/core_ext/hash/keys'
6
require 'action_controller/template_assertions'
7 8
require 'rails-dom-testing'

9
module ActionController
10
  class TestRequest < ActionDispatch::TestRequest #:nodoc:
11 12 13
    DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
    DEFAULT_ENV.delete 'PATH_INFO'

14 15 16 17
    def self.new_session
      TestSession.new
    end

18 19 20 21
    # Create a new test request with default `env` values
    def self.create
      env = {}
      env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
22
      env["rack.request.cookie_hash"] = {}.with_indifferent_access
23 24 25 26 27 28 29 30
      new(default_env.merge(env), new_session)
    end

    def self.default_env
      DEFAULT_ENV
    end
    private_class_method :default_env

31 32
    def initialize(env, session)
      super(env)
33

34
      self.session = session
35
      self.session_options = TestSession::DEFAULT_OPTIONS
36 37
    end

38 39
    def query_string=(string)
      @env[Rack::QUERY_STRING] = string
40 41 42 43 44 45
    end

    def request_parameters=(params)
      @env["action_dispatch.request.request_parameters"] = params
    end

46
    def assign_parameters(routes, controller_path, action, parameters, generated_path, query_string_keys)
A
Aaron Patterson 已提交
47
      non_path_parameters = {}
48
      path_parameters = {}
49

50
      parameters.each do |key, value|
51
        if query_string_keys.include?(key)
52 53
          non_path_parameters[key] = value
        else
54
          if value.is_a?(Array)
55
            value = value.map(&:to_param)
56 57 58 59
          else
            value = value.to_param
          end

60
          path_parameters[key] = value
61 62 63
        end
      end

64
      if get?
65 66 67
        if self.query_string.blank?
          self.query_string = non_path_parameters.to_query
        end
68
      else
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        if ENCODER.should_multipart?(non_path_parameters)
          @env['CONTENT_TYPE'] = ENCODER.content_type
          data = ENCODER.build_multipart non_path_parameters
        else
          @env['CONTENT_TYPE'] ||= 'application/x-www-form-urlencoded'

          # FIXME: setting `request_parametes` is normally handled by the
          # params parser middleware, and we should remove this roundtripping
          # when we switch to caling `call` on the controller

          case content_mime_type.ref
          when :json
            data = ActiveSupport::JSON.encode(non_path_parameters)
            params = ActiveSupport::JSON.decode(data).with_indifferent_access
            self.request_parameters = params
          when :xml
            data = non_path_parameters.to_xml
            params = Hash.from_xml(data)['hash']
            self.request_parameters = params
          when :url_encoded_form
            data = non_path_parameters.to_query
          else
            raise "Unknown Content-Type: #{content_type}"
          end
        end
94 95 96

        @env['CONTENT_LENGTH'] = data.length.to_s
        @env['rack.input'] = StringIO.new(data)
97 98
      end

99
      @env["PATH_INFO"] ||= generated_path
100 101 102
      path_parameters[:controller] = controller_path
      path_parameters[:action] = action

103
      self.path_parameters = path_parameters
104
    end
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

    ENCODER = Class.new do
      include Rack::Test::Utils

      def should_multipart?(params)
        # FIXME: lifted from Rack-Test. We should push this separation upstream
        multipart = false
        query = lambda { |value|
          case value
          when Array
            value.each(&query)
          when Hash
            value.values.each(&query)
          when Rack::Test::UploadedFile
            multipart = true
          end
        }
        params.values.each(&query)
        multipart
      end

      public :build_multipart

      def content_type
        "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}"
      end
    end.new
132 133
  end

134
  class LiveTestResponse < Live::Response
135 136 137 138 139 140 141 142
    # Was the response successful?
    alias_method :success?, :successful?

    # Was the URL not found?
    alias_method :missing?, :not_found?

    # Was there a server-side error?
    alias_method :error?, :server_error?
143 144
  end

145 146
  # Methods #destroy and #load! are overridden to avoid calling methods on the
  # @store object, which does not exist for the TestSession class.
147 148
  class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
    DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
149 150

    def initialize(session = {})
151
      super(nil, nil)
152 153
      @id = SecureRandom.hex(16)
      @data = stringify_keys(session)
154 155
      @loaded = true
    end
156

157 158 159
    def exists?
      true
    end
160

161 162 163 164 165 166 167 168
    def keys
      @data.keys
    end

    def values
      @data.values
    end

169 170 171 172
    def destroy
      clear
    end

173 174 175 176
    def fetch(*args, &block)
      @data.fetch(*args, &block)
    end

177 178 179 180 181
    private

      def load!
        @id
      end
182 183
  end

P
Pratik Naik 已提交
184 185
  # Superclass for ActionController functional tests. Functional tests allow you to
  # test a single controller action per test method. This should not be confused with
186
  # integration tests (see ActionDispatch::IntegrationTest), which are more like
187
  # "stories" that can involve multiple controllers and multiple actions (i.e. multiple
P
Pratik Naik 已提交
188
  # different HTTP requests).
P
Pratik Naik 已提交
189
  #
P
Pratik Naik 已提交
190 191 192
  # == Basic example
  #
  # Functional tests are written as follows:
193
  # 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
P
Pratik Naik 已提交
194 195 196 197 198 199 200 201 202
  #    an HTTP request.
  # 2. Then, one asserts whether the current state is as expected. "State" can be anything:
  #    the controller's HTTP response, the database contents, etc.
  #
  # For example:
  #
  #   class BooksControllerTest < ActionController::TestCase
  #     def test_create
  #       # Simulate a POST response with the given HTTP parameters.
203
  #       post(:create, params: { book: { title: "Love Hina" }})
P
Pratik Naik 已提交
204 205 206 207 208 209
  #
  #       # Assert that the controller tried to redirect us to
  #       # the created book's URI.
  #       assert_response :found
  #
  #       # Assert that the controller really put the book in the database.
210
  #       assert_not_nil Book.find_by(title: "Love Hina")
P
Pratik Naik 已提交
211 212 213
  #     end
  #   end
  #
214 215 216
  # You can also send a real document in the simulated HTTP request.
  #
  #   def test_create
A
AvnerCohen 已提交
217
  #     json = {book: { title: "Love Hina" }}.to_json
218
  #     post :create, json
R
Rafael Mendonça França 已提交
219
  #   end
220
  #
P
Pratik Naik 已提交
221 222 223 224 225 226 227 228 229 230 231 232
  # == Special instance variables
  #
  # ActionController::TestCase will also automatically provide the following instance
  # variables for use in the tests:
  #
  # <b>@controller</b>::
  #      The controller instance that will be tested.
  # <b>@request</b>::
  #      An ActionController::TestRequest, representing the current HTTP
  #      request. You can modify this object before sending the HTTP request. For example,
  #      you might want to set some session properties before sending a GET request.
  # <b>@response</b>::
233
  #      An ActionDispatch::TestResponse object, representing the response
P
Pratik Naik 已提交
234 235 236 237
  #      of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
  #      after calling +post+. If the various assert methods are not sufficient, then you
  #      may use this object to inspect the HTTP response in detail.
  #
J
Joost Baaij 已提交
238
  # (Earlier versions of \Rails required each functional test to subclass
P
Pratik Naik 已提交
239
  # Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
P
Pratik Naik 已提交
240
  #
P
Pratik Naik 已提交
241
  # == Controller is automatically inferred
P
Pratik Naik 已提交
242
  #
P
Pratik Naik 已提交
243 244
  # ActionController::TestCase will automatically infer the controller under test
  # from the test class name. If the controller cannot be inferred from the test
P
Pratik Naik 已提交
245
  # class name, you can explicitly set it with +tests+.
P
Pratik Naik 已提交
246 247 248 249
  #
  #   class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
  #     tests WidgetController
  #   end
250
  #
J
Joost Baaij 已提交
251
  # == \Testing controller internals
252 253 254 255 256 257
  #
  # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
  # can be used against. These collections are:
  #
  # * session: Objects being saved in the session.
  # * flash: The flash objects currently in the session.
J
Joost Baaij 已提交
258
  # * cookies: \Cookies being sent to the user on this request.
259 260 261 262 263 264
  #
  # These collections can be used just like any other hash:
  #
  #   assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
  #   assert flash.empty? # makes sure that there's nothing in the flash
  #
265
  # On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
266 267 268 269
  #
  # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
  # action call which can then be asserted against.
  #
270
  # == Manipulating session and cookie variables
271
  #
272 273
  # Sometimes you need to set up the session and cookie variables for a test.
  # To do this just assign a value to the session or cookie collection:
274
  #
275 276
  #   session[:key] = "value"
  #   cookies[:key] = "value"
277
  #
278
  # To clear the cookies for a test just clear the cookie collection:
279
  #
280
  #   cookies.clear
281
  #
J
Joost Baaij 已提交
282
  # == \Testing named routes
283 284 285
  #
  # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
  #
A
AvnerCohen 已提交
286
  #  assert_redirected_to page_url(title: 'foo')
287
  class TestCase < ActiveSupport::TestCase
288 289 290
    module Behavior
      extend ActiveSupport::Concern
      include ActionDispatch::TestProcess
291
      include ActiveSupport::Testing::ConstantLookup
292
      include Rails::Dom::Testing::Assertions
293

294
      attr_reader :response, :request
295

296
      module ClassMethods
297

298
        # Sets the controller class name. Useful if the name can't be inferred from test class.
299
        # Normalizes +controller_class+ before using.
300 301 302 303
        #
        #   tests WidgetController
        #   tests :widget
        #   tests 'widget'
304
        def tests(controller_class)
305 306
          case controller_class
          when String, Symbol
307
            self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize
308 309 310 311 312
          when Class
            self.controller_class = controller_class
          else
            raise ArgumentError, "controller class must be a String, Symbol, or Class"
          end
313
        end
314

315
        def controller_class=(new_class)
316
          self._controller_class = new_class
317
        end
318

319
        def controller_class
320
          if current_controller_class = self._controller_class
321 322 323 324 325
            current_controller_class
          else
            self.controller_class = determine_default_controller_class(name)
          end
        end
326

327
        def determine_default_controller_class(name)
328 329 330
          determine_constant_from_test_name(name) do |constant|
            Class === constant && constant < ActionController::Metal
          end
331
        end
332
      end
333

334 335
      # Simulate a GET request with the given parameters.
      #
336
      # - +action+: The controller action to call.
337 338
      # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+.
      # - +body+: The request body with a string that is appropriately encoded
339
      #   (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
340 341
      # - +session+: A hash of parameters to store in the session. This may be +nil+.
      # - +flash+: A hash of parameters to store in the flash. This may be +nil+.
X
Xavier Noria 已提交
342
      #
343 344
      # You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with
      # +post+, +patch+, +put+, +delete+, and +head+.
345 346 347 348 349 350
      # Example sending parameters, session and setting a flash message:
      #
      #   get :show,
      #     params: { id: 7 },
      #     session: { user_id: 1 },
      #     flash: { notice: 'This is flash message' }
351 352 353
      #
      # Note that the request method is not verified. The different methods are
      # available to make the tests more expressive.
354
      def get(action, *args)
E
eileencodes 已提交
355 356 357
        res = process_with_kwargs("GET", action, *args)
        cookies.update res.cookies
        res
358 359
      end

360
      # Simulate a POST request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
361
      # See +get+ for more details.
362
      def post(action, *args)
363
        process_with_kwargs("POST", action, *args)
364
      end
365

366
      # Simulate a PATCH request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
367
      # See +get+ for more details.
368
      def patch(action, *args)
369
        process_with_kwargs("PATCH", action, *args)
370 371
      end

372
      # Simulate a PUT request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
373
      # See +get+ for more details.
374
      def put(action, *args)
375
        process_with_kwargs("PUT", action, *args)
376
      end
377

378
      # Simulate a DELETE request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
379
      # See +get+ for more details.
380
      def delete(action, *args)
381
        process_with_kwargs("DELETE", action, *args)
382
      end
383

384
      # Simulate a HEAD request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
385
      # See +get+ for more details.
386
      def head(action, *args)
387
        process_with_kwargs("HEAD", action, *args)
388 389
      end

390
      def xml_http_request(*args)
391 392 393 394 395
        ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
          xhr and xml_http_request methods are deprecated in favor of
          `get :index, xhr: true` and `post :create, xhr: true`
        MSG

396
        @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
397
        @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
398
        __send__(*args).tap do
399 400 401 402 403 404
          @request.env.delete 'HTTP_X_REQUESTED_WITH'
          @request.env.delete 'HTTP_ACCEPT'
        end
      end
      alias xhr :xml_http_request

405 406 407 408
      # Simulate a HTTP request to +action+ by specifying request method,
      # parameters and set/volley the response.
      #
      # - +action+: The controller action to call.
409 410
      # - +method+: Request method used to send the HTTP request. Possible values
      #   are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+. Can be a symbol.
411 412
      # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+.
      # - +body+: The request body with a string that is appropriately encoded
413
      #   (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
414 415
      # - +session+: A hash of parameters to store in the session. This may be +nil+.
      # - +flash+: A hash of parameters to store in the flash. This may be +nil+.
416
      # - +format+: Request format. Defaults to +nil+. Can be string or symbol.
417
      #
418
      # Example calling +create+ action and sending two params:
419
      #
420 421 422 423 424 425 426
      #   process :create,
      #     method: 'POST',
      #     params: {
      #       user: { name: 'Gaurish Sharma', email: 'user@example.com' }
      #     },
      #     session: { user_id: 1 },
      #     flash: { notice: 'This is flash message' }
427
      #
428 429 430
      # To simulate +GET+, +POST+, +PATCH+, +PUT+, +DELETE+ and +HEAD+ requests
      # prefer using #get, #post, #patch, #put, #delete and #head methods
      # respectively which will make tests more expressive.
431 432
      #
      # Note that the request method is not verified.
433
      def process(action, *args)
434
        check_required_ivars
A
Aaron Patterson 已提交
435

436
        if kwarg_request?(args)
437
          parameters, session, body, flash, http_method, format, xhr = args[0].values_at(:params, :session, :body, :flash, :method, :format, :xhr)
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        else
          http_method, parameters, session, flash = args
          format = nil

          if parameters.is_a?(String) && http_method != 'HEAD'
            body = parameters
            parameters = nil
          end

          if parameters.present? || session.present? || flash.present?
            non_kwarg_request_warning
          end
        end

        if body.present?
          @request.env['RAW_POST_DATA'] = body
        end

        if http_method.present?
          http_method = http_method.to_s.upcase
        else
          http_method = "GET"
460
        end
A
Aaron Patterson 已提交
461

462
        parameters ||= {}
A
Aaron Patterson 已提交
463

464 465 466 467
        if format.present?
          parameters[:format] = format
        end

468 469
        @html_document = nil

A
Aaron Patterson 已提交
470 471 472 473
        unless @controller.respond_to?(:recycle!)
          @controller.extend(Testing::Functional)
        end

474 475 476 477
        self.cookies.update @request.cookies
        @request.env['HTTP_COOKIE'] = cookies.to_header
        @request.env['action_dispatch.cookies'] = nil

478
        @request          = TestRequest.new scrub_env!(@request.env), @request.session
479 480
        @response         = build_response @response_klass
        @response.request = @request
A
Aaron Patterson 已提交
481
        @controller.recycle!
482

483
        @request.env['REQUEST_METHOD'] = http_method
484

485
        parameters = parameters.symbolize_keys
486

487 488 489 490 491
        generated_extras = @routes.generate_extras(parameters.merge(controller: controller_class_name, action: action.to_s))
        generated_path = generated_path(generated_extras)
        query_string_keys = query_parameter_names(generated_extras)

        @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters, generated_path, query_string_keys)
492

493
        @request.session.update(session) if session
494
        @request.flash.update(flash || {})
495

496 497 498 499 500
        if xhr
          @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
          @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
        end

501 502 503
        @controller.request  = @request
        @controller.response = @response

504
        @request.env["SCRIPT_NAME"] ||= @controller.config.relative_url_root
505

506
        @controller.recycle!
507
        @controller.process(action)
508

509 510
        @request.env.delete 'HTTP_COOKIE'

511
        if cookies = @request.env['action_dispatch.cookies']
512
          unless @response.committed?
513
            cookies.write(@response)
E
eileencodes 已提交
514
            self.cookies.update(cookies.instance_variable_get(:@cookies))
515
          end
516 517 518
        end
        @response.prepare!

519
        if flash_value = @request.flash.to_session_value
520
          @request.session['flash'] = flash_value
521 522
        else
          @request.session.delete('flash')
523 524
        end

525 526 527 528
        if xhr
          @request.env.delete 'HTTP_X_REQUESTED_WITH'
          @request.env.delete 'HTTP_ACCEPT'
        end
529
        @request.query_string = ''
530

531
        @response
532 533
      end

534 535 536 537 538 539 540 541 542 543 544 545
      def controller_class_name
        @controller.class.anonymous? ? "anonymous" : @controller.class.controller_path
      end

      def generated_path(generated_extras)
        generated_extras[0]
      end

      def query_parameter_names(generated_extras)
        generated_extras[1] + [:controller, :action]
      end

546
      def setup_controller_request_and_response
547 548
        @controller = nil unless defined? @controller

549
        @response_klass = ActionDispatch::TestResponse
550

551
        if klass = self.class.controller_class
552
          if klass < ActionController::Live
553
            @response_klass = LiveTestResponse
554
          end
555 556 557 558 559 560 561
          unless @controller
            begin
              @controller = klass.new
            rescue
              warn "could not construct controller #{klass}" if $VERBOSE
            end
          end
562
        end
563

564
        @request          = TestRequest.create
565
        @response         = build_response @response_klass
566 567
        @response.request = @request

568
        if @controller
569 570 571
          @controller.request = @request
          @controller.params = {}
        end
572 573
      end

574 575
      def build_response(klass)
        klass.new
576 577
      end

578 579 580
      included do
        include ActionController::TemplateAssertions
        include ActionDispatch::Assertions
581
        class_attribute :_controller_class
582 583
        setup :setup_controller_request_and_response
      end
584

A
Aaron Patterson 已提交
585
      private
586

587 588 589
      def scrub_env!(env)
        env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
        env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
590
        env.delete 'action_dispatch.request.query_parameters'
591
        env.delete 'action_dispatch.request.request_parameters'
592 593 594
        env
      end

595
      def process_with_kwargs(http_method, action, *args)
596
        if kwarg_request?(args)
597 598 599
          args.first.merge!(method: http_method)
          process(action, *args)
        else
600
          non_kwarg_request_warning if args.any?
601 602 603 604 605 606

          args = args.unshift(http_method)
          process(action, *args)
        end
      end

607
      REQUEST_KWARGS = %i(params session flash method body xhr)
608
      def kwarg_request?(args)
609 610 611 612 613 614 615 616 617 618 619 620 621 622
        args[0].respond_to?(:keys) && (
          (args[0].key?(:format) && args[0].keys.size == 1) ||
          args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
        )
      end

      def non_kwarg_request_warning
        ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
          ActionController::TestCase HTTP request methods will accept only
          keyword arguments in future Rails versions.

          Examples:

          get :show, params: { id: 1 }, session: { user_id: 1 }
623
          process :update, method: :post, params: { id: 1 }
624 625 626
        MSG
      end

627 628 629 630
      def document_root_element
        html_document.root
      end

631 632 633
      def check_required_ivars
        # Sanity check for required instance variables so we can give an
        # understandable error message.
634 635
        [:@routes, :@controller, :@request, :@response].each do |iv_name|
          if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
636 637 638 639
            raise "#{iv_name} is nil: make sure you set it in your test's setup method."
          end
        end
      end
A
Aaron Patterson 已提交
640

641
      def html_format?(parameters)
642
        return true unless parameters.key?(:format)
643
        Mime.fetch(parameters[:format]) { Mime['html'] }.html?
644
      end
645
    end
646 647 648

    include Behavior
  end
P
Pratik Naik 已提交
649
end