integration.rb 16.8 KB
Newer Older
1 2
require 'stringio'
require 'uri'
3
require 'active_support/core_ext/object/metaclass'
J
Joshua Peek 已提交
4
require 'rack/test'
5 6

module ActionDispatch
D
David Heinemeier Hansson 已提交
7
  module Integration #:nodoc:
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
    module RequestHelpers
      # Performs a GET request with the given parameters.
      #
      # - +path+: The URI (as a String) on which you want to perform a GET
      #   request.
      # - +parameters+: The HTTP parameters that you want to pass. This may
      #   be +nil+,
      #   a Hash, or a String that is appropriately encoded
      #   (<tt>application/x-www-form-urlencoded</tt> or
      #   <tt>multipart/form-data</tt>).
      # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
      #   automatically be upcased, with the prefix 'HTTP_' added if needed.
      #
      # This method returns an Response object, which one can use to
      # inspect the details of the response. Furthermore, if this method was
23
      # called from an ActionDispatch::IntegrationTest object, then that
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
      # object's <tt>@response</tt> instance variable will point to the same
      # response object.
      #
      # You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
      # +put+, +delete+, and +head+.
      def get(path, parameters = nil, headers = nil)
        process :get, path, parameters, headers
      end

      # Performs a POST request with the given parameters. See get() for more
      # details.
      def post(path, parameters = nil, headers = nil)
        process :post, path, parameters, headers
      end

      # Performs a PUT request with the given parameters. See get() for more
      # details.
      def put(path, parameters = nil, headers = nil)
        process :put, path, parameters, headers
      end

      # Performs a DELETE request with the given parameters. See get() for
      # more details.
      def delete(path, parameters = nil, headers = nil)
        process :delete, path, parameters, headers
      end

      # Performs a HEAD request with the given parameters. See get() for more
      # details.
      def head(path, parameters = nil, headers = nil)
        process :head, path, parameters, headers
      end

      # Performs an XMLHttpRequest request with the given parameters, mirroring
      # a request from the Prototype library.
      #
      # The request_method is :get, :post, :put, :delete or :head; the
      # parameters are +nil+, a hash, or a url-encoded or multipart string;
      # the headers are a hash.  Keys are automatically upcased and prefixed
      # with 'HTTP_' if not already.
      def xml_http_request(request_method, path, parameters = nil, headers = nil)
        headers ||= {}
66 67
        headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
        headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
68 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        process(request_method, path, parameters, headers)
      end
      alias xhr :xml_http_request

      # Follow a single redirect response. If the last response was not a
      # redirect, an exception will be raised. Otherwise, the redirect is
      # performed on the location header.
      def follow_redirect!
        raise "not a redirect! #{status} #{status_message}" unless redirect?
        get(response.location)
        status
      end

      # Performs a request using the specified method, following any subsequent
      # redirect. Note that the redirects are followed until the response is
      # not a redirect--this means you may run into an infinite loop if your
      # redirect loops back to itself.
      def request_via_redirect(http_method, path, parameters = nil, headers = nil)
        process(http_method, path, parameters, headers)
        follow_redirect! while redirect?
        status
      end

      # Performs a GET request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def get_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:get, path, parameters, headers)
      end

      # Performs a POST request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def post_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:post, path, parameters, headers)
      end

      # Performs a PUT request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def put_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:put, path, parameters, headers)
      end

      # Performs a DELETE request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def delete_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:delete, path, parameters, headers)
      end
    end

116
    # An integration Session instance represents a set of requests and responses
P
Pratik Naik 已提交
117
    # performed sequentially by some virtual user. Because you can instantiate
118 119 120
    # multiple sessions and run them side-by-side, you can also mimic (to some
    # limited extent) multiple simultaneous users interacting with your system.
    #
121 122 123
    # Typically, you will instantiate a new session using
    # IntegrationTest#open_session, rather than instantiating
    # Integration::Session directly.
