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