Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/actionpack/lib/action_controller/integration.rb

Revision 9188, 21.9 kB (checked in by bitsweat, 6 months ago)

Ruby 1.9 compat: don't confuse with headers method call

Line 
1 require 'stringio'
2 require 'uri'
3
4 require 'action_controller/dispatcher'
5 require 'action_controller/test_process'
6
7 module ActionController
8   module Integration #:nodoc:
9     # An integration Session instance represents a set of requests and responses
10     # performed sequentially by some virtual user. Becase you can instantiate
11     # multiple sessions and run them side-by-side, you can also mimic (to some
12     # limited extent) multiple simultaneous users interacting with your system.
13     #
14     # Typically, you will instantiate a new session using IntegrationTest#open_session,
15     # rather than instantiating Integration::Session directly.
16     class Session
17       include Test::Unit::Assertions
18       include ActionController::Assertions
19       include ActionController::TestProcess
20
21       # The integer HTTP status code of the last request.
22       attr_reader :status
23
24       # The status message that accompanied the status code of the last request.
25       attr_reader :status_message
26
27       # The URI of the last request.
28       attr_reader :path
29
30       # The hostname used in the last request.
31       attr_accessor :host
32
33       # The remote_addr used in the last request.
34       attr_accessor :remote_addr
35
36       # The Accept header to send.
37       attr_accessor :accept
38
39       # A map of the cookies returned by the last response, and which will be
40       # sent with the next request.
41       attr_reader :cookies
42
43       # A map of the headers returned by the last response.
44       attr_reader :headers
45
46       # A reference to the controller instance used by the last request.
47       attr_reader :controller
48
49       # A reference to the request instance used by the last request.
50       attr_reader :request
51
52       # A reference to the response instance used by the last request.
53       attr_reader :response
54
55       # A running counter of the number of requests processed.
56       attr_accessor :request_count
57
58       class MultiPartNeededException < Exception
59       end
60
61       # Create and initialize a new +Session+ instance.
62       def initialize
63         reset!
64       end
65
66       # Resets the instance. This can be used to reset the state information
67       # in an existing session instance, so it can be used from a clean-slate
68       # condition.
69       #
70       #   session.reset!
71       def reset!
72         @status = @path = @headers = nil
73         @result = @status_message = nil
74         @https = false
75         @cookies = {}
76         @controller = @request = @response = nil
77         @request_count = 0
78
79         self.host        = "www.example.com"
80         self.remote_addr = "127.0.0.1"
81         self.accept      = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
82
83         unless defined? @named_routes_configured
84           # install the named routes in this session instance.
85           klass = class<<self; self; end
86           Routing::Routes.install_helpers(klass)
87
88           # the helpers are made protected by default--we make them public for
89           # easier access during testing and troubleshooting.
90           klass.module_eval { public *Routing::Routes.named_routes.helpers }
91           @named_routes_configured = true
92         end
93       end
94
95       # Specify whether or not the session should mimic a secure HTTPS request.
96       #
97       #   session.https!
98       #   session.https!(false)
99       def https!(flag=true)
100         @https = flag
101       end
102
103       # Return +true+ if the session is mimicing a secure HTTPS request.
104       #
105       #   if session.https?
106       #     ...
107       #   end
108       def https?
109         @https
110       end
111
112       # Set the host name to use in the next request.
113       #
114       #   session.host! "www.example.com"
115       def host!(name)
116         @host = name
117       end
118
119       # Follow a single redirect response. If the last response was not a
120       # redirect, an exception will be raised. Otherwise, the redirect is
121       # performed on the location header.
122       def follow_redirect!
123         raise "not a redirect! #{@status} #{@status_message}" unless redirect?
124         get(interpret_uri(headers['location'].first))
125         status
126       end
127
128       # Performs a request using the specified method, following any subsequent
129       # redirect. Note that the redirects are followed until the response is
130       # not a redirect--this means you may run into an infinite loop if your
131       # redirect loops back to itself.
132       def request_via_redirect(http_method, path, parameters = nil, headers = nil)
133         send(http_method, path, parameters, headers)
134         follow_redirect! while redirect?
135         status
136       end
137
138       # Performs a GET request, following any subsequent redirect.
139       # See #request_via_redirect() for more information.
140       def get_via_redirect(path, parameters = nil, headers = nil)
141         request_via_redirect(:get, path, parameters, headers)
142       end
143
144       # Performs a POST request, following any subsequent redirect.
145       # See #request_via_redirect() for more information.
146       def post_via_redirect(path, parameters = nil, headers = nil)
147         request_via_redirect(:post, path, parameters, headers)
148       end
149
150       # Performs a PUT request, following any subsequent redirect.
151       # See #request_via_redirect() for more information.
152       def put_via_redirect(path, parameters = nil, headers = nil)
153         request_via_redirect(:put, path, parameters, headers)
154       end
155
156       # Performs a DELETE request, following any subsequent redirect.
157       # See #request_via_redirect() for more information.
158       def delete_via_redirect(path, parameters = nil, headers = nil)
159         request_via_redirect(:delete, path, parameters, headers)
160       end
161
162       # Returns +true+ if the last response was a redirect.
163       def redirect?
164         status/100 == 3
165       end
166
167       # Performs a GET request with the given parameters. The parameters may
168       # be +nil+, a Hash, or a string that is appropriately encoded
169       # (application/x-www-form-urlencoded or multipart/form-data).  The headers
170       # should be a hash.  The keys will automatically be upcased, with the
171       # prefix 'HTTP_' added if needed.
172       #
173       # You can also perform POST, PUT, DELETE, and HEAD requests with #post,
174       # #put, #delete, and #head.
175       def get(path, parameters = nil, headers = nil)
176         process :get, path, parameters, headers
177       end
178
179       # Performs a POST request with the given parameters. See get() for more details.
180       def post(path, parameters = nil, headers = nil)
181         process :post, path, parameters, headers
182       end
183
184       # Performs a PUT request with the given parameters. See get() for more details.
185       def put(path, parameters = nil, headers = nil)
186         process :put, path, parameters, headers
187       end
188
189       # Performs a DELETE request with the given parameters. See get() for more details.
190       def delete(path, parameters = nil, headers = nil)
191         process :delete, path, parameters, headers
192       end
193
194       # Performs a HEAD request with the given parameters. See get() for more details.
195       def head(path, parameters = nil, headers = nil)
196         process :head, path, parameters, headers
197       end
198
199       # Performs an XMLHttpRequest request with the given parameters, mirroring
200       # a request from the Prototype library.
201       #
202       # The request_method is :get, :post, :put, :delete or :head; the
203       # parameters are +nil+, a hash, or a url-encoded or multipart string;
204       # the headers are a hash.  Keys are automatically upcased and prefixed
205       # with 'HTTP_' if not already.
206       def xml_http_request(request_method, path, parameters = nil, headers = nil)
207         headers ||= {}
208         headers['X-Requested-With'] = 'XMLHttpRequest'
209         headers['Accept'] ||= 'text/javascript, text/html, application/xml, text/xml, */*'
210
211         process(request_method, path, parameters, headers)
212       end
213       alias xhr :xml_http_request
214
215       # Returns the URL for the given options, according to the rules specified
216       # in the application's routes.
217       def url_for(options)
218         controller ? controller.url_for(options) : generic_url_rewriter.rewrite(options)
219       end
220
221       private
222         class StubCGI < CGI #:nodoc:
223           attr_accessor :stdinput, :stdoutput, :env_table
224
225           def initialize(env, stdinput = nil)
226             self.env_table = env
227             self.stdoutput = StringIO.new
228
229             super
230
231             @stdinput = stdinput.is_a?(IO) ? stdinput : StringIO.new(stdinput || '')
232           end
233         end
234
235         # Tailors the session based on the given URI, setting the HTTPS value
236         # and the hostname.
237         def interpret_uri(path)
238           location = URI.parse(path)
239           https! URI::HTTPS === location if location.scheme
240           host! location.host if location.host
241           location.query ? "#{location.path}?#{location.query}" : location.path
242         end
243
244         # Performs the actual request.
245         def process(method, path, parameters = nil, headers = nil)
246           data = requestify(parameters)
247           path = interpret_uri(path) if path =~ %r{://}
248           path = "/#{path}" unless path[0] == ?/
249           @path = path
250           env = {}
251
252           if method == :get
253             env["QUERY_STRING"] = data
254             data = nil
255           end
256
257           env.update(
258             "REQUEST_METHOD" => method.to_s.upcase,
259             "REQUEST_URI"    => path,
260             "HTTP_HOST"      => host,
261             "REMOTE_ADDR"    => remote_addr,
262             "SERVER_PORT"    => (https? ? "443" : "80"),
263             "CONTENT_TYPE"   => "application/x-www-form-urlencoded",
264             "CONTENT_LENGTH" => data ? data.length.to_s : nil,
265             "HTTP_COOKIE"    => encode_cookies,
266             "HTTPS"          => https? ? "on" : "off",
267             "HTTP_ACCEPT"    => accept
268           )
269
270           (headers || {}).each do |key, value|
271             key = key.to_s.upcase.gsub(/-/, "_")
272             key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
273             env[key] = value
274           end
275
276           unless ActionController::Base.respond_to?(:clear_last_instantiation!)
277             ActionController::Base.module_eval { include ControllerCapture }
278           end
279
280           ActionController::Base.clear_last_instantiation!
281
282           cgi = StubCGI.new(env, data)
283           ActionController::Dispatcher.dispatch(cgi, ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, cgi.stdoutput)
284           @result = cgi.stdoutput.string
285           @request_count += 1
286
287           @controller = ActionController::Base.last_instantiation
288           @request = @controller.request
289           @response = @controller.response
290
291           # Decorate the response with the standard behavior of the TestResponse
292           # so that things like assert_response can be used in integration
293           # tests.
294           @response.extend(TestResponseBehavior)
295
296           @html_document = nil
297
298           parse_result
299           return status
300         rescue MultiPartNeededException
301           boundary = "----------XnJLe9ZIbbGUYtzPQJ16u1"
302           status = process(method, path, multipart_body(parameters, boundary), (headers || {}).merge({"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"}))
303           return status
304         end
305
306         # Parses the result of the response and extracts the various values,
307         # like cookies, status, headers, etc.
308         def parse_result
309           response_headers, result_body = @result.split(/\r\n\r\n/, 2)
310
311           @headers = Hash.new { |h,k| h[k] = [] }
312           response_headers.to_s.each_line do |line|
313             key, value = line.strip.split(/:\s*/, 2)
314             @headers[key.downcase] << value
315           end
316
317           (@headers['set-cookie'] || [] ).each do |string|
318             name, value = string.match(/^([^=]*)=([^;]*);/)[1,2]
319             @cookies[name] = value
320           end
321
322           @status, @status_message = @headers["status"].first.to_s.split(/ /)
323           @status = @status.to_i
324         end
325
326         # Encode the cookies hash in a format suitable for passing to a
327         # request.
328         def encode_cookies
329           cookies.inject("") do |string, (name, value)|
330             string << "#{name}=#{value}; "
331           end
332         end
333
334         # Get a temporary URL writer object
335         def generic_url_rewriter
336           cgi = StubCGI.new('REQUEST_METHOD' => "GET",
337                             'QUERY_STRING'   => "",
338                             "REQUEST_URI"    => "/",
339                             "HTTP_HOST"      => host,
340                             "SERVER_PORT"    => https? ? "443" : "80",
341                             "HTTPS"          => https? ? "on" : "off")
342           ActionController::UrlRewriter.new(ActionController::CgiRequest.new(cgi), {})
343         end
344
345         def name_with_prefix(prefix, name)
346           prefix ? "#{prefix}[#{name}]" : name.to_s
347         end
348
349         # Convert the given parameters to a request string. The parameters may
350         # be a string, +nil+, or a Hash.
351         def requestify(parameters, prefix=nil)
352           if TestUploadedFile === parameters
353             raise MultiPartNeededException
354           elsif Hash === parameters
355             return nil if parameters.empty?
356             parameters.map { |k,v| requestify(v, name_with_prefix(prefix, k)) }.join("&")
357           elsif Array === parameters
358             parameters.map { |v| requestify(v, name_with_prefix(prefix, "")) }.join("&")
359           elsif prefix.nil?
360             parameters
361           else
362             "#{CGI.escape(prefix)}=#{CGI.escape(parameters.to_s)}"
363           end
364         end
365
366         def multipart_requestify(params, first=true)
367           returning Hash.new do |p|
368             params.each do |key, value|
369               k = first ? CGI.escape(key.to_s) : "[#{CGI.escape(key.to_s)}]"
370               if Hash === value
371                 multipart_requestify(value, false).each do |subkey, subvalue|
372                   p[k + subkey] = subvalue
373                 end
374               else
375                 p[k] = value
376               end
377             end
378           end
379         end
380
381         def multipart_body(params, boundary)
382           multipart_requestify(params).map do |key, value|
383             if value.respond_to?(:original_filename)
384               File.open(value.path) do |f|
385                 <<-EOF
386 --#{boundary}\r
387 Content-Disposition: form-data; name="#{key}"; filename="#{CGI.escape(value.original_filename)}"\r
388 Content-Type: #{value.content_type}\r
389 Content-Length: #{File.stat(value.path).size}\r
390 \r
391 #{f.read}\r
392 EOF
393               end
394             else
395 <<-EOF
396 --#{boundary}\r
397 Content-Disposition: form-data; name="#{key}"\r
398 \r
399 #{value}\r
400 EOF
401             end
402           end.join("")+"--#{boundary}--\r"
403         end
404     end
405
406     # A module used to extend ActionController::Base, so that integration tests
407     # can capture the controller used to satisfy a request.
408     module ControllerCapture #:nodoc:
409       def self.included(base)
410         base.extend(ClassMethods)
411         base.class_eval do
412           class << self
413             alias_method_chain :new, :capture
414           end
415         end
416       end
417
418       module ClassMethods #:nodoc:
419         mattr_accessor :last_instantiation
420
421         def clear_last_instantiation!
422           self.last_instantiation = nil
423         end
424
425         def new_with_capture(*args)
426           controller = new_without_capture(*args)
427           self.last_instantiation ||= controller
428           controller
429         end
430       end
431     end
432
433     module Runner
434       # Reset the current session. This is useful for testing multiple sessions
435       # in a single test case.
436       def reset!
437         @integration_session = open_session
438       end
439
440       %w(get post put head delete cookies assigns
441          xml_http_request get_via_redirect post_via_redirect).each do |method|
442         define_method(method) do |*args|
443           reset! unless @integration_session
444           # reset the html_document variable, but only for new get/post calls
445           @html_document = nil unless %w(cookies assigns).include?(method)
446           returning @integration_session.send!(method, *args) do
447             copy_session_variables!
448           end
449         end
450       end
451
452       # Open a new session instance. If a block is given, the new session is
453       # yielded to the block before being returned.
454       #
455       #   session = open_session do |sess|
456       #     sess.extend(CustomAssertions)
457       #   end
458       #
459       # By default, a single session is automatically created for you, but you
460       # can use this method to open multiple sessions that ought to be tested
461       # simultaneously.
462       def open_session
463         session = Integration::Session.new
464
465         # delegate the fixture accessors back to the test instance
466         extras = Module.new { attr_accessor :delegate, :test_result }
467         if self.class.respond_to?(:fixture_table_names)
468           self.class.fixture_table_names.each do |table_name|
469             name = table_name.tr(".", "_")
470             next unless respond_to?(name)
471             extras.send!(:define_method, name) { |*args| delegate.send(name, *args) }
472           end
473         end
474
475         # delegate add_assertion to the test case
476         extras.send!(:define_method, :add_assertion) { test_result.add_assertion }
477         session.extend(extras)
478         session.delegate = self
479         session.test_result = @_result
480
481         yield session if block_given?
482         session
483       end
484
485       # Copy the instance variables from the current session instance into the
486       # test instance.
487       def copy_session_variables! #:nodoc:
488         return unless @integration_session
489         %w(controller response request).each do |var|
490           instance_variable_set("@#{var}", @integration_session.send!(var))
491         end
492       end
493
494       # Delegate unhandled messages to the current session instance.
495       def method_missing(sym, *args, &block)
496         reset! unless @integration_session
497         returning @integration_session.send!(sym, *args, &block) do
498           copy_session_variables!
499         end
500       end
501     end
502   end
503
504   # An IntegrationTest is one that spans multiple controllers and actions,
505   # tying them all together to ensure they work together as expected. It tests
506   # more completely than either unit or functional tests do, exercising the
507   # entire stack, from the dispatcher to the database.
508   #
509   # At its simplest, you simply extend IntegrationTest and write your tests
510   # using the get/post methods:
511   #
512   #   require "#{File.dirname(__FILE__)}/test_helper"
513   #
514   #   class ExampleTest < ActionController::IntegrationTest
515   #     fixtures :people
516   #
517   #     def test_login
518   #       # get the login page
519   #       get "/login"
520   #       assert_equal 200, status
521   #
522   #       # post the login and follow through to the home page
523   #       post "/login", :username => people(:jamis).username,
524   #         :password => people(:jamis).password
525   #       follow_redirect!
526   #       assert_equal 200, status
527   #       assert_equal "/home", path
528   #     end
529   #   end
530   #
531   # However, you can also have multiple session instances open per test, and
532   # even extend those instances with assertions and methods to create a very
533   # powerful testing DSL that is specific for your application. You can even
534   # reference any named routes you happen to have defined!
535   #
536   #   require "#{File.dirname(__FILE__)}/test_helper"
537   #
538   #   class AdvancedTest < ActionController::IntegrationTest
539   #     fixtures :people, :rooms
540   #
541   #     def test_login_and_speak
542   #       jamis, david = login(:jamis), login(:david)
543   #       room = rooms(:office)
544   #
545   #       jamis.enter(room)
546   #       jamis.speak(room, "anybody home?")
547   #
548   #       david.enter(room)
549   #       david.speak(room, "hello!")
550   #     end
551   #
552   #     private
553   #
554   #       module CustomAssertions
555   #         def enter(room)
556   #           # reference a named route, for maximum internal consistency!
557   #           get(room_url(:id => room.id))
558   #           assert(...)
559   #           ...
560   #         end
561   #
562   #         def speak(room, message)
563   #           xml_http_request "/say/#{room.id}", :message => message
564   #           assert(...)
565   #           ...
566   #         end
567   #       end
568   #