124
    class Session
125 126
      DEFAULT_HOST = "www.example.com"

127
      include Test::Unit::Assertions
J
Joshua Peek 已提交
128
      include TestProcess, RequestHelpers, Assertions
129

130 131 132
      %w( status status_message headers body redirect? ).each do |method|
        delegate method, :to => :response, :allow_nil => true
      end
133

134 135 136
      %w( path ).each do |method|
        delegate method, :to => :request, :allow_nil => true
      end
137 138

      # The hostname used in the last request.
139 140 141 142
      attr_accessor :host

      # The remote_addr used in the last request.
      attr_accessor :remote_addr
143

144 145 146
      # The Accept header to send.
      attr_accessor :accept

147 148
      # A map of the cookies returned by the last response, and which will be
      # sent with the next request.
149 150 151
      def cookies
        @mock_session.cookie_jar
      end
152 153 154 155 156 157 158 159 160 161

      # A reference to the controller instance used by the last request.
      attr_reader :controller

      # A reference to the request instance used by the last request.
      attr_reader :request

      # A reference to the response instance used by the last request.
      attr_reader :response

162 163 164
      # A running counter of the number of requests processed.
      attr_accessor :request_count

P
Pratik Naik 已提交
165
      # Create and initialize a new Session instance.
166 167
      def initialize(app)
        @app = app
168 169 170 171 172 173 174 175 176 177
        reset!
      end

      # Resets the instance. This can be used to reset the state information
      # in an existing session instance, so it can be used from a clean-slate
      # condition.
      #
      #   session.reset!
      def reset!
        @https = false
178
        @mock_session = Rack::MockSession.new(@app, DEFAULT_HOST)
179
        @controller = @request = @response = nil
180
        @request_count = 0
181

182
        self.host        = DEFAULT_HOST
183
        self.remote_addr = "127.0.0.1"
184 185 186
        self.accept      = "text/xml,application/xml,application/xhtml+xml," +
                           "text/html;q=0.9,text/plain;q=0.8,image/png," +
                           "*/*;q=0.5"
J
Jamis Buck 已提交
187

188
        unless defined? @named_routes_configured
J
Jamis Buck 已提交
189
          # install the named routes in this session instance.
190
          klass = metaclass
191
          ActionController::Routing::Routes.install_helpers(klass)
J
Jamis Buck 已提交
192 193 194

          # the helpers are made protected by default--we make them public for
          # easier access during testing and troubleshooting.
195
          klass.module_eval { public *ActionController::Routing::Routes.named_routes.helpers }
J
Jamis Buck 已提交
196 197
          @named_routes_configured = true
        end
198 199 200 201 202 203
      end

      # Specify whether or not the session should mimic a secure HTTPS request.
      #
      #   session.https!
      #   session.https!(false)
204
      def https!(flag = true)
205
        @https = flag
206 207
      end

P
Pratik Naik 已提交
208
      # Return +true+ if the session is mimicking a secure HTTPS request.
209 210 211 212 213 214 215 216 217 218
      #
      #   if session.https?
      #     ...
      #   end
      def https?
        @https
      end

      # Set the host name to use in the next request.
      #
219
      #   session.host! "www.example.com"
220 221 222 223 224 225 226
      def host!(name)
        @host = name
      end

      # Returns the URL for the given options, according to the rules specified
      # in the application's routes.
      def url_for(options)
227 228 229
        controller ?
          controller.url_for(options) :
          generic_url_rewriter.rewrite(options)
230 231 232
      end

      private
233

234
        # Performs the actual request.
235
        def process(method, path, parameters = nil, rack_environment = nil)
236 237 238 239 240 241
          if path =~ %r{://}
            location = URI.parse(path)
            https! URI::HTTPS === location if location.scheme
            host! location.host if location.host
            path = location.query ? "#{location.path}?#{location.query}" : location.path
          end
242

243
          [ControllerCapture, ActionController::Testing].each do |mod|
244 245 246
            unless ActionController::Base < mod
              ActionController::Base.class_eval { include mod }
            end
247 248
          end

249
          env = {
250
            :method => method,
251
            :params => parameters,
252 253 254 255 256 257

            "SERVER_NAME"     => host,
            "SERVER_PORT"     => (https? ? "443" : "80"),
            "HTTPS"           => https? ? "on" : "off",
            "rack.url_scheme" => https? ? "https" : "http",

258 259
            "REQUEST_URI"    => path,
            "HTTP_HOST"      => host,
260
            "REMOTE_ADDR"    => remote_addr,
261
            "CONTENT_TYPE"   => "application/x-www-form-urlencoded",
262 263 264
            "HTTP_ACCEPT"    => accept,

            "action_dispatch.show_exceptions" => false
265
          }
266

267
          (rack_environment || {}).each do |key, value|
268 269 270
            env[key] = value
          end

271 272
          session = Rack::Test::Session.new(@mock_session)

273
          @controller = ActionController::Base.capture_instantiation do
274
            session.request(path, env)
275
          end
276

277
          @request_count += 1
278
          @request  = ActionDispatch::Request.new(session.last_request.env)
279
          @response = ActionDispatch::TestResponse.from_response(@mock_session.last_response)
280
          @html_document = nil
281

282
          return response.status
283 284
        end

285
        # Get a temporary URL writer object
286
        def generic_url_rewriter
287 288 289 290 291 292 293 294
          env = {
            'REQUEST_METHOD' => "GET",
            'QUERY_STRING'   => "",
            "REQUEST_URI"    => "/",
            "HTTP_HOST"      => host,
            "SERVER_PORT"    => https? ? "443" : "80",
            "HTTPS"          => https? ? "on" : "off"
          }
295
          ActionController::UrlRewriter.new(ActionDispatch::Request.new(env), {})
296 297 298 299 300 301
        end
    end

    # A module used to extend ActionController::Base, so that integration tests
    # can capture the controller used to satisfy a request.
    module ControllerCapture #:nodoc:
302
      extend ActiveSupport::Concern
303 304 305

      included do
        alias_method_chain :initialize, :capture
306 307
      end

308 309 310 311 312
      def initialize_with_capture(*args)
        initialize_without_capture
        self.class.last_instantiation ||= self
      end

D
David Heinemeier Hansson 已提交
313
      module ClassMethods #:nodoc:
314 315
        mattr_accessor :last_instantiation

316
        def capture_instantiation
317
          self.last_instantiation = nil
318 319
          yield
          return last_instantiation
320 321 322
        end
      end
    end
323 324

    module Runner
325 326 327 328
      def app
        @app
      end

329 330 331 332 333 334 335
      # Reset the current session. This is useful for testing multiple sessions
      # in a single test case.
      def reset!
        @integration_session = open_session
      end

      %w(get post put head delete cookies assigns
336
         xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
337 338 339 340
        define_method(method) do |*args|
          reset! unless @integration_session
          # reset the html_document variable, but only for new get/post calls
          @html_document = nil unless %w(cookies assigns).include?(method)
341
          returning @integration_session.__send__(method, *args) do
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            copy_session_variables!
          end
        end
      end

      # Open a new session instance. If a block is given, the new session is
      # yielded to the block before being returned.
      #
      #   session = open_session do |sess|
      #     sess.extend(CustomAssertions)
      #   end
      #
      # By default, a single session is automatically created for you, but you
      # can use this method to open multiple sessions that ought to be tested
      # simultaneously.
357
      def open_session(app = nil)
358
        session = Integration::Session.new(app || self.app)
359 360 361 362 363 364 365

        # delegate the fixture accessors back to the test instance
        extras = Module.new { attr_accessor :delegate, :test_result }
        if self.class.respond_to?(:fixture_table_names)
          self.class.fixture_table_names.each do |table_name|
            name = table_name.tr(".", "_")
            next unless respond_to?(name)
366 367 368
            extras.__send__(:define_method, name) { |*args|
              delegate.send(name, *args)
            }
369 370 371 372
          end
        end

        # delegate add_assertion to the test case
373 374 375
        extras.__send__(:define_method, :add_assertion) {
          test_result.add_assertion
        }
376 377 378 379 380 381 382 383 384 385 386 387 388
        session.extend(extras)
        session.delegate = self
        session.test_result = @_result

        yield session if block_given?
        session
      end

      # Copy the instance variables from the current session instance into the
      # test instance.
      def copy_session_variables! #:nodoc:
        return unless @integration_session
        %w(controller response request).each do |var|
389
          instance_variable_set("@#{var}", @integration_session.__send__(var))
390 391 392 393 394 395
        end
      end

      # Delegate unhandled messages to the current session instance.
      def method_missing(sym, *args, &block)
        reset! unless @integration_session
396 397 398 399 400 401
        if @integration_session.respond_to?(sym)
          returning @integration_session.__send__(sym, *args, &block) do
            copy_session_variables!
          end
        else
          super
402 403 404
        end
      end
    end
405 406 407 408 409 410 411 412 413 414
  end

  # An IntegrationTest is one that spans multiple controllers and actions,
  # tying them all together to ensure they work together as expected. It tests
  # more completely than either unit or functional tests do, exercising the
  # entire stack, from the dispatcher to the database.
  #
  # At its simplest, you simply extend IntegrationTest and write your tests
  # using the get/post methods:
  #
415
  #   require "test_helper"
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  #
  #   class ExampleTest < ActionController::IntegrationTest
  #     fixtures :people
  #
  #     def test_login
  #       # get the login page
  #       get "/login"
  #       assert_equal 200, status
  #
  #       # post the login and follow through to the home page
  #       post "/login", :username => people(:jamis).username,
  #         :password => people(:jamis).password
  #       follow_redirect!
  #       assert_equal 200, status
  #       assert_equal "/home", path
  #     end
  #   end
  #
  # However, you can also have multiple session instances open per test, and
  # even extend those instances with assertions and methods to create a very
  # powerful testing DSL that is specific for your application. You can even
  # reference any named routes you happen to have defined!
  #
439
  #   require "test_helper"
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  #
  #   class AdvancedTest < ActionController::IntegrationTest
  #     fixtures :people, :rooms
  #
  #     def test_login_and_speak
  #       jamis, david = login(:jamis), login(:david)
  #       room = rooms(:office)
  #
  #       jamis.enter(room)
  #       jamis.speak(room, "anybody home?")
  #
  #       david.enter(room)
  #       david.speak(room, "hello!")
  #     end
  #
  #     private
  #
  #       module CustomAssertions
  #         def enter(room)
  #           # reference a named route, for maximum internal consistency!
  #           get(room_url(:id => room.id))
  #           assert(...)
  #           ...
  #         end
  #
  #         def speak(room, message)
  #           xml_http_request "/say/#{room.id}", :message => message
  #           assert(...)
  #           ...
  #         end
  #       end
  #
  #       def login(who)
  #         open_session do |sess|
  #           sess.extend(CustomAssertions)
  #           who = people(who)
  #           sess.post "/login", :username => who.username,
  #             :password => who.password
  #           assert(...)
  #         end
  #       end
  #   end
482
  class IntegrationTest < ActiveSupport::TestCase
483
    include Integration::Runner
484 485 486 487

    @@app = nil

    def self.app
488 489
      # DEPRECATE Rails application fallback
      # This should be set by the initializer
490
      @@app || (defined?(Rails.application) && Rails.application) || nil
491 492 493 494 495 496 497 498 499
    end

    def self.app=(app)
      @@app = app
    end

    def app
      super || self.class.app
    end
500
  end
501
end