aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack
diff options
context:
space:
mode:
Diffstat (limited to 'actionpack')
-rw-r--r--actionpack/CHANGELOG.md250
-rw-r--r--actionpack/README.rdoc2
-rw-r--r--actionpack/Rakefile14
-rw-r--r--actionpack/actionpack.gemspec4
-rwxr-xr-xactionpack/bin/test4
-rw-r--r--actionpack/lib/abstract_controller.rb2
-rw-r--r--actionpack/lib/abstract_controller/base.rb14
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb18
-rw-r--r--actionpack/lib/abstract_controller/collector.rb13
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb2
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb26
-rw-r--r--actionpack/lib/action_controller.rb5
-rw-r--r--actionpack/lib/action_controller/api.rb146
-rw-r--r--actionpack/lib/action_controller/base.rb17
-rw-r--r--actionpack/lib/action_controller/caching.rb4
-rw-r--r--actionpack/lib/action_controller/form_builder.rb48
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb2
-rw-r--r--actionpack/lib/action_controller/metal.rb145
-rw-r--r--actionpack/lib/action_controller/metal/basic_implicit_render.rb11
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb7
-rw-r--r--actionpack/lib/action_controller/metal/cookies.rb2
-rw-r--r--actionpack/lib/action_controller/metal/data_streaming.rb24
-rw-r--r--actionpack/lib/action_controller/metal/etag_with_template_digest.rb2
-rw-r--r--actionpack/lib/action_controller/metal/exceptions.rb17
-rw-r--r--actionpack/lib/action_controller/metal/force_ssl.rb12
-rw-r--r--actionpack/lib/action_controller/metal/head.rb21
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb10
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb62
-rw-r--r--actionpack/lib/action_controller/metal/implicit_render.rb29
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb1
-rw-r--r--actionpack/lib/action_controller/metal/live.rb61
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb19
-rw-r--r--actionpack/lib/action_controller/metal/params_wrapper.rb17
-rw-r--r--actionpack/lib/action_controller/metal/rack_delegation.rb38
-rw-r--r--actionpack/lib/action_controller/metal/redirecting.rb1
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb16
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb39
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb53
-rw-r--r--actionpack/lib/action_controller/metal/rescue.rb6
-rw-r--r--actionpack/lib/action_controller/metal/streaming.rb8
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb287
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb11
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb12
-rw-r--r--actionpack/lib/action_controller/middleware.rb39
-rw-r--r--actionpack/lib/action_controller/renderer.rb93
-rw-r--r--actionpack/lib/action_controller/template_assertions.rb9
-rw-r--r--actionpack/lib/action_controller/test_case.rb500
-rw-r--r--actionpack/lib/action_dispatch.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb49
-rw-r--r--actionpack/lib/action_dispatch/http/filter_parameters.rb14
-rw-r--r--actionpack/lib/action_dispatch/http/filter_redirect.rb13
-rw-r--r--actionpack/lib/action_dispatch/http/headers.rb39
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb39
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb145
-rw-r--r--actionpack/lib/action_dispatch/http/mime_types.rb5
-rw-r--r--actionpack/lib/action_dispatch/http/parameter_filter.rb26
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb78
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb200
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb260
-rw-r--r--actionpack/lib/action_dispatch/http/upload.rb8
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb13
-rw-r--r--actionpack/lib/action_dispatch/journey/formatter.rb49
-rw-r--r--actionpack/lib/action_dispatch/journey/nfa/dot.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/nodes/node.rb18
-rw-r--r--actionpack/lib/action_dispatch/journey/parser_extras.rb4
-rw-r--r--actionpack/lib/action_dispatch/journey/path/pattern.rb71
-rw-r--r--actionpack/lib/action_dispatch/journey/route.rb82
-rw-r--r--actionpack/lib/action_dispatch/journey/router.rb6
-rw-r--r--actionpack/lib/action_dispatch/journey/router/strexp.rb27
-rw-r--r--actionpack/lib/action_dispatch/journey/router/utils.rb8
-rw-r--r--actionpack/lib/action_dispatch/journey/routes.rb16
-rw-r--r--actionpack/lib/action_dispatch/journey/visitors.rb129
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb309
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb23
-rw-r--r--actionpack/lib/action_dispatch/middleware/exception_wrapper.rb30
-rw-r--r--actionpack/lib/action_dispatch/middleware/flash.rb66
-rw-r--r--actionpack/lib/action_dispatch/middleware/load_interlock.rb21
-rw-r--r--actionpack/lib/action_dispatch/middleware/params_parser.rb76
-rw-r--r--actionpack/lib/action_dispatch/middleware/public_exceptions.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/reloader.rb6
-rw-r--r--actionpack/lib/action_dispatch/middleware/remote_ip.rb48
-rw-r--r--actionpack/lib/action_dispatch/middleware/request_id.rb13
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb34
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cache_store.rb6
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb42
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb20
-rw-r--r--actionpack/lib/action_dispatch/middleware/ssl.rb129
-rw-r--r--actionpack/lib/action_dispatch/middleware/stack.rb91
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb83
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb2
-rw-r--r--actionpack/lib/action_dispatch/request/session.rb100
-rw-r--r--actionpack/lib/action_dispatch/request/utils.rb66
-rw-r--r--actionpack/lib/action_dispatch/routing.rb9
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb6
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb729
-rw-r--r--actionpack/lib/action_dispatch/routing/redirection.rb6
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb225
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb31
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb25
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb18
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb40
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb8
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb31
-rw-r--r--actionpack/lib/action_dispatch/testing/test_response.rb5
-rw-r--r--actionpack/test/abstract/collector_test.rb6
-rw-r--r--actionpack/test/abstract/translation_test.rb22
-rw-r--r--actionpack/test/abstract_unit.rb156
-rw-r--r--actionpack/test/assertions/response_assertions_test.rb4
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb235
-rw-r--r--actionpack/test/controller/api/conditional_get_test.rb57
-rw-r--r--actionpack/test/controller/api/data_streaming_test.rb26
-rw-r--r--actionpack/test/controller/api/force_ssl_test.rb20
-rw-r--r--actionpack/test/controller/api/implicit_render_test.rb15
-rw-r--r--actionpack/test/controller/api/params_wrapper_test.rb26
-rw-r--r--actionpack/test/controller/api/redirect_to_test.rb19
-rw-r--r--actionpack/test/controller/api/renderers_test.rb38
-rw-r--r--actionpack/test/controller/api/url_for_test.rb20
-rw-r--r--actionpack/test/controller/base_test.rb10
-rw-r--r--actionpack/test/controller/caching_test.rb62
-rw-r--r--actionpack/test/controller/content_type_test.rb58
-rw-r--r--actionpack/test/controller/default_url_options_with_before_action_test.rb2
-rw-r--r--actionpack/test/controller/filters_test.rb186
-rw-r--r--actionpack/test/controller/flash_test.rb53
-rw-r--r--actionpack/test/controller/force_ssl_test.rb22
-rw-r--r--actionpack/test/controller/form_builder_test.rb17
-rw-r--r--actionpack/test/controller/helper_test.rb21
-rw-r--r--actionpack/test/controller/http_basic_authentication_test.rb23
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb13
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb21
-rw-r--r--actionpack/test/controller/integration_test.rb343
-rw-r--r--actionpack/test/controller/live_stream_test.rb122
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb6
-rw-r--r--actionpack/test/controller/mime/respond_to_test.rb217
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb24
-rw-r--r--actionpack/test/controller/new_base/base_test.rb6
-rw-r--r--actionpack/test/controller/new_base/content_negotiation_test.rb2
-rw-r--r--actionpack/test/controller/new_base/content_type_test.rb20
-rw-r--r--actionpack/test/controller/new_base/metal_test.rb43
-rw-r--r--actionpack/test/controller/new_base/middleware_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_html_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_plain_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_test.rb6
-rw-r--r--actionpack/test/controller/new_base/render_text_test.rb52
-rw-r--r--actionpack/test/controller/parameters/always_permitted_parameters_test.rb1
-rw-r--r--actionpack/test/controller/parameters/nested_parameters_test.rb2
-rw-r--r--actionpack/test/controller/parameters/parameters_permit_test.rb15
-rw-r--r--actionpack/test/controller/params_wrapper_test.rb42
-rw-r--r--actionpack/test/controller/permitted_params_test.rb4
-rw-r--r--actionpack/test/controller/redirect_test.rb24
-rw-r--r--actionpack/test/controller/render_json_test.rb2
-rw-r--r--actionpack/test/controller/render_other_test.rb2
-rw-r--r--actionpack/test/controller/render_test.rb81
-rw-r--r--actionpack/test/controller/render_xml_test.rb2
-rw-r--r--actionpack/test/controller/renderer_test.rb23
-rw-r--r--actionpack/test/controller/request/test_request_test.rb6
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb138
-rw-r--r--actionpack/test/controller/required_params_test.rb17
-rw-r--r--actionpack/test/controller/rescue_test.rb45
-rw-r--r--actionpack/test/controller/resources_test.rb141
-rw-r--r--actionpack/test/controller/routing_test.rb64
-rw-r--r--actionpack/test/controller/send_file_test.rb108
-rw-r--r--actionpack/test/controller/test_case_test.rb213
-rw-r--r--actionpack/test/controller/url_for_integration_test.rb1
-rw-r--r--actionpack/test/controller/url_for_test.rb20
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb3
-rw-r--r--actionpack/test/controller/webservice_test.rb34
-rw-r--r--actionpack/test/dispatch/callbacks_test.rb2
-rw-r--r--actionpack/test/dispatch/cookies_test.rb186
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb76
-rw-r--r--actionpack/test/dispatch/exception_wrapper_test.rb50
-rw-r--r--actionpack/test/dispatch/header_test.rb32
-rw-r--r--actionpack/test/dispatch/live_response_test.rb18
-rw-r--r--actionpack/test/dispatch/mapper_test.rb103
-rw-r--r--actionpack/test/dispatch/middleware_stack/middleware_test.rb77
-rw-r--r--actionpack/test/dispatch/middleware_stack_test.rb55
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb124
-rw-r--r--actionpack/test/dispatch/mount_test.rb2
-rw-r--r--actionpack/test/dispatch/prefix_generation_test.rb24
-rw-r--r--actionpack/test/dispatch/request/json_params_parsing_test.rb20
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb13
-rw-r--r--actionpack/test/dispatch/request/session_test.rb42
-rw-r--r--actionpack/test/dispatch/request_test.rb162
-rw-r--r--actionpack/test/dispatch/response_test.rb120
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb30
-rw-r--r--actionpack/test/dispatch/routing/ipv6_redirect_test.rb45
-rw-r--r--actionpack/test/dispatch/routing/route_set_test.rb14
-rw-r--r--actionpack/test/dispatch/routing_test.rb121
-rw-r--r--actionpack/test/dispatch/session/abstract_store_test.rb10
-rw-r--r--actionpack/test/dispatch/session/cache_store_test.rb6
-rw-r--r--actionpack/test/dispatch/session/cookie_store_test.rb44
-rw-r--r--actionpack/test/dispatch/session/mem_cache_store_test.rb6
-rw-r--r--actionpack/test/dispatch/session/test_session_test.rb20
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb18
-rw-r--r--actionpack/test/dispatch/ssl_test.rb292
-rw-r--r--actionpack/test/dispatch/static_test.rb79
-rw-r--r--actionpack/test/dispatch/template_assertions_test.rb110
-rw-r--r--actionpack/test/dispatch/test_request_test.rb24
-rw-r--r--actionpack/test/dispatch/test_response_test.rb7
-rw-r--r--actionpack/test/dispatch/url_generation_test.rb2
-rw-r--r--actionpack/test/fixtures/customers/_commented_customer.html.erb1
-rw-r--r--actionpack/test/fixtures/customers/_customer.html.erb1
-rw-r--r--actionpack/test/fixtures/layouts/standard.html.erb2
-rw-r--r--actionpack/test/fixtures/multipart/utf8_filename10
-rw-r--r--actionpack/test/fixtures/public/foo/other-index.html1
-rw-r--r--actionpack/test/fixtures/public/other-index.html1
-rw-r--r--actionpack/test/fixtures/公共/foo/other-index.html1
-rw-r--r--actionpack/test/fixtures/公共/other-index.html1
-rw-r--r--actionpack/test/journey/nodes/symbol_test.rb2
-rw-r--r--actionpack/test/journey/path/pattern_test.rb72
-rw-r--r--actionpack/test/journey/route_test.rb31
-rw-r--r--actionpack/test/journey/router_test.rb331
-rw-r--r--actionpack/test/journey/routes_test.rb63
214 files changed, 6283 insertions, 4864 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 0ae96441ce..40f447ada7 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,220 @@
+* Catch invalid UTF-8 querystring values and respond with BadRequest
+
+ Check querystring params for invalid UTF-8 characters, and raise an
+ ActionController::BadRequest error if present. Previously these strings
+ would typically trigger errors further down the stack.
+
+ *Grey Baker*
+
+* Parse RSS/ATOM responses as XML, not HTML.
+
+ *Alexander Kaupanin*
+
+* Show helpful message in `BadRequest` exceptions due to invalid path
+ parameter encodings.
+
+ Fixes #21923.
+
+ *Agis Anastasopoulos*
+
+* Add the ability of returning arbitrary headers to ActionDispatch::Static
+
+ Now ActionDispatch::Static can accept HTTP headers so that developers
+ will have control of returning arbitrary headers like
+ 'Access-Control-Allow-Origin' when a response is delivered. They can be
+ configured with `#config`:
+
+ config.public_file_server.headers = {
+ "Cache-Control" => "public, max-age=60",
+ "Access-Control-Allow-Origin" => "http://rubyonrails.org"
+ }
+
+ *Yuki Nishijima*
+
+* Allow multiple `root` routes in same scope level. Example:
+
+ ```ruby
+ root 'blog#show', constraints: ->(req) { Hostname.blog_site?(req.host) }
+ root 'landing#show'
+ ```
+ *Rafael Sales*
+
+* Fix regression in mounted engine named routes generation for app deployed to
+ a subdirectory. `relative_url_root` was prepended to the path twice (e.g.
+ "/subdir/subdir/engine_path" instead of "/subdir/engine_path")
+
+ Fixes #20920. Fixes #21459.
+
+ *Matthew Erhard*
+
+* ActionDispatch::Response#new no longer applies default headers. If you want
+ default headers applied to the response object, then call
+ `ActionDispatch::Response.create`. This change only impacts people who are
+ directly constructing an `ActionDispatch::Response` object.
+
+* Accessing mime types via constants like `Mime::HTML` is deprecated. Please
+ change code like this:
+
+ Mime::HTML
+
+ To this:
+
+ Mime[:html]
+
+ This change is so that Rails will not manage a list of constants, and fixes
+ an issue where if a type isn't registered you could possibly get the wrong
+ object.
+
+ `Mime[:html]` is available in older versions of Rails, too, so you can
+ safely change libraries and plugins and maintain compatibility with
+ multiple versions of Rails.
+
+* `url_for` does not modify its arguments when generating polymorphic URLs.
+
+ *Bernerd Schaefer*
+
+* Make it easier to opt in to `config.force_ssl` and `config.ssl_options` by
+ making them less dangerous to try and easier to disable.
+
+ SSL redirect:
+ * Move `:host` and `:port` options within `redirect: { … }`. Deprecate.
+ * Introduce `:status` and `:body` to customize the redirect response.
+ The 301 permanent default makes it difficult to test the redirect and
+ back out of it since browsers remember the 301. Test with a 302 or 307
+ instead, then switch to 301 once you're confident that all is well.
+
+ HTTP Strict Transport Security (HSTS):
+ * Shorter max-age. Shorten the default max-age from 1 year to 180 days,
+ the low end for https://www.ssllabs.com/ssltest/ grading and greater
+ than the 18-week minimum to qualify for browser preload lists.
+ * Disabling HSTS. Setting `hsts: false` now sets `hsts { expires: 0 }`
+ instead of omitting the header. Omitting does nothing to disable HSTS
+ since browsers hang on to your previous settings until they expire.
+ Sending `{ hsts: { expires: 0 }}` flushes out old browser settings and
+ actually disables HSTS:
+ http://tools.ietf.org/html/rfc6797#section-6.1.1
+ * HSTS Preload. Introduce `preload: true` to set the `preload` flag,
+ indicating that your site may be included in browser preload lists,
+ including Chrome, Firefox, Safari, IE11, and Edge. Submit your site:
+ https://hstspreload.appspot.com
+
+ *Jeremy Daer*
+
+* Update `ActionController::TestSession#fetch` to behave more like
+ `ActionDispatch::Request::Session#fetch` when using non-string keys.
+
+ *Jeremy Friesen*
+
+* Using strings or symbols for middleware class names is deprecated. Convert
+ things like this:
+
+ middleware.use "Foo::Bar"
+
+ to this:
+
+ middleware.use Foo::Bar
+
+* ActionController::TestSession now accepts a default value as well as
+ a block for generating a default value based off the key provided.
+
+ This fixes calls to session#fetch in ApplicationController instances that
+ take more two arguments or a block from raising `ArgumentError: wrong
+ number of arguments (2 for 1)` when performing controller tests.
+
+ *Matthew Gerrior*
+
+* Fix `ActionController::Parameters#fetch` overwriting `KeyError` returned by
+ default block.
+
+ *Jonas Schuber Erlandsson*, *Roque Pinel*
+
+* `ActionController::Parameters` no longer inherits from
+ `HashWithIndifferentAccess`
+
+ Inheriting from `HashWithIndifferentAccess` allowed users to call any
+ enumerable methods on `Parameters` object, resulting in a risk of losing the
+ `permitted?` status or even getting back a pure `Hash` object instead of
+ a `Parameters` object with proper sanitization.
+
+ By not inheriting from `HashWithIndifferentAccess`, we are able to make
+ sure that all methods that are defined in `Parameters` object will return
+ a proper `Parameters` object with a correct `permitted?` flag.
+
+ *Prem Sichanugrist*
+
+* Replaced `ActiveSupport::Concurrency::Latch` with `Concurrent::CountDownLatch`
+ from the concurrent-ruby gem.
+
+ *Jerry D'Antonio*
+
+* Add ability to filter parameters based on parent keys.
+
+ # matches {credit_card: {code: "xxxx"}}
+ # doesn't match {file: { code: "xxxx"}}
+ config.filter_parameters += [ "credit_card.code" ]
+
+ See #13897.
+
+ *Guillaume Malette*
+
+* Deprecate passing first parameter as `Hash` and default status code for `head` method.
+
+ *Mehmet Emin İNAÇ*
+
+* Adds`Rack::Utils::ParameterTypeError` and `Rack::Utils::InvalidParameterError`
+ to the rescue_responses hash in `ExceptionWrapper` (Rack recommends
+ integrators serve 400s for both of these).
+
+ *Grey Baker*
+
+* Add support for API only apps.
+ ActionController::API is added as a replacement of
+ ActionController::Base for this kind of applications.
+
+ *Santiago Pastorino & Jorge Bejar*
+
+* Remove `assigns` and `assert_template`. Both methods have been extracted
+ into a gem at https://github.com/rails/rails-controller-testing.
+
+ See #18950.
+
+ *Alan Guo Xiang Tan*
+
+* `FileHandler` and `Static` middleware initializers accept `index` argument
+ to configure the directory index file name. Defaults to `index` (as in
+ `index.html`).
+
+ See #20017.
+
+ *Eliot Sykes*
+
+* Deprecate `:nothing` option for `render` method.
+
+ *Mehmet Emin İNAÇ*
+
+* Fix `rake routes` not showing the right format when
+ nesting multiple routes.
+
+ See #18373.
+
+ *Ravil Bayramgalin*
+
+* Add ability to override default form builder for a controller.
+
+ class AdminController < ApplicationController
+ default_form_builder AdminFormBuilder
+ end
+
+ *Kevin McPhillips*
+
+* For actions with no corresponding templates, render `head :no_content`
+ instead of raising an error. This allows for slimmer API controller
+ methods that simply work, without needing further instructions.
+
+ See #19036.
+
+ *Stephen Bussey*
+
* Provide friendlier access to request variants.
request.variant = :phone
@@ -19,14 +236,24 @@
*Kohei Suzuki*
-* Fix handling of empty X_FORWARDED_HOST header in raw_host_with_port
+* Fix handling of empty `X_FORWARDED_HOST` header in `raw_host_with_port`.
- Previously, an empty X_FORWARDED_HOST header would cause
- Actiondispatch::Http:URL.raw_host_with_port to return nil, causing
- Actiondispatch::Http:URL.host to raise a NoMethodError.
+ Previously, an empty `X_FORWARDED_HOST` header would cause
+ `Actiondispatch::Http:URL.raw_host_with_port` to return `nil`, causing
+ `Actiondispatch::Http:URL.host` to raise a `NoMethodError`.
*Adam Forsyth*
+* Allow `Bearer` as token-keyword in `Authorization-Header`.
+
+ Aditionally to `Token`, the keyword `Bearer` is acceptable as a keyword
+ for the auth-token. The `Bearer` keyword is described in the original
+ OAuth RFC and used in libraries like Angular-JWT.
+
+ See #19094.
+
+ *Peter Schröder*
+
* Drop request class from RouteSet constructor.
If you would like to use a custom request class, please subclass and implement
@@ -86,7 +313,8 @@
*arthurnn*
* `ActionController#translate` supports symbols as shortcuts.
- When shortcut is given it also lookups without action name.
+ When a shortcut is given it also performs the lookup without the action
+ name.
*Max Melentiev*
@@ -154,13 +382,13 @@
* Preserve default url options when generating URLs.
- Fixes an issue that would cause default_url_options to be lost when
+ Fixes an issue that would cause `default_url_options` to be lost when
generating URLs with fewer positional arguments than parameters in the
route definition.
*Tekin Suleyman*
-* Deprecate *_via_redirect integration test methods.
+* Deprecate `*_via_redirect` integration test methods.
Use `follow_redirect!` manually after the request call for the same behavior.
@@ -183,11 +411,11 @@
*Jonas Baumann*
-* Deprecate all *_filter callbacks in favor of *_action callbacks.
+* Deprecate all `*_filter` callbacks in favor of `*_action` callbacks.
*Rafael Mendonça França*
-* Allow you to pass `prepend: false` to protect_from_forgery to have the
+* Allow you to pass `prepend: false` to `protect_from_forgery` to have the
verification callback appended instead of prepended to the chain.
This allows you to let the verification step depend on prior callbacks.
@@ -258,7 +486,7 @@
* Ensure `append_info_to_payload` is called even if an exception is raised.
- Fixes an issue where when an exception is raised in the request the additonal
+ Fixes an issue where when an exception is raised in the request the additional
payload data is not available.
See:
@@ -289,7 +517,7 @@
* Stop converting empty arrays in `params` to `nil`.
- This behaviour was introduced in response to CVE-2012-2660, CVE-2012-2694
+ This behavior was introduced in response to CVE-2012-2660, CVE-2012-2694
and CVE-2013-0155
ActiveRecord now issues a safe query when passing an empty array into
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 02a24a7412..44c980b070 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -28,7 +28,7 @@ can be used outside of Rails.
The latest version of Action Pack can be installed with RubyGems:
- % [sudo] gem install actionpack
+ % gem install actionpack
Source code can be downloaded as part of the Rails project on GitHub
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 3bd27f8d64..601263bfac 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -1,5 +1,4 @@
require 'rake/testtask'
-require 'rubygems/package_task'
test_files = Dir.glob('test/**/*_test.rb')
@@ -24,19 +23,6 @@ namespace :test do
end
end
-spec = eval(File.read('actionpack.gemspec'))
-
-Gem::PackageTask.new(spec) do |p|
- p.gem_spec = spec
-end
-
-desc "Release to rubygems"
-task :release => :package do
- require 'rake/gemcutter'
- Rake::Gemcutter::Tasks.new(spec).define
- Rake::Task['gem:push'].invoke
-end
-
task :lines do
load File.expand_path('..', File.dirname(__FILE__)) + '/tools/line_statistics'
files = FileList["lib/**/*.rb"]
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index b6b70a027c..28d8bc3091 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
@@ -21,7 +21,7 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
- s.add_dependency 'rack', '~> 1.6'
+ s.add_dependency 'rack', '~> 2.x'
s.add_dependency 'rack-test', '~> 0.6.3'
s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.2'
s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5'
diff --git a/actionpack/bin/test b/actionpack/bin/test
new file mode 100755
index 0000000000..404cabba51
--- /dev/null
+++ b/actionpack/bin/test
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+require File.expand_path("../tools/test", COMPONENT_ROOT)
+exit Minitest.run(ARGV)
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb
index fe9802e395..56c4033387 100644
--- a/actionpack/lib/abstract_controller.rb
+++ b/actionpack/lib/abstract_controller.rb
@@ -1,7 +1,5 @@
require 'action_pack'
require 'active_support/rails'
-require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/anonymous'
require 'active_support/i18n'
module AbstractController
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index c95b9a4097..7f349f2741 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -1,8 +1,8 @@
require 'erubis'
-require 'set'
require 'active_support/configurable'
require 'active_support/descendants_tracker'
require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/module/attr_internal'
module AbstractController
class Error < StandardError #:nodoc:
@@ -88,7 +88,7 @@ module AbstractController
# Returns the full controller name, underscored, without the ending Controller.
#
# class MyApp::MyPostsController < AbstractController::Base
- # end
+ #
# end
#
# MyApp::MyPostsController.controller_path # => "my_app/my_posts"
@@ -96,7 +96,7 @@ module AbstractController
# ==== Returns
# * <tt>String</tt>
def controller_path
- @controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
+ @controller_path ||= name.sub(/Controller$/, ''.freeze).underscore unless anonymous?
end
# Refresh the cached action_methods when a new action_method is added.
@@ -148,11 +148,8 @@ module AbstractController
#
# ==== Parameters
# * <tt>action_name</tt> - The name of an action to be tested
- #
- # ==== Returns
- # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
def available_action?(action_name)
- _find_action_name(action_name).present?
+ _find_action_name(action_name)
end
# Returns true if the given controller is capable of rendering
@@ -171,9 +168,6 @@ module AbstractController
# ==== Parameters
# * <tt>name</tt> - The name of an action to be tested
#
- # ==== Returns
- # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
- #
# :api: private
def action_method?(name)
self.class.action_methods.include?(name)
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 59ffb0a19e..d5317e4717 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -39,8 +39,8 @@ module AbstractController
# except: :index, if: -> { true } # the :except option will be ignored.
#
# ==== Options
- # * <tt>only</tt> - The callback should be run only for this action
- # * <tt>except</tt> - The callback should be run for all actions except this action
+ # * <tt>only</tt> - The callback should be run only for this action.
+ # * <tt>except</tt> - The callback should be run for all actions except this action.
def _normalize_callback_options(options)
_normalize_callback_option(options, :only, :if)
_normalize_callback_option(options, :except, :unless)
@@ -59,12 +59,12 @@ module AbstractController
# * <tt>names</tt> - A list of valid names that could be used for
# callbacks. Note that skipping uses Ruby equality, so it's
# impossible to skip a callback defined using an anonymous proc
- # using #skip_action_callback
+ # using #skip_action_callback.
def skip_action_callback(*names)
- ActiveSupport::Deprecation.warn('`skip_action_callback` is deprecated and will be removed in the next major version of Rails. Please use skip_before_action, skip_after_action or skip_around_action instead.')
- skip_before_action(*names)
- skip_after_action(*names)
- skip_around_action(*names)
+ ActiveSupport::Deprecation.warn('`skip_action_callback` is deprecated and will be removed in Rails 5.1. Please use skip_before_action, skip_after_action or skip_around_action instead.')
+ skip_before_action(*names, raise: false)
+ skip_after_action(*names, raise: false)
+ skip_around_action(*names, raise: false)
end
def skip_filter(*names)
@@ -82,8 +82,8 @@ module AbstractController
# * <tt>block</tt> - A proc that should be added to the callbacks.
#
# ==== Block Parameters
- # * <tt>name</tt> - The callback to be added
- # * <tt>options</tt> - A hash of options to be used when adding the callback
+ # * <tt>name</tt> - The callback to be added.
+ # * <tt>options</tt> - A hash of options to be used when adding the callback.
def _insert_callbacks(callbacks, block = nil)
options = callbacks.extract_options!
_normalize_callback_options(options)
diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb
index ddd56b354a..55654be224 100644
--- a/actionpack/lib/abstract_controller/collector.rb
+++ b/actionpack/lib/abstract_controller/collector.rb
@@ -4,11 +4,10 @@ module AbstractController
module Collector
def self.generate_method_for_mime(mime)
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
- const = sym.upcase
class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{sym}(*args, &block) # def html(*args, &block)
- custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
- end # end
+ def #{sym}(*args, &block)
+ custom(Mime[:#{sym}], *args, &block)
+ end
RUBY
end
@@ -23,9 +22,7 @@ module AbstractController
protected
def method_missing(symbol, &block)
- const_name = symbol.upcase
-
- unless Mime.const_defined?(const_name)
+ unless mime_constant = Mime[symbol]
raise NoMethodError, "To respond to a custom format, register it as a MIME type first: " \
"http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads. " \
"If you meant to respond to a variant like :tablet or :phone, not a custom format, " \
@@ -33,8 +30,6 @@ module AbstractController
"format.html { |html| html.tablet { ... } }"
end
- mime_constant = Mime.const_get(const_name)
-
if Mime::SET.include?(mime_constant)
AbstractController::Collector.generate_method_for_mime(mime_constant)
send(symbol, &block)
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 109eff10eb..d84c238a62 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -181,7 +181,7 @@ module AbstractController
end
def default_helper_module!
- module_name = name.sub(/Controller$/, '')
+ module_name = name.sub(/Controller$/, ''.freeze)
module_path = module_name.underscore
helper module_path
rescue LoadError => e
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index 5514213ad8..a73f188623 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -22,9 +22,13 @@ module AbstractController
# :api: public
def render(*args, &block)
options = _normalize_render(*args, &block)
- self.response_body = render_to_body(options)
- _process_format(rendered_format, options) if rendered_format
- self.response_body
+ rendered_body = render_to_body(options)
+ if options[:html]
+ _set_html_content_type
+ else
+ _set_rendered_content_type rendered_format
+ end
+ self.response_body = rendered_body
end
# Raw rendering of a template to a string.
@@ -51,14 +55,14 @@ module AbstractController
# Returns Content-Type of rendered content
# :api: public
def rendered_format
- Mime::TEXT
+ Mime[:text]
end
- DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %w(
+ DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %i(
@_action_name @_response_body @_formats @_prefixes @_config
@_view_context_class @_view_renderer @_lookup_context
@_routes @_db_runtime
- ).map(&:to_sym)
+ )
# This method should return a hash with assigns.
# You can overwrite this configuration per controller.
@@ -99,7 +103,13 @@ module AbstractController
# Process the rendered format.
# :api: private
- def _process_format(format, options = {})
+ def _process_format(format)
+ end
+
+ def _set_html_content_type # :nodoc:
+ end
+
+ def _set_rendered_content_type(format) # :nodoc:
end
# Normalize args and options.
@@ -107,7 +117,7 @@ module AbstractController
def _normalize_render(*args, &block)
options = _normalize_args(*args, &block)
#TODO: remove defined? when we restore AP <=> AV dependency
- if defined?(request) && request && request.variant.present?
+ if defined?(request) && request.variant.present?
options[:variant] = request.variant
end
_normalize_options(options)
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 7667e469d3..3d3af555c9 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -7,14 +7,15 @@ require 'action_controller/metal/strong_parameters'
module ActionController
extend ActiveSupport::Autoload
+ autoload :API
autoload :Base
autoload :Caching
autoload :Metal
autoload :Middleware
autoload :Renderer
+ autoload :FormBuilder
autoload_under "metal" do
- autoload :Compatibility
autoload :ConditionalGet
autoload :Cookies
autoload :DataStreaming
@@ -24,11 +25,11 @@ module ActionController
autoload :Head
autoload :Helpers
autoload :HttpAuthentication
+ autoload :BasicImplicitRender
autoload :ImplicitRender
autoload :Instrumentation
autoload :MimeResponds
autoload :ParamsWrapper
- autoload :RackDelegation
autoload :Redirecting
autoload :Renderers
autoload :Rendering
diff --git a/actionpack/lib/action_controller/api.rb b/actionpack/lib/action_controller/api.rb
new file mode 100644
index 0000000000..1a46d49a49
--- /dev/null
+++ b/actionpack/lib/action_controller/api.rb
@@ -0,0 +1,146 @@
+require 'action_view'
+require 'action_controller'
+require 'action_controller/log_subscriber'
+
+module ActionController
+ # API Controller is a lightweight version of <tt>ActionController::Base</tt>,
+ # created for applications that don't require all functionalities that a complete
+ # \Rails controller provides, allowing you to create controllers with just the
+ # features that you need for API only applications.
+ #
+ # An API Controller is different from a normal controller in the sense that
+ # by default it doesn't include a number of features that are usually required
+ # by browser access only: layouts and templates rendering, cookies, sessions,
+ # flash, assets, and so on. This makes the entire controller stack thinner,
+ # suitable for API applications. It doesn't mean you won't have such
+ # features if you need them: they're all available for you to include in
+ # your application, they're just not part of the default API Controller stack.
+ #
+ # By default, only the ApplicationController in a \Rails application inherits
+ # from <tt>ActionController::API</tt>. All other controllers in turn inherit
+ # from ApplicationController.
+ #
+ # A sample controller could look like this:
+ #
+ # class PostsController < ApplicationController
+ # def index
+ # @posts = Post.all
+ # render json: @posts
+ # end
+ # end
+ #
+ # Request, response and parameters objects all work the exact same way as
+ # <tt>ActionController::Base</tt>.
+ #
+ # == Renders
+ #
+ # The default API Controller stack includes all renderers, which means you
+ # can use <tt>render :json</tt> and brothers freely in your controllers. Keep
+ # in mind that templates are not going to be rendered, so you need to ensure
+ # your controller is calling either <tt>render</tt> or <tt>redirect</tt> in
+ # all actions, otherwise it will return 204 No Content response.
+ #
+ # def show
+ # @post = Post.find(params[:id])
+ # render json: @post
+ # end
+ #
+ # == Redirects
+ #
+ # Redirects are used to move from one action to another. You can use the
+ # <tt>redirect</tt> method in your controllers in the same way as
+ # <tt>ActionController::Base</tt>. For example:
+ #
+ # def create
+ # redirect_to root_url and return if not_authorized?
+ # # do stuff here
+ # end
+ #
+ # == Adding new behavior
+ #
+ # In some scenarios you may want to add back some functionality provided by
+ # <tt>ActionController::Base</tt> that is not present by default in
+ # <tt>ActionController::API</tt>, for instance <tt>MimeResponds</tt>. This
+ # module gives you the <tt>respond_to</tt> method. Adding it is quite simple,
+ # you just need to include the module in a specific controller or in
+ # +ApplicationController+ in case you want it available in your entire
+ # application:
+ #
+ # class ApplicationController < ActionController::API
+ # include ActionController::MimeResponds
+ # end
+ #
+ # class PostsController < ApplicationController
+ # def index
+ # @posts = Post.all
+ #
+ # respond_to do |format|
+ # format.json { render json: @posts }
+ # format.xml { render xml: @posts }
+ # end
+ # end
+ # end
+ #
+ # Quite straightforward. Make sure to check <tt>ActionController::Base</tt>
+ # available modules if you want to include any other functionality that is
+ # not provided by <tt>ActionController::API</tt> out of the box.
+ class API < Metal
+ abstract!
+
+ # Shortcut helper that returns all the ActionController::API modules except
+ # the ones passed as arguments:
+ #
+ # class MyAPIBaseController < ActionController::Metal
+ # ActionController::API.without_modules(:ForceSSL, :UrlFor).each do |left|
+ # include left
+ # end
+ # end
+ #
+ # This gives better control over what you want to exclude and makes it easier
+ # to create an API controller class, instead of listing the modules required
+ # manually.
+ def self.without_modules(*modules)
+ modules = modules.map do |m|
+ m.is_a?(Symbol) ? ActionController.const_get(m) : m
+ end
+
+ MODULES - modules
+ end
+
+ MODULES = [
+ AbstractController::Rendering,
+
+ UrlFor,
+ Redirecting,
+ Rendering,
+ Renderers::All,
+ ConditionalGet,
+ BasicImplicitRender,
+ StrongParameters,
+
+ ForceSSL,
+ DataStreaming,
+
+ # Before callbacks should also be executed as early as possible, so
+ # also include them at the bottom.
+ AbstractController::Callbacks,
+
+ # Append rescue at the bottom to wrap as much as possible.
+ Rescue,
+
+ # Add instrumentations hooks at the bottom, to ensure they instrument
+ # all the methods properly.
+ Instrumentation,
+
+ # Params wrapper should come before instrumentation so they are
+ # properly showed in logs
+ ParamsWrapper
+ ]
+
+ MODULES.each do |mod|
+ include mod
+ end
+
+ ActiveSupport.run_load_hooks(:action_controller, self)
+ end
+end
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index e6038396f9..04e5922ce8 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -50,9 +50,9 @@ module ActionController
#
# == Parameters
#
- # All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
- # which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
- # <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
+ # All request parameters, whether they come from a query string in the URL or form data submitted through a POST request are
+ # available through the params method which returns a hash. For example, an action that was performed through
+ # <tt>/posts?category=All&limit=5</tt> will include <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
#
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
#
@@ -183,7 +183,7 @@ module ActionController
# Shortcut helper that returns all the modules included in
# ActionController::Base except the ones passed as arguments:
#
- # class MetalController
+ # class MyBaseController < ActionController::Metal
# ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
# include left
# end
@@ -213,7 +213,6 @@ module ActionController
Renderers::All,
ConditionalGet,
EtagWithTemplateDigest,
- RackDelegation,
Caching,
MimeResponds,
ImplicitRender,
@@ -221,6 +220,7 @@ module ActionController
Cookies,
Flash,
+ FormBuilder,
RequestForgeryProtection,
ForceSSL,
Streaming,
@@ -248,20 +248,17 @@ module ActionController
MODULES.each do |mod|
include mod
end
+ setup_renderer!
# Define some internal variables that should not be propagated to the view.
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [
- :@_status, :@_headers, :@_params, :@_env, :@_response, :@_request,
+ :@_params, :@_response, :@_request,
:@_view_runtime, :@_stream, :@_url_options, :@_action_has_layout ]
def _protected_ivars # :nodoc:
PROTECTED_IVARS
end
- def self.protected_instance_variables
- PROTECTED_IVARS
- end
-
ActiveSupport.run_load_hooks(:action_controller, self)
end
end
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index de85e0c1a7..0b8fa2ea09 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -1,6 +1,5 @@
require 'fileutils'
require 'uri'
-require 'set'
module ActionController
# \Caching is a cheap way of speeding up slow applications by keeping the result of
@@ -8,7 +7,7 @@ module ActionController
#
# You can read more about each approach by clicking the modules below.
#
- # Note: To turn off all caching, set
+ # Note: To turn off all caching provided by Action Controller, set
# config.action_controller.perform_caching = false
#
# == \Caching stores
@@ -46,7 +45,6 @@ module ActionController
end
end
- include RackDelegation
include AbstractController::Callbacks
include ConfigMethods
diff --git a/actionpack/lib/action_controller/form_builder.rb b/actionpack/lib/action_controller/form_builder.rb
new file mode 100644
index 0000000000..f2656ca894
--- /dev/null
+++ b/actionpack/lib/action_controller/form_builder.rb
@@ -0,0 +1,48 @@
+module ActionController
+ # Override the default form builder for all views rendered by this
+ # controller and any of its descendants. Accepts a subclass of
+ # +ActionView::Helpers::FormBuilder+.
+ #
+ # For example, given a form builder:
+ #
+ # class AdminFormBuilder < ActionView::Helpers::FormBuilder
+ # def special_field(name)
+ # end
+ # end
+ #
+ # The controller specifies a form builder as its default:
+ #
+ # class AdminAreaController < ApplicationController
+ # default_form_builder AdminFormBuilder
+ # end
+ #
+ # Then in the view any form using +form_for+ will be an instance of the
+ # specified form builder:
+ #
+ # <%= form_for(@instance) do |builder| %>
+ # <%= builder.special_field(:name) %>
+ # <% end %>
+ module FormBuilder
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_default_form_builder, instance_accessor: false
+ end
+
+ module ClassMethods
+ # Set the form builder to be used as the default for all forms
+ # in the views rendered by this controller and its subclasses.
+ #
+ # ==== Parameters
+ # * <tt>builder</tt> - Default form builder, an instance of +ActionView::Helpers::FormBuilder+
+ def default_form_builder(builder)
+ self._default_form_builder = builder
+ end
+ end
+
+ # Default form builder for the controller
+ def default_form_builder
+ self.class._default_form_builder
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 87609d8aa7..4c9f14e409 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -25,7 +25,7 @@ module ActionController
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
end
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
- message << " (#{additions.join(" | ")})" unless additions.blank?
+ message << " (#{additions.join(" | ".freeze)})" unless additions.blank?
message
end
end
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index ae111e4951..8e040bb465 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -1,5 +1,7 @@
require 'active_support/core_ext/array/extract_options'
require 'action_dispatch/middleware/stack'
+require 'action_dispatch/http/request'
+require 'action_dispatch/http/response'
module ActionController
# Extend ActionDispatch middleware stack to make it aware of options
@@ -11,22 +13,14 @@ module ActionController
#
class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
- def initialize(klass, *args, &block)
- options = args.extract_options!
- @only = Array(options.delete(:only)).map(&:to_s)
- @except = Array(options.delete(:except)).map(&:to_s)
- args << options unless options.empty?
- super
+ def initialize(klass, args, actions, strategy, block)
+ @actions = actions
+ @strategy = strategy
+ super(klass, args, block)
end
def valid?(action)
- if @only.present?
- @only.include?(action)
- elsif @except.present?
- !@except.include?(action)
- else
- true
- end
+ @strategy.call @actions, action
end
end
@@ -37,6 +31,32 @@ module ActionController
middleware.valid?(action) ? middleware.build(a) : a
end
end
+
+ private
+
+ INCLUDE = ->(list, action) { list.include? action }
+ EXCLUDE = ->(list, action) { !list.include? action }
+ NULL = ->(list, action) { true }
+
+ def build_middleware(klass, args, block)
+ options = args.extract_options!
+ only = Array(options.delete(:only)).map(&:to_s)
+ except = Array(options.delete(:except)).map(&:to_s)
+ args << options unless options.empty?
+
+ strategy = NULL
+ list = nil
+
+ if only.any?
+ strategy = INCLUDE
+ list = only
+ elsif except.any?
+ strategy = EXCLUDE
+ list = except
+ end
+
+ Middleware.new(get_class(klass), args, list, strategy, block)
+ end
end
# <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
@@ -98,11 +118,10 @@ module ActionController
class Metal < AbstractController::Base
abstract!
- attr_internal_writer :env
-
def env
- @_env ||= {}
+ @_request.env
end
+ deprecate :env
# Returns the last part of the controller's name, underscored, without the ending
# <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
@@ -114,23 +133,23 @@ module ActionController
@controller_name ||= name.demodulize.sub(/Controller$/, '').underscore
end
+ def self.make_response!(request)
+ ActionDispatch::Response.create.tap do |res|
+ res.request = request
+ end
+ end
+
# Delegates to the class' <tt>controller_name</tt>
def controller_name
self.class.controller_name
end
- # The details below can be overridden to support a specific
- # Request and Response object. The default ActionController::Base
- # implementation includes RackDelegation, which makes a request
- # and response object available. You might wish to control the
- # environment and response manually for performance reasons.
-
- attr_internal :headers, :response, :request
+ attr_internal :response, :request
delegate :session, :to => "@_request"
+ delegate :headers, :status=, :location=, :content_type=,
+ :status, :location, :content_type, :to => "@_response"
def initialize
- @_headers = {"Content-Type" => "text/html"}
- @_status = 200
@_request = nil
@_response = nil
@_routes = nil
@@ -145,64 +164,51 @@ module ActionController
@_params = val
end
- # Basic implementations for content_type=, location=, and headers are
- # provided to reduce the dependency on the RackDelegation module
- # in Renderer and Redirector.
-
- def content_type=(type)
- headers["Content-Type"] = type.to_s
- end
-
- def content_type
- headers["Content-Type"]
- end
-
- def location
- headers["Location"]
- end
-
- def location=(url)
- headers["Location"] = url
- end
+ alias :response_code :status # :nodoc:
# Basic url_for that can be overridden for more robust functionality
def url_for(string)
string
end
- def status
- @_status
- end
- alias :response_code :status # :nodoc:
-
- def status=(status)
- @_status = Rack::Utils.status_code(status)
- end
-
def response_body=(body)
body = [body] unless body.nil? || body.respond_to?(:each)
+ response.reset_body!
+ body.each { |part|
+ next if part.empty?
+ response.write part
+ }
super
end
# Tests if render or redirect has already happened.
def performed?
- response_body || (response && response.committed?)
+ response_body || response.committed?
end
- def dispatch(name, request) #:nodoc:
+ def dispatch(name, request, response) #:nodoc:
set_request!(request)
+ set_response!(response)
process(name)
+ request.commit_flash
to_a
end
+ def set_response!(response) # :nodoc:
+ @_response = response
+ end
+
def set_request!(request) #:nodoc:
@_request = request
- @_env = request.env
- @_env['action_controller.instance'] = self
+ @_request.controller_instance = self
end
def to_a #:nodoc:
- response ? response.to_a : [status, headers, response_body]
+ response.to_a
+ end
+
+ def reset_session
+ @_request.reset_session
end
class_attribute :middleware_stack
@@ -230,15 +236,32 @@ module ActionController
req = ActionDispatch::Request.new env
action(req.path_parameters[:action]).call(env)
end
+ class << self; deprecate :call; end
# Returns a Rack endpoint for the given action name.
- def self.action(name, klass = ActionDispatch::Request)
+ def self.action(name)
if middleware_stack.any?
middleware_stack.build(name) do |env|
- new.dispatch(name, klass.new(env))
+ req = ActionDispatch::Request.new(env)
+ res = make_response! req
+ new.dispatch(name, req, res)
end
else
- lambda { |env| new.dispatch(name, klass.new(env)) }
+ lambda { |env|
+ req = ActionDispatch::Request.new(env)
+ res = make_response! req
+ new.dispatch(name, req, res)
+ }
+ end
+ end
+
+ # Direct dispatch to the controller. Instantiates the controller, then
+ # executes the action named +name+.
+ def self.dispatch(name, req, res)
+ if middleware_stack.any?
+ middleware_stack.build(name) { |env| new.dispatch(name, req, res) }.call req.env
+ else
+ new.dispatch(name, req, res)
end
end
end
diff --git a/actionpack/lib/action_controller/metal/basic_implicit_render.rb b/actionpack/lib/action_controller/metal/basic_implicit_render.rb
new file mode 100644
index 0000000000..6c6f8381ff
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/basic_implicit_render.rb
@@ -0,0 +1,11 @@
+module ActionController
+ module BasicImplicitRender
+ def send_action(method, *args)
+ super.tap { default_render unless performed? }
+ end
+
+ def default_render(*args)
+ head :no_content
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index 47bcfdb1e9..d86a793e4c 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -4,7 +4,6 @@ module ActionController
module ConditionalGet
extend ActiveSupport::Concern
- include RackDelegation
include Head
included do
@@ -40,7 +39,7 @@ module ActionController
# * <tt>:etag</tt>.
# * <tt>:last_modified</tt>.
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
- # +true+ if you want your application to be cachable by other devices (proxy caches).
+ # +true+ if you want your application to be cacheable by other devices (proxy caches).
# * <tt>:template</tt> By default, the template digest for the current
# controller/action is included in ETags. If the action renders a
# different template, you can include its digest instead. If the action
@@ -67,7 +66,7 @@ module ActionController
#
# You can also pass an object that responds to +maximum+, such as a
# collection of active records. In this case +last_modified+ will be set by
- # calling +maximum(:updated_at)+ on the collection (the timestamp of the
+ # calling <tt>maximum(:updated_at)</tt> on the collection (the timestamp of the
# most recently updated record) and the +etag+ by passing the object itself.
#
# def index
@@ -111,7 +110,7 @@ module ActionController
# * <tt>:etag</tt>.
# * <tt>:last_modified</tt>.
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
- # +true+ if you want your application to be cachable by other devices (proxy caches).
+ # +true+ if you want your application to be cacheable by other devices (proxy caches).
# * <tt>:template</tt> By default, the template digest for the current
# controller/action is included in ETags. If the action renders a
# different template, you can include its digest instead. If the action
diff --git a/actionpack/lib/action_controller/metal/cookies.rb b/actionpack/lib/action_controller/metal/cookies.rb
index d787f014cd..f8efb2b076 100644
--- a/actionpack/lib/action_controller/metal/cookies.rb
+++ b/actionpack/lib/action_controller/metal/cookies.rb
@@ -2,8 +2,6 @@ module ActionController #:nodoc:
module Cookies
extend ActiveSupport::Concern
- include RackDelegation
-
included do
helper_method :cookies
end
diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb
index 1abd8d3a33..957e7a3019 100644
--- a/actionpack/lib/action_controller/metal/data_streaming.rb
+++ b/actionpack/lib/action_controller/metal/data_streaming.rb
@@ -72,27 +72,7 @@ module ActionController #:nodoc:
self.status = options[:status] || 200
self.content_type = options[:content_type] if options.key?(:content_type)
- self.response_body = FileBody.new(path)
- end
-
- # Avoid having to pass an open file handle as the response body.
- # Rack::Sendfile will usually intercept the response and uses
- # the path directly, so there is no reason to open the file.
- class FileBody #:nodoc:
- attr_reader :to_path
-
- def initialize(path)
- @to_path = path
- end
-
- # Stream the file's contents if Rack::Sendfile isn't present.
- def each
- File.open(to_path, 'rb') do |file|
- while chunk = file.read(16384)
- yield chunk
- end
- end
- end
+ response.send_file path
end
# Sends the given binary data to the browser. This method is similar to
@@ -126,7 +106,7 @@ module ActionController #:nodoc:
# See +send_file+ for more information on HTTP Content-* headers and caching.
def send_data(data, options = {}) #:doc:
send_file_headers! options
- render options.slice(:status, :content_type).merge(:text => data)
+ render options.slice(:status, :content_type).merge(body: data)
end
private
diff --git a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
index f9303efe6c..669cf55bca 100644
--- a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
+++ b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
@@ -25,7 +25,7 @@ module ActionController
class_attribute :etag_with_template_digest
self.etag_with_template_digest = true
- ActiveSupport.on_load :action_view, yield: true do |action_view_base|
+ ActiveSupport.on_load :action_view, yield: true do
etag do |options|
determine_template_etag(options) if etag_with_template_digest
end
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
index 18e003741d..5c0ada37be 100644
--- a/actionpack/lib/action_controller/metal/exceptions.rb
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -3,14 +3,19 @@ module ActionController
end
class BadRequest < ActionControllerError #:nodoc:
- attr_reader :original_exception
+ def initialize(msg = nil, e = nil)
+ if e
+ ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \
+ "Exceptions will automatically capture the original exception.", caller)
+ end
- def initialize(type = nil, e = nil)
- return super() unless type && e
+ super(msg)
+ set_backtrace $!.backtrace if $!
+ end
- super("Invalid #{type} parameters: #{e.message}")
- @original_exception = e
- set_backtrace e.backtrace
+ def original_exception
+ ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller)
+ cause
end
end
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
index d920668184..e31d65aac2 100644
--- a/actionpack/lib/action_controller/metal/force_ssl.rb
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -55,10 +55,10 @@ module ActionController
# You can pass any of the following options to affect the before_action callback
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except</tt> - The callback should be run for all actions except this action
- # * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
- # will be called only when it returns a true value.
- # * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
- # will be called only when it returns a false value.
+ # * <tt>if</tt> - A symbol naming an instance method or a proc; the
+ # callback will be called only when it returns a true value.
+ # * <tt>unless</tt> - A symbol naming an instance method or a proc; the
+ # callback will be called only when it returns a false value.
def force_ssl(options = {})
action_options = options.slice(*ACTION_OPTIONS)
redirect_options = options.except(*ACTION_OPTIONS)
@@ -71,8 +71,8 @@ module ActionController
# Redirect the existing request to use the HTTPS protocol.
#
# ==== Parameters
- # * <tt>host_or_options</tt> - Either a host name or any of the url & redirect options
- # available to the <tt>force_ssl</tt> method.
+ # * <tt>host_or_options</tt> - Either a host name or any of the url &
+ # redirect options available to the <tt>force_ssl</tt> method.
def force_ssl_redirect(host_or_options = nil)
unless request.ssl?
options = {
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 70f42bf565..b2110bf946 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -17,8 +17,18 @@ module ActionController
#
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list of valid +status+ symbols.
def head(status, options = {})
- options, status = status, nil if status.is_a?(Hash)
- status ||= options.delete(:status) || :ok
+ if status.is_a?(Hash)
+ msg = status[:status] ? 'The :status option' : 'The implicit :ok status'
+ options, status = status, status.delete(:status)
+
+ ActiveSupport::Deprecation.warn(<<-MSG.squish)
+ #{msg} on `head` has been deprecated and will be removed in Rails 5.1.
+ Please pass the status as a separate parameter before the options, instead.
+ MSG
+ end
+
+ status ||= :ok
+
location = options.delete(:location)
content_type = options.delete(:content_type)
@@ -33,12 +43,9 @@ module ActionController
if include_content?(self.response_code)
self.content_type = content_type || (Mime[formats.first] if formats)
- self.response.charset = false if self.response
- else
- headers.delete('Content-Type')
- headers.delete('Content-Length')
+ self.response.charset = false
end
-
+
true
end
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index 4038101fe0..d3853e2e83 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -7,8 +7,8 @@ module ActionController
# extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
# will include all helpers. These helpers are only accessible on the controller through <tt>.helpers</tt>
#
- # In previous versions of \Rails the controller will include a helper whose
- # name matches that of the controller, e.g., <tt>MyController</tt> will automatically
+ # In previous versions of \Rails the controller will include a helper which
+ # matches the name of the controller, e.g., <tt>MyController</tt> will automatically
# include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
#
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
@@ -44,7 +44,7 @@ module ActionController
# the output might look like this:
#
# 23 Aug 11:30 | Carolina Railhawks Soccer Match
- # N/A | Carolina Railhaws Training Workshop
+ # N/A | Carolina Railhawks Training Workshop
#
module Helpers
extend ActiveSupport::Concern
@@ -73,7 +73,7 @@ module ActionController
# Provides a proxy to access helpers methods from outside the view.
def helpers
- @helper_proxy ||= begin
+ @helper_proxy ||= begin
proxy = ActionView::Base.new
proxy.config = config.inheritable_copy
proxy.extend(_helpers)
@@ -100,7 +100,7 @@ module ActionController
def all_helpers_from_path(path)
helpers = Array(path).flat_map do |_path|
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
- names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
+ names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1'.freeze) }
names.sort!
end
helpers.uniq!
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 2273406948..0a36fecd27 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -34,7 +34,7 @@ module ActionController
#
# def authenticate
# case request.format
- # when Mime::XML, Mime::ATOM
+ # when Mime[:xml], Mime[:atom]
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
# @current_user = user
# else
@@ -74,16 +74,16 @@ module ActionController
end
end
- def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
- authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
+ def authenticate_or_request_with_http_basic(realm = "Application", message = nil, &login_procedure)
+ authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm, message)
end
def authenticate_with_http_basic(&login_procedure)
HttpAuthentication::Basic.authenticate(request, &login_procedure)
end
- def request_http_basic_authentication(realm = "Application")
- HttpAuthentication::Basic.authentication_request(self, realm)
+ def request_http_basic_authentication(realm = "Application", message = nil)
+ HttpAuthentication::Basic.authentication_request(self, realm, message)
end
end
@@ -94,7 +94,7 @@ module ActionController
end
def has_basic_credentials?(request)
- request.authorization.present? && (auth_scheme(request) == 'Basic')
+ request.authorization.present? && (auth_scheme(request).downcase == 'basic')
end
def user_name_and_password(request)
@@ -117,10 +117,11 @@ module ActionController
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
end
- def authentication_request(controller, realm)
- controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
+ def authentication_request(controller, realm, message)
+ message ||= "HTTP Basic: Access denied.\n"
+ controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.tr('"'.freeze, "".freeze)}")
controller.status = 401
- controller.response_body = "HTTP Basic: Access denied.\n"
+ controller.response_body = message
end
end
@@ -170,8 +171,8 @@ module ActionController
extend self
module ControllerMethods
- def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
- authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
+ def authenticate_or_request_with_http_digest(realm = "Application", message = nil, &password_procedure)
+ authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm, message)
end
# Authenticate with HTTP Digest, returns true or false
@@ -202,7 +203,7 @@ module ActionController
password = password_procedure.call(credentials[:username])
return false unless password
- method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
+ method = request.get_header('rack.methodoverride.original_method') || request.get_header('REQUEST_METHOD')
uri = credentials[:uri]
[true, false].any? do |trailing_question_mark|
@@ -259,8 +260,8 @@ module ActionController
end
def secret_token(request)
- key_generator = request.env["action_dispatch.key_generator"]
- http_auth_salt = request.env["action_dispatch.http_auth_salt"]
+ key_generator = request.key_generator
+ http_auth_salt = request.http_auth_salt
key_generator.generate_key(http_auth_salt)
end
@@ -360,7 +361,7 @@ module ActionController
#
# def authenticate
# case request.format
- # when Mime::XML, Mime::ATOM
+ # when Mime[:xml], Mime[:atom]
# if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
# @current_user = user
# else
@@ -396,21 +397,21 @@ module ActionController
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
module Token
TOKEN_KEY = 'token='
- TOKEN_REGEX = /^Token /
+ TOKEN_REGEX = /^(Token|Bearer) /
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
extend self
module ControllerMethods
- def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
- authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
+ def authenticate_or_request_with_http_token(realm = "Application", message = nil, &login_procedure)
+ authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm, message)
end
def authenticate_with_http_token(&login_procedure)
Token.authenticate(self, &login_procedure)
end
- def request_http_token_authentication(realm = "Application")
- Token.authentication_request(self, realm)
+ def request_http_token_authentication(realm = "Application", message = nil)
+ Token.authentication_request(self, realm, message)
end
end
@@ -435,15 +436,17 @@ module ActionController
end
end
- # Parses the token and options out of the token authorization header. If
- # the header looks like this:
+ # Parses the token and options out of the token authorization header.
+ # The value for the Authorization header is expected to have the prefix
+ # <tt>"Token"</tt> or <tt>"Bearer"</tt>. If the header looks like this:
# Authorization: Token token="abc", nonce="def"
- # Then the returned token is "abc", and the options is {nonce: "def"}
+ # Then the returned token is <tt>"abc"</tt>, and the options are
+ # <tt>{nonce: "def"}</tt>
#
# request - ActionDispatch::Request instance with the current headers.
#
- # Returns an Array of [String, Hash] if a token is present.
- # Returns nil if no token is found.
+ # Returns an +Array+ of <tt>[String, Hash]</tt> if a token is present.
+ # Returns +nil+ if no token is found.
def token_and_options(request)
authorization_request = request.authorization.to_s
if authorization_request[TOKEN_REGEX]
@@ -492,15 +495,16 @@ module ActionController
"Token #{values * ", "}"
end
- # Sets a WWW-Authenticate to let the client know a token is desired.
+ # Sets a WWW-Authenticate header to let the client know a token is desired.
#
# controller - ActionController::Base instance for the outgoing response.
# realm - String realm to use in the header.
#
# Returns nothing.
- def authentication_request(controller, realm)
- controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
- controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
+ def authentication_request(controller, realm, message = nil)
+ message ||= "HTTP Token: Access denied.\n"
+ controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.tr('"'.freeze, "".freeze)}")
+ controller.__send__ :render, plain: message, status: :unauthorized
end
end
end
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
index ae04b53825..17fcc2fa02 100644
--- a/actionpack/lib/action_controller/metal/implicit_render.rb
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -1,13 +1,30 @@
module ActionController
module ImplicitRender
- def send_action(method, *args)
- ret = super
- default_render unless performed?
- ret
- end
+ include BasicImplicitRender
+
+ # Renders the template corresponding to the controller action, if it exists.
+ # The action name, format, and variant are all taken into account.
+ # For example, the "new" action with an HTML format and variant "phone"
+ # would try to render the <tt>new.html+phone.erb</tt> template.
+ #
+ # If no template is found <tt>ActionController::BasicImplicitRender</tt>'s implementation is called, unless
+ # a block is passed. In that case, it will override the super implementation.
+ #
+ # default_render do
+ # head 404 # No template was found
+ # end
def default_render(*args)
- render(*args)
+ if template_exists?(action_name.to_s, _prefixes, variants: request.variant)
+ render(*args)
+ else
+ if block_given?
+ yield(*args)
+ else
+ logger.info "No template found for #{self.class.name}\##{action_name}, rendering head :no_content" if logger
+ super
+ end
+ end
end
def method_for_action(action_name)
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index a3e1a71b0a..3dbf34eb2a 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -11,7 +11,6 @@ module ActionController
extend ActiveSupport::Concern
include AbstractController::Logger
- include ActionController::RackDelegation
attr_internal :view_runtime
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
index 7590fb6843..27b3eb4e58 100644
--- a/actionpack/lib/action_controller/metal/live.rb
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -33,6 +33,21 @@ module ActionController
# the main thread. Make sure your actions are thread safe, and this shouldn't
# be a problem (don't share state across threads, etc).
module Live
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def make_response!(response)
+ request = response.request
+ if request.get_header("HTTP_VERSION") == "HTTP/1.0"
+ super
+ else
+ Live::Response.new.tap do |res|
+ res.request = request
+ end
+ end
+ end
+ end
+
# This class provides the ability to write an SSE (Server Sent Event)
# to an IO stream. The class is initialized with a stream and can be used
# to either write a JSON string or an object which can be converted to JSON.
@@ -102,7 +117,7 @@ module ActionController
end
end
- message = json.gsub(/\n/, "\ndata: ")
+ message = json.gsub("\n".freeze, "\ndata: ".freeze)
@stream.write "data: #{message}\n\n"
end
end
@@ -131,8 +146,8 @@ module ActionController
def write(string)
unless @response.committed?
- @response.headers["Cache-Control"] = "no-cache"
- @response.headers.delete "Content-Length"
+ @response.set_header "Cache-Control", "no-cache"
+ @response.delete_header "Content-Length"
end
super
@@ -199,29 +214,6 @@ module ActionController
end
class Response < ActionDispatch::Response #:nodoc: all
- class Header < DelegateClass(Hash) # :nodoc:
- def initialize(response, header)
- @response = response
- super(header)
- end
-
- def []=(k,v)
- if @response.committed?
- raise ActionDispatch::IllegalStateError, 'header already sent'
- end
-
- super
- end
-
- def merge(other)
- self.class.new @response, __getobj__.merge(other)
- end
-
- def to_hash
- __getobj__.dup
- end
- end
-
private
def before_committed
@@ -242,14 +234,6 @@ module ActionController
body.each { |part| buf.write part }
buf
end
-
- def merge_default_headers(original, default)
- Header.new self, super
- end
-
- def handle_conditional_get!
- super unless committed?
- end
end
def process(name)
@@ -310,13 +294,8 @@ module ActionController
response.close if response
end
- def set_response!(request)
- if request.env["HTTP_VERSION"] == "HTTP/1.0"
- super
- else
- @_response = Live::Response.new
- @_response.request = request
- end
+ def set_response!(response)
+ @_response = self.class.make_response! response
end
end
end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index fab1be3459..6e346fadfe 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -91,11 +91,11 @@ module ActionController #:nodoc:
# and accept Rails' defaults, life will be much easier.
#
# If you need to use a MIME type which isn't supported by default, you can register your own handlers in
- # config/initializers/mime_types.rb as follows.
+ # +config/initializers/mime_types.rb+ as follows.
#
# Mime::Type.register "image/jpg", :jpg
#
- # Respond to also allows you to specify a common block for different formats by using any:
+ # Respond to also allows you to specify a common block for different formats by using +any+:
#
# def index
# @people = Person.all
@@ -151,21 +151,21 @@ module ActionController #:nodoc:
# format.html.none { render "trash" }
# end
#
- # Variants also support common `any`/`all` block that formats have.
+ # Variants also support common +any+/+all+ block that formats have.
#
# It works for both inline:
#
# respond_to do |format|
- # format.html.any { render text: "any" }
- # format.html.phone { render text: "phone" }
+ # format.html.any { render html: "any" }
+ # format.html.phone { render html: "phone" }
# end
#
# and block syntax:
#
# respond_to do |format|
# format.html do |variant|
- # variant.any(:tablet, :phablet){ render text: "any" }
- # variant.phone { render text: "phone" }
+ # variant.any(:tablet, :phablet){ render html: "any" }
+ # variant.phone { render html: "phone" }
# end
# end
#
@@ -174,7 +174,7 @@ module ActionController #:nodoc:
# request.variant = [:tablet, :phone]
#
# which will work similarly to formats and MIME types negotiation. If there will be no
- # :tablet variant declared, :phone variant will be picked:
+ # +:tablet+ variant declared, +:phone+ variant will be picked:
#
# respond_to do |format|
# format.html.none
@@ -191,6 +191,7 @@ module ActionController #:nodoc:
if format = collector.negotiate_format(request)
_process_format(format)
+ _set_rendered_content_type format
response = collector.response
response ? response.call : render({})
else
@@ -228,7 +229,7 @@ module ActionController #:nodoc:
@responses = {}
@variant = variant
- mimes.each { |mime| @responses["Mime::#{mime.upcase}".constantize] = nil }
+ mimes.each { |mime| @responses[Mime[mime]] = nil }
end
def any(*args, &block)
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
index 0a04848eba..c38fc40b81 100644
--- a/actionpack/lib/action_controller/metal/params_wrapper.rb
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -4,18 +4,17 @@ require 'active_support/core_ext/module/anonymous'
require 'action_dispatch/http/mime_type'
module ActionController
- # Wraps the parameters hash into a nested hash. This will allow clients to submit
- # POST requests without having to specify any root elements.
+ # Wraps the parameters hash into a nested hash. This will allow clients to
+ # submit requests without having to specify any root elements.
#
# This functionality is enabled in +config/initializers/wrap_parameters.rb+
- # and can be customized. If you are upgrading to \Rails 3.1, this file will
- # need to be created for the functionality to be enabled.
+ # and can be customized.
#
# You could also turn it on per controller by setting the format array to
# a non-empty array:
#
# class UsersController < ApplicationController
- # wrap_parameters format: [:json, :xml]
+ # wrap_parameters format: [:json, :xml, :url_encoded_form, :multipart_form]
# end
#
# If you enable +ParamsWrapper+ for +:json+ format, instead of having to
@@ -41,7 +40,7 @@ module ActionController
# wrap_parameters :person, include: [:username, :password]
# end
#
- # On ActiveRecord models with no +:include+ or +:exclude+ option set,
+ # On Active Record models with no +:include+ or +:exclude+ option set,
# it will only wrap the parameters returned by the class method
# <tt>attribute_names</tt>.
#
@@ -251,7 +250,7 @@ module ActionController
private
- # Returns the wrapper key which will be used to stored wrapped parameters.
+ # Returns the wrapper key which will be used to store wrapped parameters.
def _wrapper_key
_wrapper_options.name
end
@@ -277,7 +276,9 @@ module ActionController
# Checks if we should perform parameters wrapping.
def _wrapper_enabled?
- ref = request.content_mime_type.try(:ref)
+ return false unless request.has_content_type?
+
+ ref = request.content_mime_type.ref
_wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
end
end
diff --git a/actionpack/lib/action_controller/metal/rack_delegation.rb b/actionpack/lib/action_controller/metal/rack_delegation.rb
deleted file mode 100644
index ae9d89cc8c..0000000000
--- a/actionpack/lib/action_controller/metal/rack_delegation.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-require 'action_dispatch/http/request'
-require 'action_dispatch/http/response'
-
-module ActionController
- module RackDelegation
- extend ActiveSupport::Concern
-
- delegate :headers, :status=, :location=, :content_type=,
- :status, :location, :content_type, :response_code, :to => "@_response"
-
- module ClassMethods
- def build_with_env(env = {}) #:nodoc:
- new.tap { |c| c.set_request! ActionDispatch::Request.new(env) }
- end
- end
-
- def set_request!(request) #:nodoc:
- super
- set_response!(request)
- end
-
- def response_body=(body)
- response.body = body if response
- super
- end
-
- def reset_session
- @_request.reset_session
- end
-
- private
-
- def set_response!(request)
- @_response = ActionDispatch::Response.new
- @_response.request = request
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb
index acaa8227c9..0febc905f1 100644
--- a/actionpack/lib/action_controller/metal/redirecting.rb
+++ b/actionpack/lib/action_controller/metal/redirecting.rb
@@ -11,7 +11,6 @@ module ActionController
extend ActiveSupport::Concern
include AbstractController::Logger
- include ActionController::RackDelegation
include ActionController::UrlFor
# Redirects the browser to the target specified in +options+. This parameter can be any one of:
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index 45d3962494..22e0bb5955 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -68,11 +68,11 @@ module ActionController
# ActionController::Renderers.add :csv do |obj, options|
# filename = options[:filename] || 'data'
# str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
- # send_data str, type: Mime::CSV,
+ # send_data str, type: Mime[:csv],
# disposition: "attachment; filename=#{filename}.csv"
# end
#
- # Note that we used Mime::CSV for the csv mime type as it comes with Rails.
+ # Note that we used Mime[:csv] for the csv mime type as it comes with Rails.
# For a custom renderer, you'll need to register a mime type with
# <tt>Mime::Type.register</tt>.
#
@@ -94,7 +94,7 @@ module ActionController
# This method is the opposite of add method.
#
- # Usage:
+ # To remove a csv renderer:
#
# ActionController::Renderers.remove(:csv)
def self.remove(key)
@@ -116,24 +116,24 @@ module ActionController
json = json.to_json(options) unless json.kind_of?(String)
if options[:callback].present?
- if content_type.nil? || content_type == Mime::JSON
- self.content_type = Mime::JS
+ if content_type.nil? || content_type == Mime[:json]
+ self.content_type = Mime[:js]
end
"/**/#{options[:callback]}(#{json})"
else
- self.content_type ||= Mime::JSON
+ self.content_type ||= Mime[:json]
json
end
end
add :js do |js, options|
- self.content_type ||= Mime::JS
+ self.content_type ||= Mime[:js]
js.respond_to?(:to_js) ? js.to_js(options) : js
end
add :xml do |xml, options|
- self.content_type ||= Mime::XML
+ self.content_type ||= Mime[:xml]
xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
end
end
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 2d15c39d88..cce6fe7787 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/string/filters'
+
module ActionController
module Rendering
extend ActiveSupport::Concern
@@ -8,10 +10,17 @@ module ActionController
# Documentation at ActionController::Renderer#render
delegate :render, to: :renderer
- # Returns a renderer class (inherited from ActionController::Renderer)
+ # Returns a renderer instance (inherited from ActionController::Renderer)
# for the controller.
- def renderer
- @renderer ||= Renderer.for(self)
+ attr_reader :renderer
+
+ def setup_renderer! # :nodoc:
+ @renderer = Renderer.for(self)
+ end
+
+ def inherited(klass)
+ klass.setup_renderer!
+ super
end
end
@@ -53,13 +62,13 @@ module ActionController
nil
end
- def _process_format(format, options = {})
- super
+ def _set_html_content_type
+ self.content_type = Mime[:html].to_s
+ end
- if options[:plain]
- self.content_type = Mime::TEXT
- else
- self.content_type ||= format.to_s
+ def _set_rendered_content_type(format)
+ unless response.content_type
+ self.content_type = format.to_s
end
end
@@ -74,11 +83,23 @@ module ActionController
def _normalize_options(options) #:nodoc:
_normalize_text(options)
+ if options[:text]
+ ActiveSupport::Deprecation.warn <<-WARNING.squish
+ `render :text` is deprecated because it does not actually render a
+ `text/plain` response. Switch to `render plain: 'plain text'` to
+ render as `text/plain`, `render html: '<strong>HTML</strong>'` to
+ render as `text/html`, or `render body: 'raw'` to match the deprecated
+ behavior and render with the default Content-Type, which is
+ `text/plain`.
+ WARNING
+ end
+
if options[:html]
options[:html] = ERB::Util.html_escape(options[:html])
end
if options.delete(:nothing)
+ ActiveSupport::Deprecation.warn("`:nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.")
options[:body] = nil
end
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 367b736035..64f6f7cf51 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -13,9 +13,14 @@ module ActionController #:nodoc:
# by including a token in the rendered HTML for your application. This token is
# stored as a random string in the session, to which an attacker does not have
# access. When a request reaches your application, \Rails verifies the received
- # token with the token in the session. Only HTML and JavaScript requests are checked,
- # so this will not protect your XML API (presumably you'll have a different
- # authentication scheme there anyway).
+ # token with the token in the session. All requests are checked except GET requests
+ # as these should be idempotent. Keep in mind that all session-oriented requests
+ # should be CSRF protected, including JavaScript and HTML requests.
+ #
+ # Since HTML and JavaScript requests are typically made from the browser, we
+ # need to ensure to verify request authenticity for the web browser. We can
+ # use session-oriented authentication for these types of requests, by using
+ # the `protect_from_forgery` method in our controllers.
#
# GET requests are not protected since they don't have side effects like writing
# to the database and don't leak sensitive information. JavaScript requests are
@@ -26,15 +31,21 @@ module ActionController #:nodoc:
# Ajax) requests are allowed to make GET requests for JavaScript responses.
#
# It's important to remember that XML or JSON requests are also affected and if
- # you're building an API you'll need something like:
+ # you're building an API you should change forgery protection method in
+ # <tt>ApplicationController</tt> (by default: <tt>:exception</tt>):
#
# class ApplicationController < ActionController::Base
# protect_from_forgery unless: -> { request.format.json? }
# end
#
- # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
- # which checks the token and resets the session if it doesn't match what was expected.
- # A call to this method is generated for new \Rails applications by default.
+ # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method.
+ # By default <tt>protect_from_forgery</tt> protects your session with
+ # <tt>:null_session</tt> method, which provides an empty session
+ # during request.
+ #
+ # We may want to disable CSRF protection for APIs since they are typically
+ # designed to be state-less. That is, the request API client will handle
+ # the session for you instead of Rails.
#
# The token parameter is named <tt>authenticity_token</tt> by default. The name and
# value of this token must be added to every layout that renders forms by including
@@ -79,17 +90,19 @@ module ActionController #:nodoc:
#
# class FooController < ApplicationController
# protect_from_forgery except: :index
+ # end
#
# You can disable forgery protection on controller by skipping the verification before_action:
+ #
# skip_before_action :verify_authenticity_token
#
# Valid Options:
#
# * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. Like <tt>only: [ :create, :create_all ]</tt>.
- # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed proc or method reference.
+ # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed Proc or method reference.
# * <tt>:prepend</tt> - By default, the verification of the authentication token is added to the front of the
# callback chain. If you need to make the verification depend on other callbacks, like authentication methods
- # (say cookies vs oauth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
+ # (say cookies vs OAuth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
# verification callback in the position of the protect_from_forgery call. This means any callbacks added
# before are run first.
# * <tt>:with</tt> - Set the method to handle unverified request.
@@ -125,17 +138,17 @@ module ActionController #:nodoc:
# This is the method that defines the application behavior when a request is found to be unverified.
def handle_unverified_request
request = @controller.request
- request.session = NullSessionHash.new(request.env)
- request.env['action_dispatch.request.flash_hash'] = nil
- request.env['rack.session.options'] = { skip: true }
- request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
+ request.session = NullSessionHash.new(request)
+ request.flash = nil
+ request.session_options = { skip: true }
+ request.cookie_jar = NullCookieJar.build(request, {})
end
protected
class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
- def initialize(env)
- super(nil, env)
+ def initialize(req)
+ super(nil, req)
@data = {}
@loaded = true
end
@@ -149,14 +162,6 @@ module ActionController #:nodoc:
end
class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
- def self.build(request)
- key_generator = request.env[ActionDispatch::Cookies::GENERATOR_KEY]
- host = request.host
- secure = request.ssl?
-
- new(key_generator, host, secure, options_for_env({}))
- end
-
def write(*)
# nothing
end
@@ -247,7 +252,7 @@ module ActionController #:nodoc:
# Returns true or false if a request is verified. Checks:
#
- # * is it a GET or HEAD request? Gets should be safe and idempotent
+ # * Is it a GET or HEAD request? Gets should be safe and idempotent
# * Does the form_authenticity_token match the given token value from the params?
# * Does the X-CSRF-Token header match the form_authenticity_token
def verified_request?
diff --git a/actionpack/lib/action_controller/metal/rescue.rb b/actionpack/lib/action_controller/metal/rescue.rb
index 68cc9a9c9b..81b9a7b9ed 100644
--- a/actionpack/lib/action_controller/metal/rescue.rb
+++ b/actionpack/lib/action_controller/metal/rescue.rb
@@ -7,10 +7,8 @@ module ActionController #:nodoc:
include ActiveSupport::Rescuable
def rescue_with_handler(exception)
- if (exception.respond_to?(:original_exception) &&
- (orig_exception = exception.original_exception) &&
- handler_for_rescue(orig_exception))
- exception = orig_exception
+ if exception.cause && handler_for_rescue(exception.cause)
+ exception = exception.cause
end
super(exception)
end
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
index 04401cad7b..a6115674aa 100644
--- a/actionpack/lib/action_controller/metal/streaming.rb
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -110,9 +110,9 @@ module ActionController #:nodoc:
# This means that, if you have <code>yield :title</code> in your layout
# and you want to use streaming, you would have to render the whole template
# (and eventually trigger all queries) before streaming the title and all
- # assets, which kills the purpose of streaming. For this reason Rails 3.1
- # introduces a new helper called +provide+ that does the same as +content_for+
- # but tells the layout to stop searching for other entries and continue rendering.
+ # assets, which kills the purpose of streaming. For this purpose, you can use
+ # a helper called +provide+ that does the same as +content_for+ but tells the
+ # layout to stop searching for other entries and continue rendering.
#
# For instance, the template above using +provide+ would be:
#
@@ -199,7 +199,7 @@ module ActionController #:nodoc:
def _process_options(options) #:nodoc:
super
if options[:stream]
- if env["HTTP_VERSION"] == "HTTP/1.0"
+ if request.version == "HTTP/1.0"
options.delete(:stream)
else
headers["Cache-Control"] ||= "no-cache"
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index e30c9c5ade..130ba61786 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -11,9 +11,9 @@ module ActionController
#
# params = ActionController::Parameters.new(a: {})
# params.fetch(:b)
- # # => ActionController::ParameterMissing: param not found: b
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: b
# params.require(:a)
- # # => ActionController::ParameterMissing: param not found: a
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: a
class ParameterMissing < KeyError
attr_reader :param # :nodoc:
@@ -23,11 +23,13 @@ module ActionController
end
end
- # Raised when a supplied parameter is not expected.
+ # Raised when a supplied parameter is not expected and
+ # ActionController::Parameters.action_on_unpermitted_parameters
+ # is set to <tt>:raise</tt>.
#
# params = ActionController::Parameters.new(a: "123", b: "456")
# params.permit(:c)
- # # => ActionController::UnpermittedParameters: found unexpected keys: a, b
+ # # => ActionController::UnpermittedParameters: found unpermitted parameters: a, b
class UnpermittedParameters < IndexError
attr_reader :params # :nodoc:
@@ -95,17 +97,18 @@ module ActionController
# environment they should only be set once at boot-time and never mutated at
# runtime.
#
- # <tt>ActionController::Parameters</tt> inherits from
- # <tt>ActiveSupport::HashWithIndifferentAccess</tt>, this means
- # that you can fetch values using either <tt>:key</tt> or <tt>"key"</tt>.
+ # You can fetch values of <tt>ActionController::Parameters</tt> using either
+ # <tt>:key</tt> or <tt>"key"</tt>.
#
# params = ActionController::Parameters.new(key: 'value')
# params[:key] # => "value"
# params["key"] # => "value"
- class Parameters < ActiveSupport::HashWithIndifferentAccess
+ class Parameters
cattr_accessor :permit_all_parameters, instance_accessor: false
cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
+ delegate :keys, :key?, :has_key?, :empty?, :inspect, to: :@parameters
+
# By default, never raise an UnpermittedParameters exception if these
# params are present. The default includes both 'controller' and 'action'
# because they are added by Rails and should be of no concern. One way
@@ -142,11 +145,22 @@ module ActionController
# params = ActionController::Parameters.new(name: 'Francesco')
# params.permitted? # => true
# Person.new(params) # => #<Person id: nil, name: "Francesco">
- def initialize(attributes = nil)
- super(attributes)
+ def initialize(parameters = {})
+ @parameters = parameters.with_indifferent_access
@permitted = self.class.permit_all_parameters
end
+ # Returns true if another +Parameters+ object contains the same content and
+ # permitted flag, or other Hash-like object contains the same content. This
+ # override is in place so you can perform a comparison with `Hash`.
+ def ==(other_hash)
+ if other_hash.respond_to?(:permitted?)
+ super
+ else
+ @parameters == other_hash
+ end
+ end
+
# Returns a safe +Hash+ representation of this parameter with all
# unpermitted keys removed.
#
@@ -160,7 +174,7 @@ module ActionController
# safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
def to_h
if permitted?
- to_hash
+ @parameters.to_h
else
slice(*self.class.always_permitted_parameters).permit!.to_h
end
@@ -168,20 +182,17 @@ module ActionController
# Returns an unsafe, unfiltered +Hash+ representation of this parameter.
def to_unsafe_h
- to_hash
+ @parameters.to_h
end
alias_method :to_unsafe_hash, :to_unsafe_h
# Convert all hashes in values into parameters, then yield each pair like
# the same way as <tt>Hash#each_pair</tt>
def each_pair(&block)
- super do |key, value|
- convert_hashes_to_parameters(key, value)
+ @parameters.each_pair do |key, value|
+ yield key, convert_hashes_to_parameters(key, value)
end
-
- super
end
-
alias_method :each, :each_pair
# Attribute that keeps track of converted arrays, if any, to avoid double
@@ -228,19 +239,58 @@ module ActionController
self
end
- # Ensures that a parameter is present. If it's present, returns
- # the parameter at the given +key+, otherwise raises an
- # <tt>ActionController::ParameterMissing</tt> error.
+ # This method accepts both a single key and an array of keys.
+ #
+ # When passed a single key, if it exists and its associated value is
+ # either present or the singleton +false+, returns said value:
#
# ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
# # => {"name"=>"Francesco"}
#
+ # Otherwise raises <tt>ActionController::ParameterMissing</tt>:
+ #
+ # ActionController::Parameters.new.require(:person)
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
+ #
# ActionController::Parameters.new(person: nil).require(:person)
- # # => ActionController::ParameterMissing: param not found: person
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
+ #
+ # ActionController::Parameters.new(person: "\t").require(:person)
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
#
# ActionController::Parameters.new(person: {}).require(:person)
- # # => ActionController::ParameterMissing: param not found: person
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
+ #
+ # When given an array of keys, the method tries to require each one of them
+ # in order. If it succeeds, an array with the respective return values is
+ # returned:
+ #
+ # params = ActionController::Parameters.new(user: { ... }, profile: { ... })
+ # user_params, profile_params = params.require(:user, :profile)
+ #
+ # Otherwise, the method reraises the first exception found:
+ #
+ # params = ActionController::Parameters.new(user: {}, profile: {})
+ # user_params, profile_params = params.require(:user, :profile)
+ # # ActionController::ParameterMissing: param is missing or the value is empty: user
+ #
+ # Technically this method can be used to fetch terminal values:
+ #
+ # # CAREFUL
+ # params = ActionController::Parameters.new(person: { name: 'Finn' })
+ # name = params.require(:person).require(:name) # CAREFUL
+ #
+ # but take into account that at some point those ones have to be permitted:
+ #
+ # def person_params
+ # params.require(:person).permit(:name).tap do |person_params|
+ # person_params.require(:name) # SAFER
+ # end
+ # end
+ #
+ # for example.
def require(key)
+ return key.map { |k| require(k) } if key.is_a?(Array)
value = self[key]
if value.present? || value == false
value
@@ -268,7 +318,7 @@ module ActionController
#
# params.permit(:name)
#
- # +:name+ passes it is a key of +params+ whose associated value is of type
+ # +:name+ passes if it is a key of +params+ whose associated value is of type
# +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
# +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
# +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
@@ -345,7 +395,13 @@ module ActionController
# params[:person] # => {"name"=>"Francesco"}
# params[:none] # => nil
def [](key)
- convert_hashes_to_parameters(key, super)
+ convert_hashes_to_parameters(key, @parameters[key])
+ end
+
+ # Assigns a value to a given +key+. The given key may still get filtered out
+ # when +permit+ is called.
+ def []=(key, value)
+ @parameters[key] = value
end
# Returns a parameter for the given +key+. If the +key+
@@ -356,13 +412,19 @@ module ActionController
#
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
# params.fetch(:person) # => {"name"=>"Francesco"}
- # params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
+ # params.fetch(:none) # => ActionController::ParameterMissing: param is missing or the value is empty: none
# params.fetch(:none, 'Francesco') # => "Francesco"
# params.fetch(:none) { 'Francesco' } # => "Francesco"
- def fetch(key, *args)
- convert_hashes_to_parameters(key, super, false)
- rescue KeyError
- raise ActionController::ParameterMissing.new(key)
+ def fetch(key, *args, &block)
+ convert_value_to_parameters(
+ @parameters.fetch(key) {
+ if block_given?
+ yield
+ else
+ args.fetch(0) { raise ActionController::ParameterMissing.new(key) }
+ end
+ }
+ )
end
# Returns a new <tt>ActionController::Parameters</tt> instance that
@@ -373,7 +435,24 @@ module ActionController
# params.slice(:a, :b) # => {"a"=>1, "b"=>2}
# params.slice(:d) # => {}
def slice(*keys)
- new_instance_with_inherited_permitted_status(super)
+ new_instance_with_inherited_permitted_status(@parameters.slice(*keys))
+ end
+
+ # Returns current <tt>ActionController::Parameters</tt> instance which
+ # contains only the given +keys+.
+ def slice!(*keys)
+ @parameters.slice!(*keys)
+ self
+ end
+
+ # Returns a new <tt>ActionController::Parameters</tt> instance that
+ # filters out the given +keys+.
+ #
+ # params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
+ # params.except(:a, :b) # => {"c"=>3}
+ # params.except(:d) # => {"a"=>1,"b"=>2,"c"=>3}
+ def except(*keys)
+ new_instance_with_inherited_permitted_status(@parameters.except(*keys))
end
# Removes and returns the key/value pairs matching the given keys.
@@ -382,7 +461,7 @@ module ActionController
# params.extract!(:a, :b) # => {"a"=>1, "b"=>2}
# params # => {"c"=>3}
def extract!(*keys)
- new_instance_with_inherited_permitted_status(super)
+ new_instance_with_inherited_permitted_status(@parameters.extract!(*keys))
end
# Returns a new <tt>ActionController::Parameters</tt> with the results of
@@ -391,36 +470,80 @@ module ActionController
# params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
# params.transform_values { |x| x * 2 }
# # => {"a"=>2, "b"=>4, "c"=>6}
- def transform_values
- if block_given?
- new_instance_with_inherited_permitted_status(super)
+ def transform_values(&block)
+ if block
+ new_instance_with_inherited_permitted_status(
+ @parameters.transform_values(&block)
+ )
else
- super
+ @parameters.transform_values
end
end
- # This method is here only to make sure that the returned object has the
- # correct +permitted+ status. It should not matter since the parent of
- # this object is +HashWithIndifferentAccess+
- def transform_keys # :nodoc:
- if block_given?
- new_instance_with_inherited_permitted_status(super)
+ # Performs values transformation and returns the altered
+ # <tt>ActionController::Parameters</tt> instance.
+ def transform_values!(&block)
+ @parameters.transform_values!(&block)
+ self
+ end
+
+ # Returns a new <tt>ActionController::Parameters</tt> instance with the
+ # results of running +block+ once for every key. The values are unchanged.
+ def transform_keys(&block)
+ if block
+ new_instance_with_inherited_permitted_status(
+ @parameters.transform_keys(&block)
+ )
else
- super
+ @parameters.transform_keys
end
end
+ # Performs keys transformation and returns the altered
+ # <tt>ActionController::Parameters</tt> instance.
+ def transform_keys!(&block)
+ @parameters.transform_keys!(&block)
+ self
+ end
+
# Deletes and returns a key-value pair from +Parameters+ whose key is equal
# to key. If the key is not found, returns the default value. If the
# optional code block is given and the key is not found, pass in the key
# and return the result of block.
def delete(key, &block)
- convert_hashes_to_parameters(key, super, false)
+ convert_value_to_parameters(@parameters.delete(key))
+ end
+
+ # Returns a new instance of <tt>ActionController::Parameters</tt> with only
+ # items that the block evaluates to true.
+ def select(&block)
+ new_instance_with_inherited_permitted_status(@parameters.select(&block))
end
# Equivalent to Hash#keep_if, but returns nil if no changes were made.
def select!(&block)
- convert_value_to_parameters(super)
+ @parameters.select!(&block)
+ self
+ end
+ alias_method :keep_if, :select!
+
+ # Returns a new instance of <tt>ActionController::Parameters</tt> with items
+ # that the block evaluates to true removed.
+ def reject(&block)
+ new_instance_with_inherited_permitted_status(@parameters.reject(&block))
+ end
+
+ # Removes items that the block evaluates to true and returns self.
+ def reject!(&block)
+ @parameters.reject!(&block)
+ self
+ end
+ alias_method :delete_if, :reject!
+
+ # Returns values that were assigned to the given +keys+. Note that all the
+ # +Hash+ objects will be converted to <tt>ActionController::Parameters</tt>.
+ def values_at(*keys)
+ convert_value_to_parameters(@parameters.values_at(*keys))
end
# Returns an exact copy of the <tt>ActionController::Parameters</tt>
@@ -437,11 +560,30 @@ module ActionController
end
end
+ # Returns a new <tt>ActionController::Parameters</tt> with all keys from
+ # +other_hash+ merges into current hash.
+ def merge(other_hash)
+ new_instance_with_inherited_permitted_status(
+ @parameters.merge(other_hash)
+ )
+ end
+
+ # This is required by ActiveModel attribute assignment, so that user can
+ # pass +Parameters+ to a mass assignment methods in a model. It should not
+ # matter as we are using +HashWithIndifferentAccess+ internally.
+ def stringify_keys # :nodoc:
+ dup
+ end
+
protected
def permitted=(new_permitted)
@permitted = new_permitted
end
+ def fields_for_style?
+ @parameters.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
+ end
+
private
def new_instance_with_inherited_permitted_status(hash)
self.class.new(hash).tap do |new_instance|
@@ -449,40 +591,41 @@ module ActionController
end
end
- def convert_hashes_to_parameters(key, value, assign_if_converted=true)
+ def convert_hashes_to_parameters(key, value)
converted = convert_value_to_parameters(value)
- self[key] = converted if assign_if_converted && !converted.equal?(value)
+ @parameters[key] = converted unless converted.equal?(value)
converted
end
def convert_value_to_parameters(value)
- if value.is_a?(Array) && !converted_arrays.member?(value)
+ case value
+ when Array
+ return value if converted_arrays.member?(value)
converted = value.map { |_| convert_value_to_parameters(_) }
converted_arrays << converted
converted
- elsif value.is_a?(Parameters) || !value.is_a?(Hash)
- value
- else
+ when Hash
self.class.new(value)
+ else
+ value
end
end
def each_element(object)
- if object.is_a?(Array)
- object.map { |el| yield el }.compact
- elsif fields_for_style?(object)
- hash = object.class.new
- object.each { |k,v| hash[k] = yield v }
- hash
- else
- yield object
+ case object
+ when Array
+ object.grep(Parameters).map { |el| yield el }.compact
+ when Parameters
+ if object.fields_for_style?
+ hash = object.class.new
+ object.each { |k,v| hash[k] = yield v }
+ hash
+ else
+ yield object
+ end
end
end
- def fields_for_style?(object)
- object.is_a?(Hash) && object.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
- end
-
def unpermitted_parameters!(params)
unpermitted_keys = unpermitted_keys(params)
if unpermitted_keys.any?
@@ -544,14 +687,8 @@ module ActionController
end
def array_of_permitted_scalars?(value)
- if value.is_a?(Array)
- value.all? {|element| permitted_scalar?(element)}
- end
- end
-
- def array_of_permitted_scalars_filter(params, key)
- if has_key?(key) && array_of_permitted_scalars?(self[key])
- params[key] = self[key]
+ if value.is_a?(Array) && value.all? {|element| permitted_scalar?(element)}
+ yield value
end
end
@@ -562,17 +699,17 @@ module ActionController
# Slicing filters out non-declared keys.
slice(*filter.keys).each do |key, value|
next unless value
+ next unless has_key? key
if filter[key] == EMPTY_ARRAY
# Declaration { comment_ids: [] }.
- array_of_permitted_scalars_filter(params, key)
+ array_of_permitted_scalars?(self[key]) do |val|
+ params[key] = val
+ end
else
# Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
params[key] = each_element(value) do |element|
- if element.is_a?(Hash)
- element = self.class.new(element) unless element.respond_to?(:permit)
- element.permit(*Array.wrap(filter[key]))
- end
+ element.permit(*Array.wrap(filter[key]))
end
end
end
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index d01927b7cb..ac37b00010 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -2,19 +2,8 @@ module ActionController
module Testing
extend ActiveSupport::Concern
- include RackDelegation
-
- # TODO : Rewrite tests using controller.headers= to use Rack env
- def headers=(new_headers)
- @_response ||= ActionDispatch::Response.new
- @_response.headers.replace(new_headers)
- end
-
# Behavior specific to functional tests
module Functional # :nodoc:
- def set_response!(request)
- end
-
def recycle!
@_url_options = nil
self.formats = nil
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index fbaa90d521..dbf7241a14 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -5,9 +5,9 @@ module ActionController
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
# url options like the +host+. In order to do so, this module requires the host class
# to implement +env+ which needs to be Rack-compatible and +request+
- # which is either instance of +ActionDispatch::Request+ or an object
- # that responds to <tt>host</tt>, <tt>optional_port</tt>, <tt>protocol</tt> and
- # <tt>symbolized_path_parameter</tt> methods.
+ # which is either an instance of +ActionDispatch::Request+ or an object
+ # that responds to the +host+, +optional_port+, +protocol+ and
+ # +symbolized_path_parameter+ methods.
#
# class RootUrl
# include ActionController::UrlFor
@@ -41,7 +41,11 @@ module ActionController
if original_script_name
options[:original_script_name] = original_script_name
else
- options[:script_name] = same_origin ? request.script_name.dup : script_name
+ if same_origin
+ options[:script_name] = request.script_name.empty? ? "".freeze : request.script_name.dup
+ else
+ options[:script_name] = script_name
+ end
end
options.freeze
else
diff --git a/actionpack/lib/action_controller/middleware.rb b/actionpack/lib/action_controller/middleware.rb
deleted file mode 100644
index 437fec3dc6..0000000000
--- a/actionpack/lib/action_controller/middleware.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-module ActionController
- class Middleware < Metal
- class ActionMiddleware
- def initialize(controller, app)
- @controller, @app = controller, app
- end
-
- def call(env)
- request = ActionDispatch::Request.new(env)
- @controller.build(@app).dispatch(:index, request)
- end
- end
-
- class << self
- alias build new
-
- def new(app)
- ActionMiddleware.new(self, app)
- end
- end
-
- attr_internal :app
-
- def process(action)
- response = super
- self.status, self.headers, self.response_body = response if response.is_a?(Array)
- response
- end
-
- def initialize(app)
- super()
- @_app = app
- end
-
- def index
- call(env)
- end
- end
-end \ No newline at end of file
diff --git a/actionpack/lib/action_controller/renderer.rb b/actionpack/lib/action_controller/renderer.rb
index e8b29c5b5e..e4d19e9dba 100644
--- a/actionpack/lib/action_controller/renderer.rb
+++ b/actionpack/lib/action_controller/renderer.rb
@@ -34,67 +34,78 @@ module ActionController
# ApplicationController.renderer.new(method: 'post', https: true)
#
class Renderer
- class_attribute :controller, :defaults
- # Rack environment to render templates in.
- attr_reader :env
+ attr_reader :defaults, :controller
- class << self
- delegate :render, to: :new
+ DEFAULTS = {
+ http_host: 'example.org',
+ https: false,
+ method: 'get',
+ script_name: '',
+ input: ''
+ }.freeze
- # Create a new renderer class for a specific controller class.
- def for(controller)
- Class.new self do
- self.controller = controller
- self.defaults = {
- http_host: 'example.org',
- https: false,
- method: 'get',
- script_name: '',
- 'rack.input' => ''
- }
- end
- end
+ # Create a new renderer instance for a specific controller class.
+ def self.for(controller, env = {}, defaults = DEFAULTS)
+ new(controller, env, defaults)
+ end
+
+ # Create a new renderer for the same controller but with a new env.
+ def new(env = {})
+ self.class.new controller, env, defaults
+ end
+
+ # Create a new renderer for the same controller but with new defaults.
+ def with_defaults(defaults)
+ self.class.new controller, env, self.defaults.merge(defaults)
end
# Accepts a custom Rack environment to render templates in.
# It will be merged with ActionController::Renderer.defaults
- def initialize(env = {})
- @env = normalize_keys(defaults).merge normalize_keys(env)
- @env['action_dispatch.routes'] = controller._routes
+ def initialize(controller, env, defaults)
+ @controller = controller
+ @defaults = defaults
+ @env = normalize_keys defaults.merge(env)
end
# Render templates with any options from ActionController::Base#render_to_string.
def render(*args)
- raise 'missing controller' unless controller?
+ raise 'missing controller' unless controller
- instance = controller.build_with_env(env)
+ request = ActionDispatch::Request.new @env
+ request.routes = controller._routes
+
+ instance = controller.new
+ instance.set_request! request
+ instance.set_response! controller.make_response!(request)
instance.render_to_string(*args)
end
private
def normalize_keys(env)
- http_header_format(env).tap do |new_env|
- handle_method_key! new_env
- handle_https_key! new_env
- end
+ new_env = {}
+ env.each_pair { |k,v| new_env[rack_key_for(k)] = rack_value_for(k, v) }
+ new_env
end
- def http_header_format(env)
- env.transform_keys do |key|
- key.is_a?(Symbol) ? key.to_s.upcase : key
- end
- end
+ RACK_KEY_TRANSLATION = {
+ http_host: 'HTTP_HOST',
+ https: 'HTTPS',
+ method: 'REQUEST_METHOD',
+ script_name: 'SCRIPT_NAME',
+ input: 'rack.input'
+ }
- def handle_method_key!(env)
- if method = env.delete('METHOD')
- env['REQUEST_METHOD'] = method.upcase
- end
- end
+ IDENTITY = ->(_) { _ }
+
+ RACK_VALUE_TRANSLATION = {
+ https: ->(v) { v ? 'on' : 'off' },
+ method: ->(v) { v.upcase },
+ }
+
+ def rack_key_for(key); RACK_KEY_TRANSLATION[key]; end
- def handle_https_key!(env)
- if env.has_key? 'HTTPS'
- env['HTTPS'] = env['HTTPS'] ? 'on' : 'off'
- end
+ def rack_value_for(key, value)
+ RACK_VALUE_TRANSLATION.fetch(key, IDENTITY).call value
end
end
end
diff --git a/actionpack/lib/action_controller/template_assertions.rb b/actionpack/lib/action_controller/template_assertions.rb
new file mode 100644
index 0000000000..0179f4afcd
--- /dev/null
+++ b/actionpack/lib/action_controller/template_assertions.rb
@@ -0,0 +1,9 @@
+module ActionController
+ module TemplateAssertions
+ def assert_template(options = {}, message = nil)
+ raise NoMethodError,
+ "assert_template has been extracted to a gem. To continue using it,
+ add `gem 'rails-controller-testing'` to your Gemfile."
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 33c24999f9..442ffd6d7c 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -1,223 +1,57 @@
require 'rack/session/abstract/id'
+require 'active_support/core_ext/hash/conversions'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/module/anonymous'
require 'active_support/core_ext/hash/keys'
-
+require 'action_controller/template_assertions'
require 'rails-dom-testing'
module ActionController
- module TemplateAssertions
- extend ActiveSupport::Concern
+ class TestRequest < ActionDispatch::TestRequest #:nodoc:
+ DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
+ DEFAULT_ENV.delete 'PATH_INFO'
- included do
- setup :setup_subscriptions
- teardown :teardown_subscriptions
+ def self.new_session
+ TestSession.new
end
- RENDER_TEMPLATE_INSTANCE_VARIABLES = %w{partials templates layouts files}.freeze
-
- def setup_subscriptions
- RENDER_TEMPLATE_INSTANCE_VARIABLES.each do |instance_variable|
- instance_variable_set("@_#{instance_variable}", Hash.new(0))
- end
-
- @_subscribers = []
-
- @_subscribers << ActiveSupport::Notifications.subscribe("render_template.action_view") do |_name, _start, _finish, _id, payload|
- path = payload[:layout]
- if path
- @_layouts[path] += 1
- if path =~ /^layouts\/(.*)/
- @_layouts[$1] += 1
- end
- end
- end
-
- @_subscribers << ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
- if virtual_path = payload[:virtual_path]
- partial = virtual_path =~ /^.*\/_[^\/]*$/
-
- if partial
- @_partials[virtual_path] += 1
- @_partials[virtual_path.split("/").last] += 1
- end
-
- @_templates[virtual_path] += 1
- else
- path = payload[:identifier]
- if path
- @_files[path] += 1
- @_files[path.split("/").last] += 1
- end
- end
- end
+ # 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
+ env["rack.request.cookie_hash"] = {}.with_indifferent_access
+ new(default_env.merge(env), new_session)
end
- def teardown_subscriptions
- @_subscribers.each do |subscriber|
- ActiveSupport::Notifications.unsubscribe(subscriber)
- end
+ def self.default_env
+ DEFAULT_ENV
end
+ private_class_method :default_env
- def process(*args)
- reset_template_assertion
- super
- end
+ def initialize(env, session)
+ super(env)
- def reset_template_assertion
- RENDER_TEMPLATE_INSTANCE_VARIABLES.each do |instance_variable|
- ivar_name = "@_#{instance_variable}"
- if instance_variable_defined?(ivar_name)
- instance_variable_get(ivar_name).clear
- end
- end
+ self.session = session
+ self.session_options = TestSession::DEFAULT_OPTIONS
+ @custom_param_parsers = {
+ Mime[:xml] => lambda { |raw_post| Hash.from_xml(raw_post)['hash'] }
+ }
end
- # Asserts that the request was rendered with the appropriate template file or partials.
- #
- # # assert that the "new" view template was rendered
- # assert_template "new"
- #
- # # assert that the exact template "admin/posts/new" was rendered
- # assert_template %r{\Aadmin/posts/new\Z}
- #
- # # assert that the layout 'admin' was rendered
- # assert_template layout: 'admin'
- # assert_template layout: 'layouts/admin'
- # assert_template layout: :admin
- #
- # # assert that no layout was rendered
- # assert_template layout: nil
- # assert_template layout: false
- #
- # # assert that the "_customer" partial was rendered twice
- # assert_template partial: '_customer', count: 2
- #
- # # assert that no partials were rendered
- # assert_template partial: false
- #
- # # assert that a file was rendered
- # assert_template file: "README.rdoc"
- #
- # # assert that no file was rendered
- # assert_template file: nil
- # assert_template file: false
- #
- # In a view test case, you can also assert that specific locals are passed
- # to partials:
- #
- # # assert that the "_customer" partial was rendered with a specific object
- # assert_template partial: '_customer', locals: { customer: @customer }
- def assert_template(options = {}, message = nil)
- # Force body to be read in case the template is being streamed.
- response.body
-
- case options
- when NilClass, Regexp, String, Symbol
- options = options.to_s if Symbol === options
- rendered = @_templates
- msg = message || sprintf("expecting <%s> but rendering with <%s>",
- options.inspect, rendered.keys)
- matches_template =
- case options
- when String
- !options.empty? && rendered.any? do |t, num|
- options_splited = options.split(File::SEPARATOR)
- t_splited = t.split(File::SEPARATOR)
- t_splited.last(options_splited.size) == options_splited
- end
- when Regexp
- rendered.any? { |t,num| t.match(options) }
- when NilClass
- rendered.blank?
- end
- assert matches_template, msg
- when Hash
- options.assert_valid_keys(:layout, :partial, :locals, :count, :file)
-
- if options.key?(:layout)
- expected_layout = options[:layout]
- msg = message || sprintf("expecting layout <%s> but action rendered <%s>",
- expected_layout, @_layouts.keys)
-
- case expected_layout
- when String, Symbol
- assert_includes @_layouts.keys, expected_layout.to_s, msg
- when Regexp
- assert(@_layouts.keys.any? {|l| l =~ expected_layout }, msg)
- when nil, false
- assert(@_layouts.empty?, msg)
- else
- raise ArgumentError, "assert_template only accepts a String, Symbol, Regexp, nil or false for :layout"
- end
- end
-
- if options[:file]
- assert_includes @_files.keys, options[:file]
- elsif options.key?(:file)
- assert @_files.blank?, "expected no files but #{@_files.keys} was rendered"
- end
-
- if expected_partial = options[:partial]
- if expected_locals = options[:locals]
- if defined?(@_rendered_views)
- view = expected_partial.to_s.sub(/^_/, '').sub(/\/_(?=[^\/]+\z)/, '/')
-
- partial_was_not_rendered_msg = "expected %s to be rendered but it was not." % view
- assert_includes @_rendered_views.rendered_views, view, partial_was_not_rendered_msg
-
- msg = 'expecting %s to be rendered with %s but was with %s' % [expected_partial,
- expected_locals,
- @_rendered_views.locals_for(view)]
- assert(@_rendered_views.view_rendered?(view, options[:locals]), msg)
- else
- warn "the :locals option to #assert_template is only supported in a ActionView::TestCase"
- end
- elsif expected_count = options[:count]
- actual_count = @_partials[expected_partial]
- msg = message || sprintf("expecting %s to be rendered %s time(s) but rendered %s time(s)",
- expected_partial, expected_count, actual_count)
- assert(actual_count == expected_count.to_i, msg)
- else
- msg = message || sprintf("expecting partial <%s> but action rendered <%s>",
- options[:partial], @_partials.keys)
- assert_includes @_partials, expected_partial, msg
- end
- elsif options.key?(:partial)
- assert @_partials.empty?,
- "Expected no partials to be rendered"
- end
- else
- raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil"
- end
+ def query_string=(string)
+ set_header Rack::QUERY_STRING, string
end
- end
-
- class TestRequest < ActionDispatch::TestRequest #:nodoc:
- DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
- DEFAULT_ENV.delete 'PATH_INFO'
- def initialize(env = {})
- super
-
- self.session = TestSession.new
- self.session_options = TestSession::DEFAULT_OPTIONS
+ def content_type=(type)
+ set_header 'CONTENT_TYPE', type
end
- def assign_parameters(routes, controller_path, action, parameters = {})
- parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
- extra_keys = routes.extra_keys(parameters)
- non_path_parameters = get? ? query_parameters : request_parameters
- parameters.each do |key, value|
- if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
- value = value.map{ |v| v.duplicable? ? v.dup : v }
- elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
- value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
- elsif value.frozen? && value.duplicable?
- value = value.dup
- end
+ def assign_parameters(routes, controller_path, action, parameters, generated_path, query_string_keys)
+ non_path_parameters = {}
+ path_parameters = {}
- if extra_keys.include?(key)
+ parameters.each do |key, value|
+ if query_string_keys.include?(key)
non_path_parameters[key] = value
else
if value.is_a?(Array)
@@ -230,72 +64,88 @@ module ActionController
end
end
- # Clear the combined params hash in case it was already referenced.
- @env.delete("action_dispatch.request.parameters")
+ if get?
+ if self.query_string.blank?
+ self.query_string = non_path_parameters.to_query
+ end
+ else
+ if ENCODER.should_multipart?(non_path_parameters)
+ self.content_type = ENCODER.content_type
+ data = ENCODER.build_multipart non_path_parameters
+ else
+ fetch_header('CONTENT_TYPE') do |k|
+ set_header k, 'application/x-www-form-urlencoded'
+ end
+
+ case content_mime_type.to_sym
+ when nil
+ raise "Unknown Content-Type: #{content_type}"
+ when :json
+ data = ActiveSupport::JSON.encode(non_path_parameters)
+ when :xml
+ data = non_path_parameters.to_xml
+ when :url_encoded_form
+ data = non_path_parameters.to_query
+ else
+ @custom_param_parsers[content_mime_type] = ->(_) { non_path_parameters }
+ data = non_path_parameters.to_query
+ end
+ end
- # Clear the filter cache variables so they're not stale
- @filtered_parameters = @filtered_env = @filtered_path = nil
+ set_header 'CONTENT_LENGTH', data.length.to_s
+ set_header 'rack.input', StringIO.new(data)
+ end
- params = self.request_parameters.dup
- %w(controller action only_path).each do |k|
- params.delete(k)
- params.delete(k.to_sym)
+ fetch_header("PATH_INFO") do |k|
+ set_header k, generated_path
end
- data = params.to_query
+ path_parameters[:controller] = controller_path
+ path_parameters[:action] = action
- @env['CONTENT_LENGTH'] = data.length.to_s
- @env['rack.input'] = StringIO.new(data)
+ self.path_parameters = path_parameters
end
- def recycle!
- @formats = nil
- @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
- @env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
- @method = @request_method = nil
- @fullpath = @ip = @remote_ip = @protocol = nil
- @env['action_dispatch.request.query_parameters'] = {}
- @set_cookies ||= {}
- @set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
- deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
- @set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
- cookie_jar.update(rack_cookies)
- cookie_jar.update(cookies)
- cookie_jar.update(@set_cookies)
- cookie_jar.recycle!
- end
+ 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
- private
+ public :build_multipart
- def default_env
- DEFAULT_ENV
- end
- end
+ def content_type
+ "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}"
+ end
+ end.new
+
+ private
- class TestResponse < ActionDispatch::TestResponse
- def recycle!
- initialize
+ def params_parsers
+ super.merge @custom_param_parsers
end
end
class LiveTestResponse < Live::Response
- def recycle!
- @body = nil
- initialize
- end
-
- def body
- @body ||= super
- end
-
# Was the response successful?
alias_method :success?, :successful?
# Was the URL not found?
alias_method :missing?, :not_found?
- # Were we redirected?
- alias_method :redirect?, :redirection?
-
# Was there a server-side error?
alias_method :error?, :server_error?
end
@@ -303,7 +153,7 @@ module ActionController
# Methods #destroy and #load! are overridden to avoid calling methods on the
# @store object, which does not exist for the TestSession class.
class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
- DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
+ DEFAULT_OPTIONS = Rack::Session::Abstract::Persisted::DEFAULT_OPTIONS
def initialize(session = {})
super(nil, nil)
@@ -328,6 +178,10 @@ module ActionController
clear
end
+ def fetch(key, *args, &block)
+ @data.fetch(key.to_s, *args, &block)
+ end
+
private
def load!
@@ -354,13 +208,13 @@ module ActionController
# class BooksControllerTest < ActionController::TestCase
# def test_create
# # Simulate a POST response with the given HTTP parameters.
- # post(:create, book: { title: "Love Hina" })
+ # post(:create, params: { book: { title: "Love Hina" }})
#
- # # Assert that the controller tried to redirect us to
+ # # Asserts 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.
+ # # Asserts that the controller really put the book in the database.
# assert_not_nil Book.find_by(title: "Love Hina")
# end
# end
@@ -384,7 +238,7 @@ module ActionController
# 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>::
- # An ActionController::TestResponse object, representing the response
+ # An ActionDispatch::TestResponse object, representing the response
# 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.
@@ -407,21 +261,15 @@ module ActionController
# 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:
#
- # * assigns: Instance variables assigned in the action that are available for the view.
# * session: Objects being saved in the session.
# * flash: The flash objects currently in the session.
# * cookies: \Cookies being sent to the user on this request.
#
# These collections can be used just like any other hash:
#
- # assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
# 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
#
- # For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
- # appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
- # So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
- #
# On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
#
# For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
@@ -512,7 +360,9 @@ module ActionController
# Note that the request method is not verified. The different methods are
# available to make the tests more expressive.
def get(action, *args)
- process_with_kwargs("GET", action, *args)
+ res = process_with_kwargs("GET", action, *args)
+ cookies.update res.cookies
+ res
end
# Simulate a POST request with the given parameters and set/volley the response.
@@ -552,7 +402,7 @@ module ActionController
MSG
@request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
- @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ @request.env['HTTP_ACCEPT'] ||= [Mime[:js], Mime[:html], Mime[:xml], 'text/xml', '*/*'].join(', ')
__send__(*args).tap do
@request.env.delete 'HTTP_X_REQUESTED_WITH'
@request.env.delete 'HTTP_ACCEPT'
@@ -560,19 +410,6 @@ module ActionController
end
alias xhr :xml_http_request
- def paramify_values(hash_or_array_or_value)
- case hash_or_array_or_value
- when Hash
- Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
- when Array
- hash_or_array_or_value.map {|i| paramify_values(i)}
- when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
- hash_or_array_or_value
- else
- hash_or_array_or_value.to_param
- end
- end
-
# Simulate a HTTP request to +action+ by specifying request method,
# parameters and set/volley the response.
#
@@ -604,7 +441,7 @@ module ActionController
def process(action, *args)
check_required_ivars
- if kwarg_request?(*args)
+ if kwarg_request?(args)
parameters, session, body, flash, http_method, format, xhr = args[0].values_at(:params, :session, :body, :flash, :method, :format, :xhr)
else
http_method, parameters, session, flash = args
@@ -621,7 +458,7 @@ module ActionController
end
if body.present?
- @request.env['RAW_POST_DATA'] = body
+ @request.set_header 'RAW_POST_DATA', body
end
if http_method.present?
@@ -632,10 +469,6 @@ module ActionController
parameters ||= {}
- # Ensure that numbers and symbols passed as params are converted to
- # proper params, as is the case when engaging rack.
- parameters = paramify_values(parameters) if html_format?(parameters)
-
if format.present?
parameters[:format] = format
end
@@ -646,45 +479,55 @@ module ActionController
@controller.extend(Testing::Functional)
end
- @request.recycle!
- @response.recycle!
+ self.cookies.update @request.cookies
+ self.cookies.update_cookies_from_jar
+ @request.set_header 'HTTP_COOKIE', cookies.to_header
+ @request.delete_header 'action_dispatch.cookies'
+
+ @request = TestRequest.new scrub_env!(@request.env), @request.session
+ @response = build_response @response_klass
+ @response.request = @request
@controller.recycle!
- @request.env['REQUEST_METHOD'] = http_method
+ @request.set_header 'REQUEST_METHOD', http_method
- controller_class_name = @controller.class.anonymous? ?
- "anonymous" :
- @controller.class.controller_path
+ parameters = parameters.symbolize_keys
- @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
+ 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)
@request.session.update(session) if session
@request.flash.update(flash || {})
if xhr
- @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
- @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ @request.set_header 'HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'
+ @request.fetch_header('HTTP_ACCEPT') do |k|
+ @request.set_header k, [Mime[:js], Mime[:html], Mime[:xml], 'text/xml', '*/*'].join(', ')
+ end
end
- @controller.request = @request
- @controller.response = @response
-
- build_request_uri(action, parameters)
-
- name = @request.parameters[:action]
+ @request.fetch_header("SCRIPT_NAME") do |k|
+ @request.set_header k, @controller.config.relative_url_root
+ end
@controller.recycle!
- @controller.process(name)
+ @controller.dispatch(action, @request, @response)
+ @request = @controller.request
+ @response = @controller.response
- if cookies = @request.env['action_dispatch.cookies']
- unless @response.committed?
- cookies.write(@response)
+ @request.delete_header 'HTTP_COOKIE'
+
+ if @request.have_cookie_jar?
+ unless @request.cookie_jar.committed?
+ @request.cookie_jar.write(@response)
+ self.cookies.update(@request.cookie_jar.instance_variable_get(:@cookies))
end
end
@response.prepare!
- @assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
-
if flash_value = @request.flash.to_session_value
@request.session['flash'] = flash_value
else
@@ -692,21 +535,34 @@ module ActionController
end
if xhr
- @request.env.delete 'HTTP_X_REQUESTED_WITH'
- @request.env.delete 'HTTP_ACCEPT'
+ @request.delete_header 'HTTP_X_REQUESTED_WITH'
+ @request.delete_header 'HTTP_ACCEPT'
end
+ @request.query_string = ''
@response
end
+ 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
+
def setup_controller_request_and_response
@controller = nil unless defined? @controller
- response_klass = TestResponse
+ @response_klass = ActionDispatch::TestResponse
if klass = self.class.controller_class
if klass < ActionController::Live
- response_klass = LiveTestResponse
+ @response_klass = LiveTestResponse
end
unless @controller
begin
@@ -717,8 +573,8 @@ module ActionController
end
end
- @request = build_request
- @response = build_response response_klass
+ @request = TestRequest.create
+ @response = build_response @response_klass
@response.request = @request
if @controller
@@ -727,12 +583,8 @@ module ActionController
end
end
- def build_request
- TestRequest.new
- end
-
def build_response(klass)
- klass.new
+ klass.create
end
included do
@@ -744,12 +596,20 @@ module ActionController
private
+ def scrub_env!(env)
+ env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
+ env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
+ env.delete 'action_dispatch.request.query_parameters'
+ env.delete 'action_dispatch.request.request_parameters'
+ env
+ end
+
def process_with_kwargs(http_method, action, *args)
- if kwarg_request?(*args)
+ if kwarg_request?(args)
args.first.merge!(method: http_method)
process(action, *args)
else
- non_kwarg_request_warning if args.present?
+ non_kwarg_request_warning if args.any?
args = args.unshift(http_method)
process(action, *args)
@@ -757,7 +617,7 @@ module ActionController
end
REQUEST_KWARGS = %i(params session flash method body xhr)
- def kwarg_request?(*args)
+ def kwarg_request?(args)
args[0].respond_to?(:keys) && (
(args[0].key?(:format) && args[0].keys.size == 1) ||
args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
@@ -790,22 +650,6 @@ module ActionController
end
end
- def build_request_uri(action, parameters)
- unless @request.env["PATH_INFO"]
- options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
- options.update(
- :action => action,
- :relative_url_root => nil,
- :_recall => @request.path_parameters)
-
- url, query_string = @routes.path_for(options).split("?", 2)
-
- @request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
- @request.env["PATH_INFO"] = url
- @request.env["QUERY_STRING"] = query_string || ""
- end
- end
-
def html_format?(parameters)
return true unless parameters.key?(:format)
Mime.fetch(parameters[:format]) { Mime['html'] }.html?
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index dcd3ee0644..f6336c8c7a 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -52,6 +52,7 @@ module ActionDispatch
autoload :DebugExceptions
autoload :ExceptionWrapper
autoload :Flash
+ autoload :LoadInterlock
autoload :ParamsParser
autoload :PublicExceptions
autoload :Reloader
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index 747d295261..30ade14c26 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -1,4 +1,3 @@
-
module ActionDispatch
module Http
module Cache
@@ -8,13 +7,13 @@ module ActionDispatch
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
def if_modified_since
- if since = env[HTTP_IF_MODIFIED_SINCE]
+ if since = get_header(HTTP_IF_MODIFIED_SINCE)
Time.rfc2822(since) rescue nil
end
end
def if_none_match
- env[HTTP_IF_NONE_MATCH]
+ get_header HTTP_IF_NONE_MATCH
end
def if_none_match_etags
@@ -51,52 +50,51 @@ module ActionDispatch
end
module Response
- attr_reader :cache_control, :etag
- alias :etag? :etag
+ attr_reader :cache_control
def last_modified
- if last = headers[LAST_MODIFIED]
+ if last = get_header(LAST_MODIFIED)
Time.httpdate(last)
end
end
def last_modified?
- headers.include?(LAST_MODIFIED)
+ has_header? LAST_MODIFIED
end
def last_modified=(utc_time)
- headers[LAST_MODIFIED] = utc_time.httpdate
+ set_header LAST_MODIFIED, utc_time.httpdate
end
def date
- if date_header = headers[DATE]
+ if date_header = get_header(DATE)
Time.httpdate(date_header)
end
end
def date?
- headers.include?(DATE)
+ has_header? DATE
end
def date=(utc_time)
- headers[DATE] = utc_time.httpdate
+ set_header DATE, utc_time.httpdate
end
def etag=(etag)
key = ActiveSupport::Cache.expand_cache_key(etag)
- @etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
+ super %("#{Digest::MD5.hexdigest(key)}")
end
+ def etag?; etag; end
+
private
DATE = 'Date'.freeze
LAST_MODIFIED = "Last-Modified".freeze
- ETAG = "ETag".freeze
- CACHE_CONTROL = "Cache-Control".freeze
SPECIAL_KEYS = Set.new(%w[extras no-cache max-age public must-revalidate])
def cache_control_segments
- if cache_control = self[CACHE_CONTROL]
+ if cache_control = _cache_control
cache_control.delete(' ').split(',')
else
[]
@@ -123,12 +121,11 @@ module ActionDispatch
def prepare_cache_control!
@cache_control = cache_control_headers
- @etag = self[ETAG]
end
def handle_conditional_get!
if etag? || last_modified? || !@cache_control.empty?
- set_conditional_cache_control!
+ set_conditional_cache_control!(@cache_control)
end
end
@@ -138,24 +135,24 @@ module ActionDispatch
PRIVATE = "private".freeze
MUST_REVALIDATE = "must-revalidate".freeze
- def set_conditional_cache_control!
+ def set_conditional_cache_control!(cache_control)
control = {}
cc_headers = cache_control_headers
if extras = cc_headers.delete(:extras)
- @cache_control[:extras] ||= []
- @cache_control[:extras] += extras
- @cache_control[:extras].uniq!
+ cache_control[:extras] ||= []
+ cache_control[:extras] += extras
+ cache_control[:extras].uniq!
end
control.merge! cc_headers
- control.merge! @cache_control
+ control.merge! cache_control
if control.empty?
- headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
+ self._cache_control = DEFAULT_CACHE_CONTROL
elsif control[:no_cache]
- headers[CACHE_CONTROL] = NO_CACHE
+ self._cache_control = NO_CACHE
if control[:extras]
- headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
+ self._cache_control = _cache_control + ", #{control[:extras].join(', ')}"
end
else
extras = control[:extras]
@@ -167,7 +164,7 @@ module ActionDispatch
options << MUST_REVALIDATE if control[:must_revalidate]
options.concat(extras) if extras
- headers[CACHE_CONTROL] = options.join(", ")
+ self._cache_control = options.join(", ")
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb
index 2b851cc28d..9dcab79c3a 100644
--- a/actionpack/lib/action_dispatch/http/filter_parameters.rb
+++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/object/duplicable'
require 'action_dispatch/http/parameter_filter'
module ActionDispatch
@@ -16,7 +14,7 @@ module ActionDispatch
# env["action_dispatch.parameter_filter"] = [:foo, "bar"]
# => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
#
- # env["action_dispatch.parameter_filter"] = lambda do |k,v|
+ # env["action_dispatch.parameter_filter"] = -> (k, v) do
# v.reverse! if k =~ /secret/i
# end
# => reverses the value to all keys matching /secret/i
@@ -25,19 +23,19 @@ module ActionDispatch
NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc:
- def initialize(env)
+ def initialize
super
@filtered_parameters = nil
@filtered_env = nil
@filtered_path = nil
end
- # Return a hash of parameters with all sensitive data replaced.
+ # Returns a hash of parameters with all sensitive data replaced.
def filtered_parameters
@filtered_parameters ||= parameter_filter.filter(parameters)
end
- # Return a hash of request.env with all sensitive data replaced.
+ # Returns a hash of request.env with all sensitive data replaced.
def filtered_env
@filtered_env ||= env_filter.filter(@env)
end
@@ -50,13 +48,13 @@ module ActionDispatch
protected
def parameter_filter
- parameter_filter_for @env.fetch("action_dispatch.parameter_filter") {
+ parameter_filter_for fetch_header("action_dispatch.parameter_filter") {
return NULL_PARAM_FILTER
}
end
def env_filter
- user_key = @env.fetch("action_dispatch.parameter_filter") {
+ user_key = fetch_header("action_dispatch.parameter_filter") {
return NULL_ENV_FILTER
}
parameter_filter_for(Array(user_key) + ENV_MATCH)
diff --git a/actionpack/lib/action_dispatch/http/filter_redirect.rb b/actionpack/lib/action_dispatch/http/filter_redirect.rb
index bf79963351..f4b806b8b5 100644
--- a/actionpack/lib/action_dispatch/http/filter_redirect.rb
+++ b/actionpack/lib/action_dispatch/http/filter_redirect.rb
@@ -5,8 +5,7 @@ module ActionDispatch
FILTERED = '[FILTERED]'.freeze # :nodoc:
def filtered_location # :nodoc:
- filters = location_filter
- if !filters.empty? && location_filter_match?(filters)
+ if location_filter_match?
FILTERED
else
location
@@ -15,20 +14,20 @@ module ActionDispatch
private
- def location_filter
+ def location_filters
if request
- request.env['action_dispatch.redirect_filter'] || []
+ request.get_header('action_dispatch.redirect_filter') || []
else
[]
end
end
- def location_filter_match?(filters)
- filters.any? do |filter|
+ def location_filter_match?
+ location_filters.any? do |filter|
if String === filter
location.include?(filter)
elsif Regexp === filter
- location.match(filter)
+ location =~ filter
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb
index bc5410dc38..12f81dc1a5 100644
--- a/actionpack/lib/action_dispatch/http/headers.rb
+++ b/actionpack/lib/action_dispatch/http/headers.rb
@@ -30,27 +30,37 @@ module ActionDispatch
HTTP_HEADER = /\A[A-Za-z0-9-]+\z/
include Enumerable
- attr_reader :env
- def initialize(env = {}) # :nodoc:
- @env = env
+ def self.from_hash(hash)
+ new ActionDispatch::Request.new hash
+ end
+
+ def initialize(request) # :nodoc:
+ @req = request
end
# Returns the value for the given key mapped to @env.
def [](key)
- @env[env_name(key)]
+ @req.get_header env_name(key)
end
# Sets the given value for the key mapped to @env.
def []=(key, value)
- @env[env_name(key)] = value
+ @req.set_header env_name(key), value
+ end
+
+ # Add a value to a multivalued header like Vary or Accept-Encoding.
+ def add(key, value)
+ @req.add_header env_name(key), value
end
def key?(key)
- @env.key? env_name(key)
+ @req.has_header? env_name(key)
end
alias :include? :key?
+ DEFAULT = Object.new # :nodoc:
+
# Returns the value for the given key mapped to @env.
#
# If the key is not found and an optional code block is not provided,
@@ -58,18 +68,22 @@ module ActionDispatch
#
# If the code block is provided, then it will be run and
# its result returned.
- def fetch(key, *args, &block)
- @env.fetch env_name(key), *args, &block
+ def fetch(key, default = DEFAULT)
+ @req.fetch_header(env_name(key)) do
+ return default unless default == DEFAULT
+ return yield if block_given?
+ raise NameError, key
+ end
end
def each(&block)
- @env.each(&block)
+ @req.each_header(&block)
end
# Returns a new Http::Headers instance containing the contents of
# <tt>headers_or_env</tt> and the original instance.
def merge(headers_or_env)
- headers = Http::Headers.new(env.dup)
+ headers = @req.dup.headers
headers.merge!(headers_or_env)
headers
end
@@ -79,11 +93,14 @@ module ActionDispatch
# <tt>headers_or_env</tt>.
def merge!(headers_or_env)
headers_or_env.each do |key, value|
- self[env_name(key)] = value
+ @req.set_header env_name(key), value
end
end
+ def env; @req.env.dup; end
+
private
+
# Converts a HTTP header name to an environment variable name if it is
# not contained within the headers hash.
def env_name(key)
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index ff336b7354..7acf91902d 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -10,17 +10,18 @@ module ActionDispatch
self.ignore_accept_header = false
end
- # The MIME type of the HTTP request, such as Mime::XML.
+ # The MIME type of the HTTP request, such as Mime[:xml].
#
# For backward compatibility, the post \format is extracted from the
# X-Post-Data-Format HTTP header if present.
def content_mime_type
- @env["action_dispatch.request.content_type"] ||= begin
- if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
+ fetch_header("action_dispatch.request.content_type") do |k|
+ v = if get_header('CONTENT_TYPE') =~ /^([^,\;]*)/
Mime::Type.lookup($1.strip.downcase)
else
nil
end
+ set_header k, v
end
end
@@ -28,46 +29,52 @@ module ActionDispatch
content_mime_type && content_mime_type.to_s
end
+ def has_content_type?
+ has_header? 'CONTENT_TYPE'
+ end
+
# Returns the accepted MIME type for the request.
def accepts
- @env["action_dispatch.request.accepts"] ||= begin
- header = @env['HTTP_ACCEPT'].to_s.strip
+ fetch_header("action_dispatch.request.accepts") do |k|
+ header = get_header('HTTP_ACCEPT').to_s.strip
- if header.empty?
+ v = if header.empty?
[content_mime_type]
else
Mime::Type.parse(header)
end
+ set_header k, v
end
end
# Returns the MIME type for the \format used in the request.
#
- # GET /posts/5.xml | request.format => Mime::XML
- # GET /posts/5.xhtml | request.format => Mime::HTML
- # GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
+ # GET /posts/5.xml | request.format => Mime[:xml]
+ # GET /posts/5.xhtml | request.format => Mime[:html]
+ # GET /posts/5 | request.format => Mime[:html] or Mime[:js], or request.accepts.first
#
def format(view_path = [])
formats.first || Mime::NullType.instance
end
def formats
- @env["action_dispatch.request.formats"] ||= begin
+ fetch_header("action_dispatch.request.formats") do |k|
params_readable = begin
parameters[:format]
rescue ActionController::BadRequest
false
end
- if params_readable
+ v = if params_readable
Array(Mime[parameters[:format]])
elsif use_accept_header && valid_accept_header
accepts
elsif xhr?
- [Mime::JS]
+ [Mime[:js]]
else
- [Mime::HTML]
+ [Mime[:html]]
end
+ set_header k, v
end
end
@@ -102,7 +109,7 @@ module ActionDispatch
# end
def format=(extension)
parameters[:format] = extension.to_s
- @env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
+ set_header "action_dispatch.request.formats", [Mime::Type.lookup_by_extension(parameters[:format])]
end
# Sets the \formats by string extensions. This differs from #format= by allowing you
@@ -121,9 +128,9 @@ module ActionDispatch
# end
def formats=(extensions)
parameters[:format] = extensions.first.to_s
- @env["action_dispatch.request.formats"] = extensions.collect do |extension|
+ set_header "action_dispatch.request.formats", extensions.collect { |extension|
Mime::Type.lookup_by_extension(extension)
- end
+ }
end
# Receives an array of mimes and return the first user sent mime that
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index 7e585aa244..b64f660ec5 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -1,23 +1,31 @@
-require 'set'
require 'singleton'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/string/starts_ends_with'
module Mime
- class Mimes < Array
- def symbols
- @symbols ||= map(&:to_sym)
+ class Mimes
+ include Enumerable
+
+ def initialize
+ @mimes = []
+ @symbols = nil
end
- %w(<< concat shift unshift push pop []= clear compact! collect!
- delete delete_at delete_if flatten! map! insert reject! reverse!
- replace slice! sort! uniq!).each do |method|
- module_eval <<-CODE, __FILE__, __LINE__ + 1
- def #{method}(*)
- @symbols = nil
- super
- end
- CODE
+ def each
+ @mimes.each { |x| yield x }
+ end
+
+ def <<(type)
+ @mimes << type
+ @symbols = nil
+ end
+
+ def delete_if
+ @mimes.delete_if { |x| yield x }.tap { @symbols = nil }
+ end
+
+ def symbols
+ @symbols ||= map(&:to_sym)
end
end
@@ -35,6 +43,42 @@ module Mime
return type if type.is_a?(Type)
EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
end
+
+ def const_missing(sym)
+ ext = sym.downcase
+ if Mime[ext]
+ ActiveSupport::Deprecation.warn <<-eow
+Accessing mime types via constants is deprecated. Please change:
+
+ `Mime::#{sym}`
+
+to:
+
+ `Mime[:#{ext}]`
+ eow
+ Mime[ext]
+ else
+ super
+ end
+ end
+
+ def const_defined?(sym, inherit = true)
+ ext = sym.downcase
+ if Mime[ext]
+ ActiveSupport::Deprecation.warn <<-eow
+Accessing mime types via constants is deprecated. Please change:
+
+ `Mime.const_defined?(#{sym})`
+
+to:
+
+ `Mime[:#{ext}]`
+ eow
+ true
+ else
+ super
+ end
+ end
end
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
@@ -45,15 +89,12 @@ module Mime
#
# respond_to do |format|
# format.html
- # format.ics { render text: @post.to_ics, mime_type: Mime::Type.lookup("text/calendar") }
+ # format.ics { render body: @post.to_ics, mime_type: Mime::Type.lookup("text/calendar") }
# format.xml { render xml: @post }
# end
# end
# end
class Type
- @@html_types = Set.new [:html, :all]
- cattr_reader :html_types
-
attr_reader :symbol
@register_callbacks = []
@@ -66,7 +107,7 @@ module Mime
def initialize(index, name, q = nil)
@index = index
@name = name
- q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list
+ q ||= 0.0 if @name == '*/*'.freeze # default wildcard match to end of list
@q = ((q || 1.0).to_f * 100).to_i
end
@@ -91,7 +132,7 @@ module Mime
exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
delete_at(text_xml_idx) # delete text_xml from the list
elsif text_xml_idx
- text_xml.name = Mime::XML.to_s
+ text_xml.name = Mime[:xml].to_s
end
# Look for more specific XML-based types and sort them ahead of app/xml
@@ -120,7 +161,7 @@ module Mime
end
def app_xml_idx
- @app_xml_idx ||= index(Mime::XML.to_s)
+ @app_xml_idx ||= index(Mime[:xml].to_s)
end
def text_xml
@@ -160,17 +201,17 @@ module Mime
end
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
- Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
+ new_mime = Type.new(string, symbol, mime_type_synonyms)
- new_mime = Mime.const_get(symbol.upcase)
SET << new_mime
- ([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
- ([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
+ ([string] + mime_type_synonyms).each { |str| LOOKUP[str] = new_mime } unless skip_lookup
+ ([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = new_mime }
@register_callbacks.each do |callback|
callback.call(new_mime)
end
+ new_mime
end
def parse(accept_header)
@@ -200,28 +241,27 @@ module Mime
parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP
end
- # For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS,
- # Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>.
+ # For an input of <tt>'text'</tt>, returns <tt>[Mime[:json], Mime[:xml], Mime[:ics],
+ # Mime[:html], Mime[:css], Mime[:csv], Mime[:js], Mime[:yaml], Mime[:text]</tt>.
#
- # For an input of <tt>'application'</tt>, returns <tt>[Mime::HTML, Mime::JS,
- # Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]</tt>.
- def parse_data_with_trailing_star(input)
- Mime::SET.select { |m| m =~ input }
+ # For an input of <tt>'application'</tt>, returns <tt>[Mime[:html], Mime[:js],
+ # Mime[:xml], Mime[:yaml], Mime[:atom], Mime[:json], Mime[:rss], Mime[:url_encoded_form]</tt>.
+ def parse_data_with_trailing_star(type)
+ Mime::SET.select { |m| m =~ type }
end
# This method is opposite of register method.
#
- # Usage:
+ # To unregister a MIME type:
#
# Mime::Type.unregister(:mobile)
def unregister(symbol)
- symbol = symbol.upcase
- mime = Mime.const_get(symbol)
- Mime.instance_eval { remove_const(symbol) }
-
- SET.delete_if { |v| v.eql?(mime) }
- LOOKUP.delete_if { |_,v| v.eql?(mime) }
- EXTENSION_LOOKUP.delete_if { |_,v| v.eql?(mime) }
+ symbol = symbol.downcase
+ if mime = Mime[symbol]
+ SET.delete_if { |v| v.eql?(mime) }
+ LOOKUP.delete_if { |_, v| v.eql?(mime) }
+ EXTENSION_LOOKUP.delete_if { |_, v| v.eql?(mime) }
+ end
end
end
@@ -243,7 +283,7 @@ module Mime
end
def ref
- to_sym || to_s
+ symbol || to_s
end
def ===(list)
@@ -255,24 +295,23 @@ module Mime
end
def ==(mime_type)
- return false if mime_type.blank?
+ return false unless mime_type
(@synonyms + [ self ]).any? do |synonym|
synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
end
end
def =~(mime_type)
- return false if mime_type.blank?
+ return false unless mime_type
regexp = Regexp.new(Regexp.quote(mime_type.to_s))
- (@synonyms + [ self ]).any? do |synonym|
- synonym.to_s =~ regexp
- end
+ @synonyms.any? { |synonym| synonym.to_s =~ regexp } || @string =~ regexp
end
def html?
- @@html_types.include?(to_sym) || @string =~ /html/
+ symbol == :html || @string =~ /html/
end
+ def all?; false; end
private
@@ -292,6 +331,22 @@ module Mime
end
end
+ class AllType < Type
+ include Singleton
+
+ def initialize
+ super '*/*', :all
+ end
+
+ def all?; true; end
+ def html?; true; end
+ end
+
+ # ALL isn't a real MIME type, so we don't register it for lookup with the
+ # other concrete types. It's a wildcard match that we use for `respond_to`
+ # negotiation internals.
+ ALL = AllType.instance
+
class NullType
include Singleton
diff --git a/actionpack/lib/action_dispatch/http/mime_types.rb b/actionpack/lib/action_dispatch/http/mime_types.rb
index 0e4da36038..87715205d9 100644
--- a/actionpack/lib/action_dispatch/http/mime_types.rb
+++ b/actionpack/lib/action_dispatch/http/mime_types.rb
@@ -27,10 +27,7 @@ Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form
# http://www.ietf.org/rfc/rfc4627.txt
# http://www.json.org/JSONRequest.html
-Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
+Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest application/vnd.api+json )
Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
Mime::Type.register "application/zip", :zip, [], %w(zip)
-
-# Create Mime::ALL but do not add it to the SET.
-Mime::ALL = Mime::Type.new("*/*", :all, [])
diff --git a/actionpack/lib/action_dispatch/http/parameter_filter.rb b/actionpack/lib/action_dispatch/http/parameter_filter.rb
index df4b073a17..e826551f4b 100644
--- a/actionpack/lib/action_dispatch/http/parameter_filter.rb
+++ b/actionpack/lib/action_dispatch/http/parameter_filter.rb
@@ -30,36 +30,46 @@ module ActionDispatch
when Regexp
regexps << item
else
- strings << item.to_s
+ strings << Regexp.escape(item.to_s)
end
end
- regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
- new regexps, blocks
+ deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.".freeze) }
+ deep_strings, strings = strings.partition { |s| s.include?("\\.".freeze) }
+
+ regexps << Regexp.new(strings.join('|'.freeze), true) unless strings.empty?
+ deep_regexps << Regexp.new(deep_strings.join('|'.freeze), true) unless deep_strings.empty?
+
+ new regexps, deep_regexps, blocks
end
- attr_reader :regexps, :blocks
+ attr_reader :regexps, :deep_regexps, :blocks
- def initialize(regexps, blocks)
+ def initialize(regexps, deep_regexps, blocks)
@regexps = regexps
+ @deep_regexps = deep_regexps.any? ? deep_regexps : nil
@blocks = blocks
end
- def call(original_params)
+ def call(original_params, parents = [])
filtered_params = {}
original_params.each do |key, value|
+ parents.push(key) if deep_regexps
if regexps.any? { |r| key =~ r }
value = FILTERED
+ elsif deep_regexps && (joined = parents.join('.')) && deep_regexps.any? { |r| joined =~ r }
+ value = FILTERED
elsif value.is_a?(Hash)
- value = call(value)
+ value = call(value, parents)
elsif value.is_a?(Array)
- value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
+ value = value.map { |v| v.is_a?(Hash) ? call(v, parents) : v }
elsif blocks.any?
key = key.dup if key.duplicable?
value = value.dup if value.duplicable?
blocks.each { |b| b.call(key, value) }
end
+ parents.pop if deep_regexps
filtered_params[key] = value
end
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index c2f05ecc86..c9df787351 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -1,27 +1,41 @@
-require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/hash/indifferent_access'
-
module ActionDispatch
module Http
module Parameters
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
+ DEFAULT_PARSERS = {
+ Mime[:json] => lambda { |raw_post|
+ data = ActiveSupport::JSON.decode(raw_post)
+ data.is_a?(Hash) ? data : {:_json => data}
+ }
+ }
+
+ def self.included(klass)
+ class << klass
+ attr_accessor :parameter_parsers
+ end
+
+ klass.parameter_parsers = DEFAULT_PARSERS
+ end
# Returns both GET and POST \parameters in a single hash.
def parameters
- @env["action_dispatch.request.parameters"] ||= begin
- params = begin
- request_parameters.merge(query_parameters)
- rescue EOFError
- query_parameters.dup
- end
- params.merge!(path_parameters)
- end
+ params = get_header("action_dispatch.request.parameters")
+ return params if params
+
+ params = begin
+ request_parameters.merge(query_parameters)
+ rescue EOFError
+ query_parameters.dup
+ end
+ params.merge!(path_parameters)
+ set_header("action_dispatch.request.parameters", params)
+ params
end
alias :params :parameters
def path_parameters=(parameters) #:nodoc:
- @env.delete('action_dispatch.request.parameters')
- @env[PARAMETERS_KEY] = parameters
+ delete_header('action_dispatch.request.parameters')
+ set_header PARAMETERS_KEY, parameters
end
# Returns a hash with the \parameters used to form the \path of the request.
@@ -29,31 +43,29 @@ module ActionDispatch
#
# {'action' => 'my_action', 'controller' => 'my_controller'}
def path_parameters
- @env[PARAMETERS_KEY] ||= {}
+ get_header(PARAMETERS_KEY) || {}
end
- private
+ private
- # Convert nested Hash to HashWithIndifferentAccess.
- #
- def normalize_encode_params(params)
- case params
- when Hash
- if params.has_key?(:tempfile)
- UploadedFile.new(params)
- else
- params.each_with_object({}) do |(key, val), new_hash|
- new_hash[key] = if val.is_a?(Array)
- val.map! { |el| normalize_encode_params(el) }
- else
- normalize_encode_params(val)
- end
- end.with_indifferent_access
- end
- else
- params
+ def parse_formatted_parameters(parsers)
+ return yield if content_length.zero?
+
+ strategy = parsers.fetch(content_mime_type) { return yield }
+
+ begin
+ strategy.call(raw_post)
+ rescue # JSON or Ruby code block errors
+ my_logger = logger || ActiveSupport::Logger.new($stderr)
+ my_logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{raw_post}"
+
+ raise ParamsParser::ParseError
end
end
+
+ def params_parsers
+ ActionDispatch::Request.parameter_parsers
+ end
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index d8419ad804..bd0f38953a 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -13,12 +13,14 @@ require 'action_dispatch/http/url'
require 'active_support/core_ext/array/conversions'
module ActionDispatch
- class Request < Rack::Request
+ class Request
+ include Rack::Request::Helpers
include ActionDispatch::Http::Cache::Request
include ActionDispatch::Http::MimeNegotiation
include ActionDispatch::Http::Parameters
include ActionDispatch::Http::FilterParameters
include ActionDispatch::Http::URL
+ include Rack::Request::Env
autoload :Session, 'action_dispatch/request/session'
autoload :Utils, 'action_dispatch/request/utils'
@@ -29,15 +31,20 @@ module ActionDispatch
PATH_TRANSLATED REMOTE_HOST
REMOTE_IDENT REMOTE_USER REMOTE_ADDR
SERVER_NAME SERVER_PROTOCOL
+ ORIGINAL_SCRIPT_NAME
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
- HTTP_NEGOTIATE HTTP_PRAGMA ].freeze
+ HTTP_NEGOTIATE HTTP_PRAGMA HTTP_CLIENT_IP
+ HTTP_X_FORWARDED_FOR HTTP_VERSION
+ HTTP_X_REQUEST_ID HTTP_X_FORWARDED_HOST
+ SERVER_ADDR
+ ].freeze
ENV_METHODS.each do |env|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
- @env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
+ get_header "#{env}".freeze # get_header "HTTP_ACCEPT_CHARSET".freeze
end # end
METHOD
end
@@ -50,7 +57,6 @@ module ActionDispatch
@original_fullpath = nil
@fullpath = nil
@ip = nil
- @request_id = nil
end
def check_path_parameters!
@@ -59,13 +65,32 @@ module ActionDispatch
path_parameters.each do |key, value|
next unless value.respond_to?(:valid_encoding?)
unless value.valid_encoding?
- raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
+ raise ActionController::BadRequest, "Invalid parameter encoding: #{key} => #{value.inspect}"
end
end
end
+ PASS_NOT_FOUND = Class.new { # :nodoc:
+ def self.action(_); self; end
+ def self.call(_); [404, {'X-Cascade' => 'pass'}, []]; end
+ }
+
+ def controller_class
+ check_path_parameters!
+ params = path_parameters
+
+ if params.key?(:controller)
+ controller_param = params[:controller].underscore
+ params[:action] ||= 'index'
+ const_name = "#{controller_param.camelize}Controller"
+ ActiveSupport::Dependencies.constantize(const_name)
+ else
+ PASS_NOT_FOUND
+ end
+ end
+
def key?(key)
- @env.key?(key)
+ has_header? key
end
# List of HTTP request methods from the following RFCs:
@@ -102,27 +127,50 @@ module ActionDispatch
# the application should use), this \method returns the overridden
# value, not the original.
def request_method
- @request_method ||= check_method(env["REQUEST_METHOD"])
+ @request_method ||= check_method(super)
end
def routes # :nodoc:
- env["action_dispatch.routes".freeze]
+ get_header("action_dispatch.routes".freeze)
end
- def original_script_name # :nodoc:
- env['ORIGINAL_SCRIPT_NAME'.freeze]
+ def routes=(routes) # :nodoc:
+ set_header("action_dispatch.routes".freeze, routes)
end
def engine_script_name(_routes) # :nodoc:
- env[_routes.env_key]
+ get_header(_routes.env_key)
+ end
+
+ def engine_script_name=(name) # :nodoc:
+ set_header(routes.env_key, name.dup)
end
def request_method=(request_method) #:nodoc:
if check_method(request_method)
- @request_method = env["REQUEST_METHOD"] = request_method
+ @request_method = set_header("REQUEST_METHOD", request_method)
end
end
+ def controller_instance # :nodoc:
+ get_header('action_controller.instance'.freeze)
+ end
+
+ def controller_instance=(controller) # :nodoc:
+ set_header('action_controller.instance'.freeze, controller)
+ end
+
+ def http_auth_salt
+ get_header "action_dispatch.http_auth_salt"
+ end
+
+ def show_exceptions? # :nodoc:
+ # We're treating `nil` as "unset", and we want the default setting to be
+ # `true`. This logic should be extracted to `env_config` and calculated
+ # once.
+ !(get_header('action_dispatch.show_exceptions'.freeze) == false)
+ end
+
# Returns a symbol form of the #request_method
def request_method_symbol
HTTP_METHOD_LOOKUP[request_method]
@@ -132,7 +180,7 @@ module ActionDispatch
# even if it was overridden by middleware. See #request_method for
# more information.
def method
- @method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
+ @method ||= check_method(get_header("rack.methodoverride.original_method") || get_header('REQUEST_METHOD'))
end
# Returns a symbol form of the #method
@@ -140,47 +188,11 @@ module ActionDispatch
HTTP_METHOD_LOOKUP[method]
end
- # Is this a GET (or HEAD) request?
- # Equivalent to <tt>request.request_method_symbol == :get</tt>.
- def get?
- HTTP_METHOD_LOOKUP[request_method] == :get
- end
-
- # Is this a POST request?
- # Equivalent to <tt>request.request_method_symbol == :post</tt>.
- def post?
- HTTP_METHOD_LOOKUP[request_method] == :post
- end
-
- # Is this a PATCH request?
- # Equivalent to <tt>request.request_method == :patch</tt>.
- def patch?
- HTTP_METHOD_LOOKUP[request_method] == :patch
- end
-
- # Is this a PUT request?
- # Equivalent to <tt>request.request_method_symbol == :put</tt>.
- def put?
- HTTP_METHOD_LOOKUP[request_method] == :put
- end
-
- # Is this a DELETE request?
- # Equivalent to <tt>request.request_method_symbol == :delete</tt>.
- def delete?
- HTTP_METHOD_LOOKUP[request_method] == :delete
- end
-
- # Is this a HEAD request?
- # Equivalent to <tt>request.request_method_symbol == :head</tt>.
- def head?
- HTTP_METHOD_LOOKUP[request_method] == :head
- end
-
# Provides access to the request's HTTP headers, for example:
#
# request.headers["Content-Type"] # => "text/plain"
def headers
- Http::Headers.new(@env)
+ @headers ||= Http::Headers.new(self)
end
# Returns a +String+ with the last requested path including their params.
@@ -191,7 +203,7 @@ module ActionDispatch
# # get '/foo?bar'
# request.original_fullpath # => '/foo?bar'
def original_fullpath
- @original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)
+ @original_fullpath ||= (get_header("ORIGINAL_FULLPATH") || fullpath)
end
# Returns the +String+ full path including params of the last URL requested.
@@ -230,19 +242,27 @@ module ActionDispatch
# (case-insensitive), which may need to be manually added depending on the
# choice of JavaScript libraries and frameworks.
def xml_http_request?
- @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
+ get_header('HTTP_X_REQUESTED_WITH') =~ /XMLHttpRequest/i
end
alias :xhr? :xml_http_request?
+ # Returns the IP address of client as a +String+.
def ip
@ip ||= super
end
- # Originating IP address, usually set by the RemoteIp middleware.
+ # Returns the IP address of client as a +String+,
+ # usually set by the RemoteIp middleware.
def remote_ip
- @remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
+ @remote_ip ||= (get_header("action_dispatch.remote_ip") || ip).to_s
+ end
+
+ def remote_ip=(remote_ip)
+ set_header "action_dispatch.remote_ip".freeze, remote_ip
end
+ ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id".freeze # :nodoc:
+
# Returns the unique request id, which is based on either the X-Request-Id header that can
# be generated by a firewall, load balancer, or web server or by the RequestId middleware
# (which sets the action_dispatch.request_id environment variable).
@@ -250,35 +270,39 @@ module ActionDispatch
# This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
# This relies on the rack variable set by the ActionDispatch::RequestId middleware.
def request_id
- @request_id ||= env["action_dispatch.request_id"]
+ get_header ACTION_DISPATCH_REQUEST_ID
+ end
+
+ def request_id=(id) # :nodoc:
+ set_header ACTION_DISPATCH_REQUEST_ID, id
end
alias_method :uuid, :request_id
# Returns the lowercase name of the HTTP server software.
def server_software
- (@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
+ (get_header('SERVER_SOFTWARE') && /^([a-zA-Z]+)/ =~ get_header('SERVER_SOFTWARE')) ? $1.downcase : nil
end
# Read the request \body. This is useful for web services that need to
# work with raw requests directly.
def raw_post
- unless @env.include? 'RAW_POST_DATA'
+ unless has_header? 'RAW_POST_DATA'
raw_post_body = body
- @env['RAW_POST_DATA'] = raw_post_body.read(content_length)
+ set_header('RAW_POST_DATA', raw_post_body.read(content_length))
raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
end
- @env['RAW_POST_DATA']
+ get_header 'RAW_POST_DATA'
end
# The request body is an IO input stream. If the RAW_POST_DATA environment
# variable is already set, wrap it in a StringIO.
def body
- if raw_post = @env['RAW_POST_DATA']
+ if raw_post = get_header('RAW_POST_DATA')
raw_post.force_encoding(Encoding::BINARY)
StringIO.new(raw_post)
else
- @env['rack.input']
+ body_stream
end
end
@@ -295,7 +319,7 @@ module ActionDispatch
end
def body_stream #:nodoc:
- @env['rack.input']
+ get_header('rack.input')
end
# TODO This should be broken apart into AD::Request::Session and probably
@@ -306,51 +330,71 @@ module ActionDispatch
else
self.session = {}
end
- @env['action_dispatch.request.flash_hash'] = nil
+ self.flash = nil
end
def session=(session) #:nodoc:
- Session.set @env, session
+ Session.set self, session
end
def session_options=(options)
- Session::Options.set @env, options
+ Session::Options.set self, options
end
# Override Rack's GET method to support indifferent access
def GET
- @env["action_dispatch.request.query_parameters"] ||= Utils.deep_munge(normalize_encode_params(super || {}))
+ fetch_header("action_dispatch.request.query_parameters") do |k|
+ rack_query_params = super || {}
+ # Check for non UTF-8 parameter values, which would cause errors later
+ Request::Utils.check_param_encoding(rack_query_params)
+ set_header k, Request::Utils.normalize_encode_params(rack_query_params)
+ end
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
- raise ActionController::BadRequest.new(:query, e)
+ raise ActionController::BadRequest.new("Invalid query parameters: #{e.message}")
end
alias :query_parameters :GET
# Override Rack's POST method to support indifferent access
def POST
- @env["action_dispatch.request.request_parameters"] ||= Utils.deep_munge(normalize_encode_params(super || {}))
+ fetch_header("action_dispatch.request.request_parameters") do
+ pr = parse_formatted_parameters(params_parsers) do |params|
+ super || {}
+ end
+ self.request_parameters = Request::Utils.normalize_encode_params(pr)
+ end
+ rescue ParamsParser::ParseError # one of the parse strategies blew up
+ self.request_parameters = Request::Utils.normalize_encode_params(super || {})
+ raise
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
- raise ActionController::BadRequest.new(:request, e)
+ raise ActionController::BadRequest.new("Invalid request parameters: #{e.message}")
end
alias :request_parameters :POST
# Returns the authorization header regardless of whether it was specified directly or through one of the
# proxy alternatives.
def authorization
- @env['HTTP_AUTHORIZATION'] ||
- @env['X-HTTP_AUTHORIZATION'] ||
- @env['X_HTTP_AUTHORIZATION'] ||
- @env['REDIRECT_X_HTTP_AUTHORIZATION']
+ get_header('HTTP_AUTHORIZATION') ||
+ get_header('X-HTTP_AUTHORIZATION') ||
+ get_header('X_HTTP_AUTHORIZATION') ||
+ get_header('REDIRECT_X_HTTP_AUTHORIZATION')
end
- # True if the request came from localhost, 127.0.0.1.
+ # True if the request came from localhost, 127.0.0.1, or ::1.
def local?
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
end
- protected
- def parse_query(qs)
- Utils.deep_munge(super)
- end
+ def request_parameters=(params)
+ raise if params.nil?
+ set_header("action_dispatch.request.request_parameters".freeze, params)
+ end
+
+ def logger
+ get_header("action_dispatch.logger".freeze)
+ end
+
+ def commit_flash
+ end
private
def check_method(name)
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index a895d1ab18..f0127aa276 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -32,46 +32,56 @@ module ActionDispatch # :nodoc:
# end
# end
class Response
+ class Header < DelegateClass(Hash) # :nodoc:
+ def initialize(response, header)
+ @response = response
+ super(header)
+ end
+
+ def []=(k,v)
+ if @response.sending? || @response.sent?
+ raise ActionDispatch::IllegalStateError, 'header already sent'
+ end
+
+ super
+ end
+
+ def merge(other)
+ self.class.new @response, __getobj__.merge(other)
+ end
+
+ def to_hash
+ __getobj__.dup
+ end
+ end
+
# The request that the response is responding to.
attr_accessor :request
# The HTTP status code.
attr_reader :status
- attr_writer :sending_file
-
- # Get and set headers for this response.
- attr_accessor :header
+ # Get headers for this response.
+ attr_reader :header
- alias_method :headers=, :header=
alias_method :headers, :header
delegate :[], :[]=, :to => :@header
delegate :each, :to => :@stream
- # Sets the HTTP response's content MIME type. For example, in the controller
- # you could write this:
- #
- # response.content_type = "text/plain"
- #
- # If a character set has been defined for this response (see charset=) then
- # the character set information will also be included in the content type
- # information.
- attr_reader :content_type
-
- # The charset of the response. HTML wants to know the encoding of the
- # content you're giving them, so we need to send that along.
- attr_accessor :charset
-
CONTENT_TYPE = "Content-Type".freeze
SET_COOKIE = "Set-Cookie".freeze
LOCATION = "Location".freeze
- NO_CONTENT_CODES = [204, 304]
+ NO_CONTENT_CODES = [100, 101, 102, 204, 205, 304]
cattr_accessor(:default_charset) { "utf-8" }
cattr_accessor(:default_headers)
include Rack::Response::Helpers
+ # Aliasing these off because AD::Http::Cache::Response defines them
+ alias :_cache_control :cache_control
+ alias :_cache_control= :cache_control=
+
include ActionDispatch::Http::FilterRedirect
include ActionDispatch::Http::Cache::Response
include MonitorMixin
@@ -81,11 +91,21 @@ module ActionDispatch # :nodoc:
@response = response
@buf = buf
@closed = false
+ @str_body = nil
+ end
+
+ def body
+ @str_body ||= begin
+ buf = ''
+ each { |chunk| buf << chunk }
+ buf
+ end
end
def write(string)
raise IOError, "closed stream" if closed?
+ @str_body = nil
@response.commit!
@buf.push string
end
@@ -110,36 +130,40 @@ module ActionDispatch # :nodoc:
end
end
+ def self.create(status = 200, header = {}, body = [], default_headers: self.default_headers)
+ header = merge_default_headers(header, default_headers)
+ new status, header, body
+ end
+
+ def self.merge_default_headers(original, default)
+ default.respond_to?(:merge) ? default.merge(original) : original
+ end
+
# The underlying body, as a streamable object.
attr_reader :stream
- def initialize(status = 200, header = {}, body = [], default_headers: self.class.default_headers)
+ def initialize(status = 200, header = {}, body = [])
super()
- header = merge_default_headers(header, default_headers)
+ @header = Header.new(self, header)
- self.body, self.header, self.status = body, header, status
+ self.body, self.status = body, status
- @sending_file = false
- @blank = false
@cv = new_cond
@committed = false
@sending = false
@sent = false
- @content_type = nil
- @charset = nil
-
- if content_type = self[CONTENT_TYPE]
- type, charset = content_type.split(/;\s*charset=/)
- @content_type = Mime::Type.lookup(type)
- @charset = charset || self.class.default_charset
- end
prepare_cache_control!
yield self if block_given?
end
+ def has_header?(key); headers.key? key; end
+ def get_header(key); headers[key]; end
+ def set_header(key, v); headers[key] = v; end
+ def delete_header(key); headers.delete key; end
+
def await_commit
synchronize do
@cv.wait_until { @committed }
@@ -184,7 +208,49 @@ module ActionDispatch # :nodoc:
# Sets the HTTP content type.
def content_type=(content_type)
- @content_type = content_type.to_s
+ header_info = parse_content_type
+ set_content_type content_type.to_s, header_info.charset || self.class.default_charset
+ end
+
+ # Sets the HTTP response's content MIME type. For example, in the controller
+ # you could write this:
+ #
+ # response.content_type = "text/plain"
+ #
+ # If a character set has been defined for this response (see charset=) then
+ # the character set information will also be included in the content type
+ # information.
+
+ def content_type
+ parse_content_type.mime_type
+ end
+
+ def sending_file=(v)
+ if true == v
+ self.charset = false
+ end
+ end
+
+ # Sets the HTTP character set. In case of nil parameter
+ # it sets the charset to utf-8.
+ #
+ # response.charset = 'utf-16' # => 'utf-16'
+ # response.charset = nil # => 'utf-8'
+ def charset=(charset)
+ header_info = parse_content_type
+ if false == charset
+ set_header CONTENT_TYPE, header_info.mime_type
+ else
+ content_type = header_info.mime_type
+ set_content_type content_type, charset || self.class.default_charset
+ end
+ end
+
+ # The charset of the response. HTML wants to know the encoding of the
+ # content you're giving them, so we need to send that along.
+ def charset
+ header_info = parse_content_type
+ header_info.charset || self.class.default_charset
end
# The response code of the request.
@@ -213,17 +279,15 @@ module ActionDispatch # :nodoc:
# Returns the content of the response as a string. This contains the contents
# of any calls to <tt>render</tt>.
def body
- strings = []
- each { |part| strings << part.to_s }
- strings.join
+ @stream.body
end
- EMPTY = " "
+ def write(string)
+ @stream.write string
+ end
# Allows you to manually set or override the response body.
def body=(body)
- @blank = true if body == EMPTY
-
if body.respond_to?(:to_path)
@stream = body
else
@@ -233,31 +297,49 @@ module ActionDispatch # :nodoc:
end
end
- def body_parts
- parts = []
- @stream.each { |x| parts << x }
- parts
- end
+ # Avoid having to pass an open file handle as the response body.
+ # Rack::Sendfile will usually intercept the response and uses
+ # the path directly, so there is no reason to open the file.
+ class FileBody #:nodoc:
+ attr_reader :to_path
- def set_cookie(key, value)
- ::Rack::Utils.set_cookie_header!(header, key, value)
+ def initialize(path)
+ @to_path = path
+ end
+
+ def body
+ File.binread(to_path)
+ end
+
+ # Stream the file's contents if Rack::Sendfile isn't present.
+ def each
+ File.open(to_path, 'rb') do |file|
+ while chunk = file.read(16384)
+ yield chunk
+ end
+ end
+ end
end
- def delete_cookie(key, value={})
- ::Rack::Utils.delete_cookie_header!(header, key, value)
+ # Send the file stored at +path+ as the response body.
+ def send_file(path)
+ commit!
+ @stream = FileBody.new(path)
end
- # The location header we'll be responding with.
- def location
- headers[LOCATION]
+ def reset_body!
+ @stream = build_buffer(self, [])
end
- alias_method :redirect_url, :location
- # Sets the location header we'll be responding with.
- def location=(url)
- headers[LOCATION] = url
+ def body_parts
+ parts = []
+ @stream.each { |x| parts << x }
+ parts
end
+ # The location header we'll be responding with.
+ alias_method :redirect_url, :location
+
def close
stream.close if stream.respond_to?(:close)
end
@@ -274,10 +356,11 @@ module ActionDispatch # :nodoc:
end
# Turns the Response into a Rack-compatible array of the status, headers,
- # and body. Allows explict splatting:
+ # and body. Allows explicit splatting:
#
# status, headers, body = *response
def to_a
+ commit!
rack_response @status, @header.to_hash
end
alias prepare! to_a
@@ -287,7 +370,7 @@ module ActionDispatch # :nodoc:
# assert_equal 'AuthorOfNewPage', r.cookies['author']
def cookies
cookies = {}
- if header = self[SET_COOKIE]
+ if header = get_header(SET_COOKIE)
header = header.split("\n") if header.respond_to?(:to_str)
header.each do |cookie|
if pair = cookie.split(';').first
@@ -301,14 +384,34 @@ module ActionDispatch # :nodoc:
private
- def before_committed
+ ContentTypeHeader = Struct.new :mime_type, :charset
+ NullContentTypeHeader = ContentTypeHeader.new nil, nil
+
+ def parse_content_type
+ content_type = get_header CONTENT_TYPE
+ if content_type
+ type, charset = content_type.split(/;\s*charset=/)
+ type = nil if type.empty?
+ ContentTypeHeader.new(type, charset)
+ else
+ NullContentTypeHeader
+ end
end
- def before_sending
+ def set_content_type(content_type, charset)
+ type = (content_type || '').dup
+ type << "; charset=#{charset}" if charset
+ set_header CONTENT_TYPE, type
end
- def merge_default_headers(original, default)
- default.respond_to?(:merge) ? default.merge(original) : original
+ def before_committed
+ return if committed?
+ assign_default_content_type_and_charset!
+ handle_conditional_get!
+ handle_no_content!
+ end
+
+ def before_sending
end
def build_buffer(response, body)
@@ -319,20 +422,12 @@ module ActionDispatch # :nodoc:
body.respond_to?(:each) ? body : [body]
end
- def assign_default_content_type_and_charset!(headers)
- return if headers[CONTENT_TYPE].present?
-
- @content_type ||= Mime::HTML
- @charset ||= self.class.default_charset unless @charset == false
+ def assign_default_content_type_and_charset!
+ return if content_type
- type = @content_type.to_s.dup
- type << "; charset=#{@charset}" if append_charset?
-
- headers[CONTENT_TYPE] = type
- end
-
- def append_charset?
- !@sending_file && @charset != false
+ ct = parse_content_type
+ set_content_type(ct.mime_type || Mime[:html].to_s,
+ ct.charset || self.class.default_charset)
end
class RackBody
@@ -371,14 +466,15 @@ module ActionDispatch # :nodoc:
end
end
- def rack_response(status, header)
- assign_default_content_type_and_charset!(header)
- handle_conditional_get!
-
- header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
-
+ def handle_no_content!
if NO_CONTENT_CODES.include?(@status)
- header.delete CONTENT_TYPE
+ @header.delete CONTENT_TYPE
+ @header.delete 'Content-Length'
+ end
+ end
+
+ def rack_response(status, header)
+ if NO_CONTENT_CODES.include?(status)
[status, header, []]
else
[status, header, RackBody.new(self)]
diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb
index 540e11a4a0..a221f4c5af 100644
--- a/actionpack/lib/action_dispatch/http/upload.rb
+++ b/actionpack/lib/action_dispatch/http/upload.rb
@@ -28,7 +28,13 @@ module ActionDispatch
raise(ArgumentError, ':tempfile is required') unless @tempfile
@original_filename = hash[:filename]
- @original_filename &&= @original_filename.encode "UTF-8"
+ if @original_filename
+ begin
+ @original_filename.encode!(Encoding::UTF_8)
+ rescue EncodingError
+ @original_filename.force_encoding(Encoding::UTF_8)
+ end
+ end
@content_type = hash[:type]
@headers = hash[:head]
end
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index f5b709ccd6..92b10b6d3b 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -1,11 +1,10 @@
require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/hash/slice'
module ActionDispatch
module Http
module URL
IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
- HOST_REGEXP = /(^[^:]+:\/\/)?([^:]+)(?::(\d+$))?/
+ HOST_REGEXP = /(^[^:]+:\/\/)?(\[[^\]]+\]|[^:]+)(?::(\d+$))?/
PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
mattr_accessor :tld_length
@@ -184,7 +183,7 @@ module ActionDispatch
end
end
- def initialize(env)
+ def initialize
super
@protocol = nil
@port = nil
@@ -229,10 +228,10 @@ module ActionDispatch
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.raw_host_with_port # => "example.com:8080"
def raw_host_with_port
- if forwarded = env["HTTP_X_FORWARDED_HOST"].presence
+ if forwarded = x_forwarded_host.presence
forwarded.split(/,\s?/).last
else
- env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
+ get_header('HTTP_HOST') || "#{server_name || server_addr}:#{get_header('SERVER_PORT')}"
end
end
@@ -245,7 +244,7 @@ module ActionDispatch
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.host # => "example.com"
def host
- raw_host_with_port.sub(/:\d+$/, '')
+ raw_host_with_port.sub(/:\d+$/, ''.freeze)
end
# Returns a \host:\port string for this request, such as "example.com" or
@@ -348,7 +347,7 @@ module ActionDispatch
end
def server_port
- @env['SERVER_PORT'].to_i
+ get_header('SERVER_PORT').to_i
end
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index 992c1a9efe..0323360faa 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -14,7 +14,7 @@ module ActionDispatch
def generate(name, options, path_parameters, parameterize = nil)
constraints = path_parameters.merge(options)
- missing_keys = []
+ missing_keys = nil # need for variable scope
match_route(name, constraints) do |route|
parameterized_parts = extract_parameterized_parts(route, options, path_parameters, parameterize)
@@ -25,22 +25,22 @@ module ActionDispatch
next unless name || route.dispatcher?
missing_keys = missing_keys(route, parameterized_parts)
- next unless missing_keys.empty?
+ next if missing_keys && !missing_keys.empty?
params = options.dup.delete_if do |key, _|
parameterized_parts.key?(key) || route.defaults.key?(key)
end
defaults = route.defaults
required_parts = route.required_parts
- parameterized_parts.delete_if do |key, value|
- value.to_s == defaults[key].to_s && !required_parts.include?(key)
+ parameterized_parts.keep_if do |key, value|
+ (defaults[key].nil? && value.present?) || value.to_s != defaults[key].to_s || required_parts.include?(key)
end
return [route.format(parameterized_parts), params]
end
- message = "No route matches #{Hash[constraints.sort].inspect}"
- message << " missing required keys: #{missing_keys.sort.inspect}" unless missing_keys.empty?
+ message = "No route matches #{Hash[constraints.sort_by{|k,v| k.to_s}].inspect}"
+ message << " missing required keys: #{missing_keys.sort.inspect}" if missing_keys && !missing_keys.empty?
raise ActionController::UrlGenerationError, message
end
@@ -54,12 +54,12 @@ module ActionDispatch
def extract_parameterized_parts(route, options, recall, parameterize = nil)
parameterized_parts = recall.merge(options)
- keys_to_keep = route.parts.reverse.drop_while { |part|
+ keys_to_keep = route.parts.reverse_each.drop_while { |part|
!options.key?(part) || (options[part] || recall[part]).nil?
} | route.required_parts
- (parameterized_parts.keys - keys_to_keep).each do |bad_key|
- parameterized_parts.delete(bad_key)
+ parameterized_parts.delete_if do |bad_key, _|
+ !keys_to_keep.include?(bad_key)
end
if parameterize
@@ -110,15 +110,36 @@ module ActionDispatch
routes
end
+ module RegexCaseComparator
+ DEFAULT_INPUT = /[-_.a-zA-Z0-9]+\/[-_.a-zA-Z0-9]+/
+ DEFAULT_REGEX = /\A#{DEFAULT_INPUT}\Z/
+
+ def self.===(regex)
+ DEFAULT_INPUT == regex
+ end
+ end
+
# Returns an array populated with missing keys if any are present.
def missing_keys(route, parts)
- missing_keys = []
+ missing_keys = nil
tests = route.path.requirements
route.required_parts.each { |key|
- if tests.key?(key)
- missing_keys << key unless /\A#{tests[key]}\Z/ === parts[key]
+ case tests[key]
+ when nil
+ unless parts[key]
+ missing_keys ||= []
+ missing_keys << key
+ end
+ when RegexCaseComparator
+ unless RegexCaseComparator::DEFAULT_REGEX === parts[key]
+ missing_keys ||= []
+ missing_keys << key
+ end
else
- missing_keys << key unless parts[key]
+ unless /\A#{tests[key]}\Z/ === parts[key]
+ missing_keys ||= []
+ missing_keys << key
+ end
end
}
missing_keys
@@ -134,7 +155,7 @@ module ActionDispatch
def build_cache
root = { ___routes: [] }
- routes.each_with_index do |route, i|
+ routes.routes.each_with_index do |route, i|
leaf = route.required_defaults.inject(root) do |h, tuple|
h[tuple] ||= {}
end
diff --git a/actionpack/lib/action_dispatch/journey/nfa/dot.rb b/actionpack/lib/action_dispatch/journey/nfa/dot.rb
index 47bf76bdbf..7063b44bb5 100644
--- a/actionpack/lib/action_dispatch/journey/nfa/dot.rb
+++ b/actionpack/lib/action_dispatch/journey/nfa/dot.rb
@@ -1,5 +1,3 @@
-# encoding: utf-8
-
module ActionDispatch
module Journey # :nodoc:
module NFA # :nodoc:
diff --git a/actionpack/lib/action_dispatch/journey/nodes/node.rb b/actionpack/lib/action_dispatch/journey/nodes/node.rb
index bb01c087bc..2793c5668d 100644
--- a/actionpack/lib/action_dispatch/journey/nodes/node.rb
+++ b/actionpack/lib/action_dispatch/journey/nodes/node.rb
@@ -14,15 +14,15 @@ module ActionDispatch
end
def each(&block)
- Visitors::Each.new(block).accept(self)
+ Visitors::Each::INSTANCE.accept(self, block)
end
def to_s
- Visitors::String.new.accept(self)
+ Visitors::String::INSTANCE.accept(self, '')
end
def to_dot
- Visitors::Dot.new.accept(self)
+ Visitors::Dot::INSTANCE.accept(self)
end
def to_sym
@@ -30,7 +30,7 @@ module ActionDispatch
end
def name
- left.tr '*:', ''
+ left.tr '*:'.freeze, ''.freeze
end
def type
@@ -39,10 +39,15 @@ module ActionDispatch
def symbol?; false; end
def literal?; false; end
+ def terminal?; false; end
+ def star?; false; end
+ def cat?; false; end
+ def group?; false; end
end
class Terminal < Node # :nodoc:
alias :symbol :left
+ def terminal?; true; end
end
class Literal < Terminal # :nodoc:
@@ -69,11 +74,13 @@ module ActionDispatch
class Symbol < Terminal # :nodoc:
attr_accessor :regexp
alias :symbol :regexp
+ attr_reader :name
DEFAULT_EXP = /[^\.\/\?]+/
def initialize(left)
super
@regexp = DEFAULT_EXP
+ @name = left.tr '*:'.freeze, ''.freeze
end
def default_regexp?
@@ -89,9 +96,11 @@ module ActionDispatch
class Group < Unary # :nodoc:
def type; :GROUP; end
+ def group?; true; end
end
class Star < Unary # :nodoc:
+ def star?; true; end
def type; :STAR; end
def name
@@ -111,6 +120,7 @@ module ActionDispatch
end
class Cat < Binary # :nodoc:
+ def cat?; true; end
def type; :CAT; end
end
diff --git a/actionpack/lib/action_dispatch/journey/parser_extras.rb b/actionpack/lib/action_dispatch/journey/parser_extras.rb
index 14892f4321..fff0299812 100644
--- a/actionpack/lib/action_dispatch/journey/parser_extras.rb
+++ b/actionpack/lib/action_dispatch/journey/parser_extras.rb
@@ -6,6 +6,10 @@ module ActionDispatch
class Parser < Racc::Parser # :nodoc:
include Journey::Nodes
+ def self.parse(string)
+ new.parse string
+ end
+
def initialize
@scanner = Scanner.new
end
diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb
index 64b48ca45f..5ee8810066 100644
--- a/actionpack/lib/action_dispatch/journey/path/pattern.rb
+++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb
@@ -1,5 +1,3 @@
-require 'action_dispatch/journey/router/strexp'
-
module ActionDispatch
module Journey # :nodoc:
module Path # :nodoc:
@@ -7,14 +5,20 @@ module ActionDispatch
attr_reader :spec, :requirements, :anchored
def self.from_string string
- new Journey::Router::Strexp.build(string, {}, ["/.?"], true)
+ build(string, {}, "/.?", true)
+ end
+
+ def self.build(path, requirements, separators, anchored)
+ parser = Journey::Parser.new
+ ast = parser.parse path
+ new ast, requirements, separators, anchored
end
- def initialize(strexp)
- @spec = strexp.ast
- @requirements = strexp.requirements
- @separators = strexp.separators.join
- @anchored = strexp.anchor
+ def initialize(ast, requirements, separators, anchored)
+ @spec = ast
+ @requirements = requirements
+ @separators = separators
+ @anchored = anchored
@names = nil
@optional_names = nil
@@ -28,12 +32,12 @@ module ActionDispatch
end
def ast
- @spec.grep(Nodes::Symbol).each do |node|
+ @spec.find_all(&:symbol?).each do |node|
re = @requirements[node.to_sym]
node.regexp = re if re
end
- @spec.grep(Nodes::Star).each do |node|
+ @spec.find_all(&:star?).each do |node|
node = node.left
node.regexp = @requirements[node.to_sym] || /(.+)/
end
@@ -42,7 +46,7 @@ module ActionDispatch
end
def names
- @names ||= spec.grep(Nodes::Symbol).map(&:name)
+ @names ||= spec.find_all(&:symbol?).map(&:name)
end
def required_names
@@ -50,36 +54,11 @@ module ActionDispatch
end
def optional_names
- @optional_names ||= spec.grep(Nodes::Group).flat_map { |group|
- group.grep(Nodes::Symbol)
+ @optional_names ||= spec.find_all(&:group?).flat_map { |group|
+ group.find_all(&:symbol?)
}.map(&:name).uniq
end
- class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
- attr_reader :offsets
-
- def initialize(matchers)
- @matchers = matchers
- @capture_count = [0]
- end
-
- def visit(node)
- super
- @capture_count
- end
-
- def visit_SYMBOL(node)
- node = node.to_sym
-
- if @matchers.key?(node)
- re = /#{@matchers[node]}|/
- @capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
- else
- @capture_count << (@capture_count.last || 0)
- end
- end
- end
-
class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
def initialize(separator, matchers)
@separator = separator
@@ -189,8 +168,20 @@ module ActionDispatch
def offsets
return @offsets if @offsets
- viz = RegexpOffsets.new(@requirements)
- @offsets = viz.accept(spec)
+ @offsets = [0]
+
+ spec.find_all(&:symbol?).each do |node|
+ node = node.to_sym
+
+ if @requirements.key?(node)
+ re = /#{@requirements[node]}|/
+ @offsets.push((re.match('').length - 1) + @offsets.last)
+ else
+ @offsets << @offsets.last
+ end
+ end
+
+ @offsets
end
end
end
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
index 4d5c18984a..35c2b1b86e 100644
--- a/actionpack/lib/action_dispatch/journey/route.rb
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -1,42 +1,88 @@
module ActionDispatch
module Journey # :nodoc:
class Route # :nodoc:
- attr_reader :app, :path, :defaults, :name
+ attr_reader :app, :path, :defaults, :name, :precedence
attr_reader :constraints
alias :conditions :constraints
- attr_accessor :precedence
+ module VerbMatchers
+ VERBS = %w{ DELETE GET HEAD OPTIONS LINK PATCH POST PUT TRACE UNLINK }
+ VERBS.each do |v|
+ class_eval <<-eoc
+ class #{v}
+ def self.verb; name.split("::").last; end
+ def self.call(req); req.#{v.downcase}?; end
+ end
+ eoc
+ end
+
+ class Unknown
+ attr_reader :verb
+
+ def initialize(verb)
+ @verb = verb
+ end
+
+ def call(request); @verb === request.request_method; end
+ end
+
+ class All
+ def self.call(_); true; end
+ def self.verb; ''; end
+ end
+
+ VERB_TO_CLASS = VERBS.each_with_object({ :all => All }) do |verb, hash|
+ klass = const_get verb
+ hash[verb] = klass
+ hash[verb.downcase] = klass
+ hash[verb.downcase.to_sym] = klass
+ end
+
+ end
+
+ def self.verb_matcher(verb)
+ VerbMatchers::VERB_TO_CLASS.fetch(verb) do
+ VerbMatchers::Unknown.new verb.to_s.dasherize.upcase
+ end
+ end
+
+ def self.build(name, app, path, constraints, required_defaults, defaults)
+ request_method_match = verb_matcher(constraints.delete(:request_method))
+ new name, app, path, constraints, required_defaults, defaults, request_method_match, 0
+ end
##
# +path+ is a path constraint.
# +constraints+ is a hash of constraints to be applied to this route.
- def initialize(name, app, path, constraints, defaults = {})
+ def initialize(name, app, path, constraints, required_defaults, defaults, request_method_match, precedence)
@name = name
@app = app
@path = path
+ @request_method_match = request_method_match
@constraints = constraints
@defaults = defaults
@required_defaults = nil
+ @_required_defaults = required_defaults
@required_parts = nil
@parts = nil
@decorated_ast = nil
- @precedence = 0
+ @precedence = precedence
@path_formatter = @path.build_formatter
end
def ast
@decorated_ast ||= begin
decorated_ast = path.ast
- decorated_ast.grep(Nodes::Terminal).each { |n| n.memo = self }
+ decorated_ast.find_all(&:terminal?).each { |n| n.memo = self }
decorated_ast
end
end
def requirements # :nodoc:
# needed for rails `rake routes`
- path.requirements.merge(@defaults).delete_if { |_,v|
+ @defaults.merge(path.requirements).delete_if { |_,v|
/.+?/ == v
}
end
@@ -73,7 +119,7 @@ module ActionDispatch
end
def required_default?(key)
- (constraints[:required_defaults] || []).include?(key)
+ @_required_defaults.include?(key)
end
def required_defaults
@@ -91,9 +137,8 @@ module ActionDispatch
end
def matches?(request)
- constraints.all? do |method, value|
- next true unless request.respond_to?(method)
-
+ match_verb(request) &&
+ constraints.all? { |method, value|
case value
when Regexp, String
value === request.send(method).to_s
@@ -106,15 +151,28 @@ module ActionDispatch
else
value === request.send(method)
end
- end
+ }
end
def ip
constraints[:ip] || //
end
+ def requires_matching_verb?
+ !@request_method_match.all? { |x| x == VerbMatchers::All }
+ end
+
def verb
- constraints[:request_method] || //
+ verbs.join('|')
+ end
+
+ private
+ def verbs
+ @request_method_match.map(&:verb)
+ end
+
+ def match_verb(request)
+ @request_method_match.any? { |m| m.call request }
end
end
end
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
index cc4bd6105d..f649588520 100644
--- a/actionpack/lib/action_dispatch/journey/router.rb
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -1,5 +1,4 @@
require 'action_dispatch/journey/router/utils'
-require 'action_dispatch/journey/router/strexp'
require 'action_dispatch/journey/routes'
require 'action_dispatch/journey/formatter'
@@ -102,7 +101,7 @@ module ActionDispatch
}
routes =
- if req.request_method == "HEAD"
+ if req.head?
match_head_routes(routes, req)
else
match_routes(routes, req)
@@ -121,7 +120,8 @@ module ActionDispatch
end
def match_head_routes(routes, req)
- head_routes = match_routes(routes, req)
+ verb_specific_routes = routes.select(&:requires_matching_verb?)
+ head_routes = match_routes(verb_specific_routes, req)
if head_routes.empty?
begin
diff --git a/actionpack/lib/action_dispatch/journey/router/strexp.rb b/actionpack/lib/action_dispatch/journey/router/strexp.rb
deleted file mode 100644
index 4b7738f335..0000000000
--- a/actionpack/lib/action_dispatch/journey/router/strexp.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-module ActionDispatch
- module Journey # :nodoc:
- class Router # :nodoc:
- class Strexp # :nodoc:
- class << self
- alias :compile :new
- end
-
- attr_reader :path, :requirements, :separators, :anchor, :ast
-
- def self.build(path, requirements, separators, anchor = true)
- parser = Journey::Parser.new
- ast = parser.parse path
- new ast, path, requirements, separators, anchor
- end
-
- def initialize(ast, path, requirements, separators, anchor = true)
- @ast = ast
- @path = path
- @requirements = requirements
- @separators = separators
- @anchor = anchor
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/journey/router/utils.rb b/actionpack/lib/action_dispatch/journey/router/utils.rb
index 2b0a6575d4..9793ca1c7a 100644
--- a/actionpack/lib/action_dispatch/journey/router/utils.rb
+++ b/actionpack/lib/action_dispatch/journey/router/utils.rb
@@ -14,10 +14,10 @@ module ActionDispatch
# normalize_path("/%ab") # => "/%AB"
def self.normalize_path(path)
path = "/#{path}"
- path.squeeze!('/')
- path.sub!(%r{/+\Z}, '')
+ path.squeeze!('/'.freeze)
+ path.sub!(%r{/+\Z}, ''.freeze)
path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
- path = '/' if path == ''
+ path = '/' if path == ''.freeze
path
end
@@ -55,7 +55,7 @@ module ActionDispatch
def unescape_uri(uri)
encoding = uri.encoding == US_ASCII ? UTF_8 : uri.encoding
- uri.gsub(ESCAPED) { [$&[1, 2].hex].pack('C') }.force_encoding(encoding)
+ uri.gsub(ESCAPED) { |match| [match[1, 2].hex].pack('C') }.force_encoding(encoding)
end
protected
diff --git a/actionpack/lib/action_dispatch/journey/routes.rb b/actionpack/lib/action_dispatch/journey/routes.rb
index a6d1980db2..f7b009109e 100644
--- a/actionpack/lib/action_dispatch/journey/routes.rb
+++ b/actionpack/lib/action_dispatch/journey/routes.rb
@@ -5,17 +5,20 @@ module ActionDispatch
class Routes # :nodoc:
include Enumerable
- attr_reader :routes, :named_routes, :custom_routes, :anchored_routes
+ attr_reader :routes, :custom_routes, :anchored_routes
def initialize
@routes = []
- @named_routes = {}
@ast = nil
@anchored_routes = []
@custom_routes = []
@simulator = nil
end
+ def empty?
+ routes.empty?
+ end
+
def length
routes.length
end
@@ -33,7 +36,6 @@ module ActionDispatch
routes.clear
anchored_routes.clear
custom_routes.clear
- named_routes.clear
end
def partition_route(route)
@@ -58,13 +60,9 @@ module ActionDispatch
end
end
- # Add a route to the routing table.
- def add_route(app, path, conditions, defaults, name = nil)
- route = Route.new(name, app, path, conditions, defaults)
-
- route.precedence = routes.length
+ def add_route(name, mapping)
+ route = mapping.make_route name, routes.length
routes << route
- named_routes[name] = route if name && !named_routes[name]
partition_route(route)
clear_cache!
route
diff --git a/actionpack/lib/action_dispatch/journey/visitors.rb b/actionpack/lib/action_dispatch/journey/visitors.rb
index 52b4c8b489..306d2e674a 100644
--- a/actionpack/lib/action_dispatch/journey/visitors.rb
+++ b/actionpack/lib/action_dispatch/journey/visitors.rb
@@ -1,5 +1,3 @@
-# encoding: utf-8
-
module ActionDispatch
module Journey # :nodoc:
class Format
@@ -92,6 +90,45 @@ module ActionDispatch
end
end
+ class FunctionalVisitor # :nodoc:
+ DISPATCH_CACHE = {}
+
+ def accept(node, seed)
+ visit(node, seed)
+ end
+
+ def visit node, seed
+ send(DISPATCH_CACHE[node.type], node, seed)
+ end
+
+ def binary(node, seed)
+ visit(node.right, visit(node.left, seed))
+ end
+ def visit_CAT(n, seed); binary(n, seed); end
+
+ def nary(node, seed)
+ node.children.inject(seed) { |s, c| visit(c, s) }
+ end
+ def visit_OR(n, seed); nary(n, seed); end
+
+ def unary(node, seed)
+ visit(node.left, seed)
+ end
+ def visit_GROUP(n, seed); unary(n, seed); end
+ def visit_STAR(n, seed); unary(n, seed); end
+
+ def terminal(node, seed); seed; end
+ def visit_LITERAL(n, seed); terminal(n, seed); end
+ def visit_SYMBOL(n, seed); terminal(n, seed); end
+ def visit_SLASH(n, seed); terminal(n, seed); end
+ def visit_DOT(n, seed); terminal(n, seed); end
+
+ instance_methods(false).each do |pim|
+ next unless pim =~ /^visit_(.*)$/
+ DISPATCH_CACHE[$1.to_sym] = pim
+ end
+ end
+
class FormatBuilder < Visitor # :nodoc:
def accept(node); Journey::Format.new(super); end
def terminal(node); [node.left]; end
@@ -117,104 +154,110 @@ module ActionDispatch
end
# Loop through the requirements AST
- class Each < Visitor # :nodoc:
- attr_reader :block
-
- def initialize(block)
- @block = block
- end
-
- def visit(node)
+ class Each < FunctionalVisitor # :nodoc:
+ def visit(node, block)
block.call(node)
super
end
+
+ INSTANCE = new
end
- class String < Visitor # :nodoc:
+ class String < FunctionalVisitor # :nodoc:
private
- def binary(node)
- [visit(node.left), visit(node.right)].join
+ def binary(node, seed)
+ visit(node.right, visit(node.left, seed))
end
- def nary(node)
- node.children.map { |c| visit(c) }.join '|'
+ def nary(node, seed)
+ last_child = node.children.last
+ node.children.inject(seed) { |s, c|
+ string = visit(c, s)
+ string << "|".freeze unless last_child == c
+ string
+ }
end
- def terminal(node)
- node.left
+ def terminal(node, seed)
+ seed + node.left
end
- def visit_GROUP(node)
- "(#{visit(node.left)})"
+ def visit_GROUP(node, seed)
+ visit(node.left, seed << "(".freeze) << ")".freeze
end
+
+ INSTANCE = new
end
- class Dot < Visitor # :nodoc:
+ class Dot < FunctionalVisitor # :nodoc:
def initialize
@nodes = []
@edges = []
end
- def accept(node)
+ def accept(node, seed = [[], []])
super
+ nodes, edges = seed
<<-eodot
digraph parse_tree {
size="8,5"
node [shape = none];
edge [dir = none];
- #{@nodes.join "\n"}
- #{@edges.join("\n")}
+ #{nodes.join "\n"}
+ #{edges.join("\n")}
}
eodot
end
private
- def binary(node)
- node.children.each do |c|
- @edges << "#{node.object_id} -> #{c.object_id};"
- end
+ def binary(node, seed)
+ seed.last.concat node.children.map { |c|
+ "#{node.object_id} -> #{c.object_id};"
+ }
super
end
- def nary(node)
- node.children.each do |c|
- @edges << "#{node.object_id} -> #{c.object_id};"
- end
+ def nary(node, seed)
+ seed.last.concat node.children.map { |c|
+ "#{node.object_id} -> #{c.object_id};"
+ }
super
end
- def unary(node)
- @edges << "#{node.object_id} -> #{node.left.object_id};"
+ def unary(node, seed)
+ seed.last << "#{node.object_id} -> #{node.left.object_id};"
super
end
- def visit_GROUP(node)
- @nodes << "#{node.object_id} [label=\"()\"];"
+ def visit_GROUP(node, seed)
+ seed.first << "#{node.object_id} [label=\"()\"];"
super
end
- def visit_CAT(node)
- @nodes << "#{node.object_id} [label=\"○\"];"
+ def visit_CAT(node, seed)
+ seed.first << "#{node.object_id} [label=\"○\"];"
super
end
- def visit_STAR(node)
- @nodes << "#{node.object_id} [label=\"*\"];"
+ def visit_STAR(node, seed)
+ seed.first << "#{node.object_id} [label=\"*\"];"
super
end
- def visit_OR(node)
- @nodes << "#{node.object_id} [label=\"|\"];"
+ def visit_OR(node, seed)
+ seed.first << "#{node.object_id} [label=\"|\"];"
super
end
- def terminal(node)
+ def terminal(node, seed)
value = node.left
- @nodes << "#{node.object_id} [label=\"#{value}\"];"
+ seed.first << "#{node.object_id} [label=\"#{value}\"];"
+ seed
end
+ INSTANCE = new
end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index b7687ca100..65baf117ba 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -1,15 +1,57 @@
require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/object/blank'
require 'active_support/key_generator'
require 'active_support/message_verifier'
require 'active_support/json'
module ActionDispatch
- class Request < Rack::Request
+ class Request
def cookie_jar
- env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
+ fetch_header('action_dispatch.cookies'.freeze) do
+ self.cookie_jar = Cookies::CookieJar.build(self, cookies)
+ end
+ end
+
+ # :stopdoc:
+ def have_cookie_jar?
+ has_header? 'action_dispatch.cookies'.freeze
+ end
+
+ def cookie_jar=(jar)
+ set_header 'action_dispatch.cookies'.freeze, jar
+ end
+
+ def key_generator
+ get_header Cookies::GENERATOR_KEY
+ end
+
+ def signed_cookie_salt
+ get_header Cookies::SIGNED_COOKIE_SALT
+ end
+
+ def encrypted_cookie_salt
+ get_header Cookies::ENCRYPTED_COOKIE_SALT
+ end
+
+ def encrypted_signed_cookie_salt
+ get_header Cookies::ENCRYPTED_SIGNED_COOKIE_SALT
+ end
+
+ def secret_token
+ get_header Cookies::SECRET_TOKEN
+ end
+
+ def secret_key_base
+ get_header Cookies::SECRET_KEY_BASE
+ end
+
+ def cookies_serializer
+ get_header Cookies::COOKIES_SERIALIZER
+ end
+
+ def cookies_digest
+ get_header Cookies::COOKIES_DIGEST
end
+ # :startdoc:
end
# \Cookies are read and written through ActionController#cookies.
@@ -35,6 +77,12 @@ module ActionDispatch
# # It can be read using the signed method `cookies.signed[:name]`
# cookies.signed[:user_id] = current_user.id
#
+ # # Sets an encrypted cookie value before sending it to the client which
+ # # prevent users from reading and tampering with its value.
+ # # The cookie is signed by your app's `secrets.secret_key_base` value.
+ # # It can be read using the encrypted method `cookies.encrypted[:name]`
+ # cookies.encrypted[:discount] = 45
+ #
# # Sets a "permanent" cookie (which expires in 20 years from now).
# cookies.permanent[:login] = "XJ-122"
#
@@ -47,6 +95,7 @@ module ActionDispatch
# cookies.size # => 2
# JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37]
# cookies.signed[:login] # => "XJ-122"
+ # cookies.encrypted[:discount] # => 45
#
# Example for deleting:
#
@@ -79,6 +128,9 @@ module ActionDispatch
# domain: %w(.example.com .example.org) # Allow the cookie
# # for concrete domain names.
#
+ # * <tt>:tld_length</tt> - When using <tt>:domain => :all</tt>, this option can be used to explicitly
+ # set the TLD length when using a short (<= 3 character) domain that is being interpreted as part of a TLD.
+ # For example, to share cookies between user1.lvh.me and user2.lvh.me, set <tt>:tld_length</tt> to 1.
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
# * <tt>:secure</tt> - Whether this cookie is only transmitted to HTTPS servers.
# Default is +false+.
@@ -115,7 +167,7 @@ module ActionDispatch
# cookies.permanent.signed[:remember_me] = current_user.id
# # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
def permanent
- @permanent ||= PermanentCookieJar.new(self, @key_generator, @options)
+ @permanent ||= PermanentCookieJar.new(self)
end
# Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
@@ -135,10 +187,10 @@ module ActionDispatch
# cookies.signed[:discount] # => 45
def signed
@signed ||=
- if @options[:upgrade_legacy_signed_cookies]
- UpgradeLegacySignedCookieJar.new(self, @key_generator, @options)
+ if upgrade_legacy_signed_cookies?
+ UpgradeLegacySignedCookieJar.new(self)
else
- SignedCookieJar.new(self, @key_generator, @options)
+ SignedCookieJar.new(self)
end
end
@@ -158,10 +210,10 @@ module ActionDispatch
# cookies.encrypted[:discount] # => 45
def encrypted
@encrypted ||=
- if @options[:upgrade_legacy_signed_cookies]
- UpgradeLegacyEncryptedCookieJar.new(self, @key_generator, @options)
+ if upgrade_legacy_signed_cookies?
+ UpgradeLegacyEncryptedCookieJar.new(self)
else
- EncryptedCookieJar.new(self, @key_generator, @options)
+ EncryptedCookieJar.new(self)
end
end
@@ -169,22 +221,28 @@ module ActionDispatch
# Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores.
def signed_or_encrypted
@signed_or_encrypted ||=
- if @options[:secret_key_base].present?
+ if request.secret_key_base.present?
encrypted
else
signed
end
end
+
+ private
+
+ def upgrade_legacy_signed_cookies?
+ request.secret_token.present? && request.secret_key_base.present?
+ end
end
# Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream
# to the Message{Encryptor,Verifier} allows us to handle the
# (de)serialization step within the cookie jar, which gives us the
# opportunity to detect and migrate legacy cookies.
- module VerifyAndUpgradeLegacySignedMessage
+ module VerifyAndUpgradeLegacySignedMessage # :nodoc:
def initialize(*args)
super
- @legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token], serializer: ActiveSupport::MessageEncryptor::NullSerializer)
+ @legacy_verifier = ActiveSupport::MessageVerifier.new(request.secret_token, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
end
def verify_and_upgrade_legacy_signed_message(name, signed_message)
@@ -194,6 +252,11 @@ module ActionDispatch
rescue ActiveSupport::MessageVerifier::InvalidSignature
nil
end
+
+ private
+ def parse(name, signed_message)
+ super || verify_and_upgrade_legacy_signed_message(name, signed_message)
+ end
end
class CookieJar #:nodoc:
@@ -213,38 +276,18 @@ module ActionDispatch
# $& => example.local
DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
- def self.options_for_env(env) #:nodoc:
- { signed_cookie_salt: env[SIGNED_COOKIE_SALT] || '',
- encrypted_cookie_salt: env[ENCRYPTED_COOKIE_SALT] || '',
- encrypted_signed_cookie_salt: env[ENCRYPTED_SIGNED_COOKIE_SALT] || '',
- secret_token: env[SECRET_TOKEN],
- secret_key_base: env[SECRET_KEY_BASE],
- upgrade_legacy_signed_cookies: env[SECRET_TOKEN].present? && env[SECRET_KEY_BASE].present?,
- serializer: env[COOKIES_SERIALIZER],
- digest: env[COOKIES_DIGEST]
- }
- end
-
- def self.build(request)
- env = request.env
- key_generator = env[GENERATOR_KEY]
- options = options_for_env env
-
- host = request.host
- secure = request.ssl?
-
- new(key_generator, host, secure, options).tap do |hash|
- hash.update(request.cookies)
+ def self.build(req, cookies)
+ new(req).tap do |hash|
+ hash.update(cookies)
end
end
- def initialize(key_generator, host = nil, secure = false, options = {})
- @key_generator = key_generator
+ attr_reader :request
+
+ def initialize(request)
@set_cookies = {}
@delete_cookies = {}
- @host = host
- @secure = secure
- @options = options
+ @request = request
@cookies = {}
@committed = false
end
@@ -280,6 +323,17 @@ module ActionDispatch
self
end
+ def update_cookies_from_jar
+ request_jar = @request.cookie_jar.instance_variable_get(:@cookies)
+ set_cookies = request_jar.reject { |k,_| @delete_cookies.key?(k) }
+
+ @cookies.update set_cookies if set_cookies
+ end
+
+ def to_header
+ @cookies.map { |k,v| "#{k}=#{v}" }.join ';'
+ end
+
def handle_options(options) #:nodoc:
options[:path] ||= "/"
@@ -289,12 +343,12 @@ module ActionDispatch
# if host is not ip and matches domain regexp
# (ip confirms to domain regexp so we explicitly check for ip)
- options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
+ options[:domain] = if (request.host !~ /^[\d.]+$/) && (request.host =~ domain_regexp)
".#{$&}"
end
elsif options[:domain].is_a? Array
# if host matches one of the supplied domains without a dot in front of it
- options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
+ options[:domain] = options[:domain].find {|domain| request.host.include? domain.sub(/^\./, '') }
end
end
@@ -349,50 +403,74 @@ module ActionDispatch
end
def write(headers)
- @set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) }
- @delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) }
- end
-
- def recycle! #:nodoc:
- @set_cookies = {}
- @delete_cookies = {}
+ if header = make_set_cookie_header(headers[HTTP_HEADER])
+ headers[HTTP_HEADER] = header
+ end
end
mattr_accessor :always_write_cookie
self.always_write_cookie = false
private
- def write_cookie?(cookie)
- @secure || !cookie[:secure] || always_write_cookie
- end
+
+ def make_set_cookie_header(header)
+ header = @set_cookies.inject(header) { |m, (k, v)|
+ if write_cookie?(v)
+ ::Rack::Utils.add_cookie_to_header(m, k, v)
+ else
+ m
+ end
+ }
+ @delete_cookies.inject(header) { |m, (k, v)|
+ ::Rack::Utils.add_remove_cookie_to_header(m, k, v)
+ }
+ end
+
+ def write_cookie?(cookie)
+ request.ssl? || !cookie[:secure] || always_write_cookie
+ end
end
- class PermanentCookieJar #:nodoc:
+ class AbstractCookieJar # :nodoc:
include ChainedCookieJars
- def initialize(parent_jar, key_generator, options = {})
+ def initialize(parent_jar)
@parent_jar = parent_jar
- @key_generator = key_generator
- @options = options
end
def [](name)
- @parent_jar[name.to_s]
+ if data = @parent_jar[name.to_s]
+ parse name, data
+ end
end
def []=(name, options)
if options.is_a?(Hash)
options.symbolize_keys!
else
- options = { :value => options }
+ options = { value: options }
end
- options[:expires] = 20.years.from_now
+ commit(options)
@parent_jar[name] = options
end
+
+ protected
+ def request; @parent_jar.request; end
+
+ private
+ def parse(name, data); data; end
+ def commit(options); end
+ end
+
+ class PermanentCookieJar < AbstractCookieJar # :nodoc:
+ private
+ def commit(options)
+ options[:expires] = 20.years.from_now
+ end
end
- class JsonSerializer
+ class JsonSerializer # :nodoc:
def self.load(value)
ActiveSupport::JSON.decode(value)
end
@@ -402,12 +480,12 @@ module ActionDispatch
end
end
- module SerializedCookieJars
+ module SerializedCookieJars # :nodoc:
MARSHAL_SIGNATURE = "\x04\x08".freeze
protected
def needs_migration?(value)
- @options[:serializer] == :hybrid && value.start_with?(MARSHAL_SIGNATURE)
+ request.cookies_serializer == :hybrid && value.start_with?(MARSHAL_SIGNATURE)
end
def serialize(value)
@@ -427,7 +505,7 @@ module ActionDispatch
end
def serializer
- serializer = @options[:serializer] || :marshal
+ serializer = request.cookies_serializer || :marshal
case serializer
when :marshal
Marshal
@@ -439,103 +517,71 @@ module ActionDispatch
end
def digest
- @options[:digest] || 'SHA1'
+ request.cookies_digest || 'SHA1'
+ end
+
+ def key_generator
+ request.key_generator
end
end
- class SignedCookieJar #:nodoc:
- include ChainedCookieJars
+ class SignedCookieJar < AbstractCookieJar # :nodoc:
include SerializedCookieJars
- def initialize(parent_jar, key_generator, options = {})
- @parent_jar = parent_jar
- @options = options
- secret = key_generator.generate_key(@options[:signed_cookie_salt])
+ def initialize(parent_jar)
+ super
+ secret = key_generator.generate_key(request.signed_cookie_salt)
@verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
end
- def [](name)
- if signed_message = @parent_jar[name]
- deserialize name, verify(signed_message)
+ private
+ def parse(name, signed_message)
+ deserialize name, @verifier.verified(signed_message)
end
- end
- def []=(name, options)
- if options.is_a?(Hash)
- options.symbolize_keys!
+ def commit(options)
options[:value] = @verifier.generate(serialize(options[:value]))
- else
- options = { :value => @verifier.generate(serialize(options)) }
- end
- raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
- @parent_jar[name] = options
- end
-
- private
- def verify(signed_message)
- @verifier.verify(signed_message)
- rescue ActiveSupport::MessageVerifier::InvalidSignature
- nil
+ raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
end
end
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
# secrets.secret_token and secrets.secret_key_base are both set. It reads
- # legacy cookies signed with the old dummy key generator and re-saves
- # them using the new key generator to provide a smooth upgrade path.
+ # legacy cookies signed with the old dummy key generator and signs and
+ # re-saves them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
include VerifyAndUpgradeLegacySignedMessage
-
- def [](name)
- if signed_message = @parent_jar[name]
- deserialize(name, verify(signed_message)) || verify_and_upgrade_legacy_signed_message(name, signed_message)
- end
- end
end
- class EncryptedCookieJar #:nodoc:
- include ChainedCookieJars
+ class EncryptedCookieJar < AbstractCookieJar # :nodoc:
include SerializedCookieJars
- def initialize(parent_jar, key_generator, options = {})
+ def initialize(parent_jar)
+ super
+
if ActiveSupport::LegacyKeyGenerator === key_generator
raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " +
"Read the upgrade documentation to learn more about this new config option."
end
- @parent_jar = parent_jar
- @options = options
- secret = key_generator.generate_key(@options[:encrypted_cookie_salt])
- sign_secret = key_generator.generate_key(@options[:encrypted_signed_cookie_salt])
+ secret = key_generator.generate_key(request.encrypted_cookie_salt || '')
+ sign_secret = key_generator.generate_key(request.encrypted_signed_cookie_salt || '')
@encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
end
- def [](name)
- if encrypted_message = @parent_jar[name]
- deserialize name, decrypt_and_verify(encrypted_message)
- end
- end
-
- def []=(name, options)
- if options.is_a?(Hash)
- options.symbolize_keys!
- else
- options = { :value => options }
- end
-
- options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value]))
-
- raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
- @parent_jar[name] = options
- end
-
private
- def decrypt_and_verify(encrypted_message)
- @encryptor.decrypt_and_verify(encrypted_message)
+ def parse(name, encrypted_message)
+ deserialize name, @encryptor.decrypt_and_verify(encrypted_message)
rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage
nil
end
+
+ def commit(options)
+ options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value]))
+
+ raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
+ end
end
# UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
@@ -544,12 +590,6 @@ module ActionDispatch
# encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
include VerifyAndUpgradeLegacySignedMessage
-
- def [](name)
- if encrypted_or_signed_message = @parent_jar[name]
- deserialize(name, decrypt_and_verify(encrypted_or_signed_message)) || verify_and_upgrade_legacy_signed_message(name, encrypted_or_signed_message)
- end
- end
end
def initialize(app)
@@ -557,9 +597,12 @@ module ActionDispatch
end
def call(env)
+ request = ActionDispatch::Request.new env
+
status, headers, body = @app.call(env)
- if cookie_jar = env['action_dispatch.cookies']
+ if request.have_cookie_jar?
+ cookie_jar = request.cookie_jar
unless cookie_jar.committed?
cookie_jar.write(headers)
if headers[HTTP_HEADER].respond_to?(:join)
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index 9082aac271..66bb74b9c5 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -44,6 +44,7 @@ module ActionDispatch
end
def call(env)
+ request = ActionDispatch::Request.new env
_, headers, body = response = @app.call(env)
if headers['X-Cascade'] == 'pass'
@@ -53,18 +54,18 @@ module ActionDispatch
response
rescue Exception => exception
- raise exception if env['action_dispatch.show_exceptions'] == false
- render_exception(env, exception)
+ raise exception unless request.show_exceptions?
+ render_exception(request, exception)
end
private
- def render_exception(env, exception)
- wrapper = ExceptionWrapper.new(env, exception)
- log_error(env, wrapper)
+ def render_exception(request, exception)
+ backtrace_cleaner = request.get_header('action_dispatch.backtrace_cleaner')
+ wrapper = ExceptionWrapper.new(backtrace_cleaner, exception)
+ log_error(request, wrapper)
- if env['action_dispatch.show_detailed_exceptions']
- request = Request.new(env)
+ if request.get_header('action_dispatch.show_detailed_exceptions')
traces = wrapper.traces
trace_to_show = 'Application Trace'
@@ -106,8 +107,8 @@ module ActionDispatch
[status, {'Content-Type' => "#{format}; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
end
- def log_error(env, wrapper)
- logger = logger(env)
+ def log_error(request, wrapper)
+ logger = logger(request)
return unless logger
exception = wrapper.exception
@@ -123,8 +124,8 @@ module ActionDispatch
end
end
- def logger(env)
- env['action_dispatch.logger'] || stderr_logger
+ def logger(request)
+ request.logger || stderr_logger
end
def stderr_logger
diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
index d176a73633..3b61824cc9 100644
--- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
+++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
@@ -17,7 +17,9 @@ module ActionDispatch
'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity,
'ActionDispatch::ParamsParser::ParseError' => :bad_request,
'ActionController::BadRequest' => :bad_request,
- 'ActionController::ParameterMissing' => :bad_request
+ 'ActionController::ParameterMissing' => :bad_request,
+ 'Rack::Utils::ParameterTypeError' => :bad_request,
+ 'Rack::Utils::InvalidParameterError' => :bad_request
)
cattr_accessor :rescue_templates
@@ -29,13 +31,13 @@ module ActionDispatch
'ActionView::Template::Error' => 'template_error'
)
- attr_reader :env, :exception, :line_number, :file
+ attr_reader :backtrace_cleaner, :exception, :line_number, :file
- def initialize(env, exception)
- @env = env
+ def initialize(backtrace_cleaner, exception)
+ @backtrace_cleaner = backtrace_cleaner
@exception = original_exception(exception)
- expand_backtrace if exception.is_a?(SyntaxError) || exception.try(:original_exception).try(:is_a?, SyntaxError)
+ expand_backtrace if exception.is_a?(SyntaxError) || exception.cause.is_a?(SyntaxError)
end
def rescue_template
@@ -59,7 +61,7 @@ module ActionDispatch
end
def traces
- appplication_trace_with_ids = []
+ application_trace_with_ids = []
framework_trace_with_ids = []
full_trace_with_ids = []
@@ -67,7 +69,7 @@ module ActionDispatch
trace_with_id = { id: idx, trace: trace }
if application_trace.include?(trace)
- appplication_trace_with_ids << trace_with_id
+ application_trace_with_ids << trace_with_id
else
framework_trace_with_ids << trace_with_id
end
@@ -76,7 +78,7 @@ module ActionDispatch
end
{
- "Application Trace" => appplication_trace_with_ids,
+ "Application Trace" => application_trace_with_ids,
"Framework Trace" => framework_trace_with_ids,
"Full Trace" => full_trace_with_ids
}
@@ -104,17 +106,13 @@ module ActionDispatch
end
def original_exception(exception)
- if registered_original_exception?(exception)
- exception.original_exception
+ if @@rescue_responses.has_key?(exception.cause.class.name)
+ exception.cause
else
exception
end
end
- def registered_original_exception?(exception)
- exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
- end
-
def clean_backtrace(*args)
if backtrace_cleaner
backtrace_cleaner.clean(backtrace, *args)
@@ -123,10 +121,6 @@ module ActionDispatch
end
end
- def backtrace_cleaner
- @backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
- end
-
def source_fragment(path, line)
return unless Rails.respond_to?(:root) && Rails.root
full_path = Rails.root.join(path)
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index 59639a010e..c51dcd542a 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -1,15 +1,6 @@
require 'active_support/core_ext/hash/keys'
module ActionDispatch
- class Request < Rack::Request
- # Access the contents of the flash. Use <tt>flash["notice"]</tt> to
- # read a notice you put there or <tt>flash["notice"] = "hello"</tt>
- # to put a new one.
- def flash
- @env[Flash::KEY] ||= Flash::FlashHash.from_session_value(session["flash"])
- end
- end
-
# The flash provides a way to pass temporary primitive-types (String, Array, Hash) between actions. Anything you place in the flash will be exposed
# to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create
# action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can
@@ -47,6 +38,40 @@ module ActionDispatch
class Flash
KEY = 'action_dispatch.request.flash_hash'.freeze
+ module RequestMethods
+ # Access the contents of the flash. Use <tt>flash["notice"]</tt> to
+ # read a notice you put there or <tt>flash["notice"] = "hello"</tt>
+ # to put a new one.
+ def flash
+ flash = flash_hash
+ return flash if flash
+ self.flash = Flash::FlashHash.from_session_value(session["flash"])
+ end
+
+ def flash=(flash)
+ set_header Flash::KEY, flash
+ end
+
+ def flash_hash # :nodoc:
+ get_header Flash::KEY
+ end
+
+ def commit_flash # :nodoc:
+ session = self.session || {}
+ flash_hash = self.flash_hash
+
+ if flash_hash && (flash_hash.present? || session.key?('flash'))
+ session["flash"] = flash_hash.to_session_value
+ self.flash = flash_hash.dup
+ end
+
+ if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
+ session.key?('flash') && session['flash'].nil?
+ session.delete('flash')
+ end
+ end
+ end
+
class FlashNow #:nodoc:
attr_accessor :flash
@@ -258,25 +283,10 @@ module ActionDispatch
end
end
- def initialize(app)
- @app = app
- end
-
- def call(env)
- @app.call(env)
- ensure
- session = Request::Session.find(env) || {}
- flash_hash = env[KEY]
-
- if flash_hash && (flash_hash.present? || session.key?('flash'))
- session["flash"] = flash_hash.to_session_value
- env[KEY] = flash_hash.dup
- end
+ def self.new(app) app; end
+ end
- if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
- session.key?('flash') && session['flash'].nil?
- session.delete('flash')
- end
- end
+ class Request
+ prepend Flash::RequestMethods
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/load_interlock.rb b/actionpack/lib/action_dispatch/middleware/load_interlock.rb
new file mode 100644
index 0000000000..07f498319c
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/load_interlock.rb
@@ -0,0 +1,21 @@
+require 'active_support/dependencies'
+require 'rack/body_proxy'
+
+module ActionDispatch
+ class LoadInterlock
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ interlock = ActiveSupport::Dependencies.interlock
+ interlock.start_running
+ response = @app.call(env)
+ body = Rack::BodyProxy.new(response[2]) { interlock.done_running }
+ response[2] = body
+ response
+ ensure
+ interlock.done_running unless body
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index 29d43faeed..c2a4f46e67 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -1,60 +1,44 @@
-require 'active_support/core_ext/hash/conversions'
require 'action_dispatch/http/request'
-require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
+ # ActionDispatch::ParamsParser works for all the requests having any Content-Length
+ # (like POST). It takes raw data from the request and puts it through the parser
+ # that is picked based on Content-Type header.
+ #
+ # In case of any error while parsing data ParamsParser::ParseError is raised.
class ParamsParser
+ # Raised when raw data from the request cannot be parsed by the parser
+ # defined for request's content mime type.
class ParseError < StandardError
- attr_reader :original_exception
- def initialize(message, original_exception)
- super(message)
- @original_exception = original_exception
- end
- end
-
- DEFAULT_PARSERS = { Mime::JSON => :json }
-
- def initialize(app, parsers = {})
- @app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
- end
-
- def call(env)
- if params = parse_formatted_parameters(env)
- env["action_dispatch.request.request_parameters"] = params
- end
-
- @app.call(env)
- end
-
- private
- def parse_formatted_parameters(env)
- request = Request.new(env)
-
- return false if request.content_length.zero?
-
- strategy = @parsers[request.content_mime_type]
-
- return false unless strategy
+ def initialize(message = nil, original_exception = nil)
+ if message
+ ActiveSupport::Deprecation.warn("Passing #message is deprecated and has no effect. " \
+ "#{self.class} will automatically capture the message " \
+ "of the original exception.", caller)
+ end
- case strategy
- when Proc
- strategy.call(request.raw_post)
- when :json
- data = ActiveSupport::JSON.decode(request.raw_post)
- data = {:_json => data} unless data.is_a?(Hash)
- Request::Utils.deep_munge(data).with_indifferent_access
- else
- false
+ if original_exception
+ ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \
+ "Exceptions will automatically capture the original exception.", caller)
end
- rescue => e # JSON or Ruby code block errors
- logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
- raise ParseError.new(e.message, e)
+ super($!.message)
end
- def logger(env)
- env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
+ def original_exception
+ ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller)
+ cause
end
+ end
+
+ # Create a new +ParamsParser+ middleware instance.
+ #
+ # The +parsers+ argument can take Hash of parsers where key is identifying
+ # content mime type, and value is a lambda that is going to process data.
+ def self.new(app, parsers = {})
+ ActionDispatch::Request.parameter_parsers = ActionDispatch::Request::DEFAULT_PARSERS.merge(parsers)
+ app
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
index 7cde76b30e..0f27984550 100644
--- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
@@ -17,8 +17,8 @@ module ActionDispatch
end
def call(env)
- status = env["PATH_INFO"][1..-1].to_i
request = ActionDispatch::Request.new(env)
+ status = request.path_info[1..-1].to_i
content_type = request.formats.first
body = { :status => status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]) }
diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb
index 15b5a48535..af9a29eb07 100644
--- a/actionpack/lib/action_dispatch/middleware/reloader.rb
+++ b/actionpack/lib/action_dispatch/middleware/reloader.rb
@@ -1,5 +1,3 @@
-require 'active_support/deprecation/reporting'
-
module ActionDispatch
# ActionDispatch::Reloader provides prepare and cleanup callbacks,
# intended to assist with code reloading during development.
@@ -11,9 +9,9 @@ module ActionDispatch
# the response body. This is important for streaming responses such as the
# following:
#
- # self.response_body = lambda { |response, output|
+ # self.response_body = -> (response, output) do
# # code here which refers to application models
- # }
+ # end
#
# Cleanup callbacks will not be called until after the response_body lambda
# is evaluated, ensuring that it can refer to application models and other
diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
index 7c4236518d..31b75498b6 100644
--- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb
+++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
@@ -43,7 +43,7 @@ module ActionDispatch
# Create a new +RemoteIp+ middleware instance.
#
- # The +check_ip_spoofing+ option is on by default. When on, an exception
+ # The +ip_spoofing_check+ option is on by default. When on, an exception
# is raised if it looks like the client is trying to lie about its own IP
# address. It makes sense to turn off this check on sites aimed at non-IP
# clients (like WAP devices), or behind proxies that set headers in an
@@ -57,9 +57,9 @@ module ActionDispatch
# with your proxy servers after it. If your proxies aren't removed, pass
# them in via the +custom_proxies+ parameter. That way, the middleware will
# ignore those IP addresses, and return the one that you want.
- def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
+ def initialize(app, ip_spoofing_check = true, custom_proxies = nil)
@app = app
- @check_ip = check_ip_spoofing
+ @check_ip = ip_spoofing_check
@proxies = if custom_proxies.blank?
TRUSTED_PROXIES
elsif custom_proxies.respond_to?(:any?)
@@ -74,18 +74,19 @@ module ActionDispatch
# requests. For those requests that do need to know the IP, the
# GetIp#calculate_ip method will calculate the memoized client IP address.
def call(env)
- env["action_dispatch.remote_ip"] = GetIp.new(env, self)
- @app.call(env)
+ req = ActionDispatch::Request.new env
+ req.remote_ip = GetIp.new(req, check_ip, proxies)
+ @app.call(req.env)
end
# The GetIp class exists as a way to defer processing of the request data
# into an actual IP address. If the ActionDispatch::Request#remote_ip method
# is called, this class will calculate the value and then memoize it.
class GetIp
- def initialize(env, middleware)
- @env = env
- @check_ip = middleware.check_ip
- @proxies = middleware.proxies
+ def initialize(req, check_ip, proxies)
+ @req = req
+ @check_ip = check_ip
+ @proxies = proxies
end
# Sort through the various IP address headers, looking for the IP most
@@ -108,23 +109,31 @@ module ActionDispatch
# the last address left, which was presumably set by one of those proxies.
def calculate_ip
# Set by the Rack web server, this is a single value.
- remote_addr = ips_from('REMOTE_ADDR').last
+ remote_addr = ips_from(@req.remote_addr).last
# Could be a CSV list and/or repeated headers that were concatenated.
- client_ips = ips_from('HTTP_CLIENT_IP').reverse
- forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse
+ client_ips = ips_from(@req.client_ip).reverse
+ forwarded_ips = ips_from(@req.x_forwarded_for).reverse
# +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
- # If they are both set, it means that this request passed through two
- # proxies with incompatible IP header conventions, and there is no way
- # for us to determine which header is the right one after the fact.
- # Since we have no idea, we give up and explode.
+ # If they are both set, it means that either:
+ #
+ # 1) This request passed through two proxies with incompatible IP header
+ # conventions.
+ # 2) The client passed one of +Client-Ip+ or +X-Forwarded-For+
+ # (whichever the proxy servers weren't using) themselves.
+ #
+ # Either way, there is no way for us to determine which header is the
+ # right one after the fact. Since we have no idea, if we are concerned
+ # about IP spoofing we need to give up and explode. (If you're not
+ # concerned about IP spoofing you can turn the +ip_spoofing_check+
+ # option off.)
should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
if should_check_ip && !forwarded_ips.include?(client_ips.last)
# We don't know which came from the proxy, and which from the user
raise IpSpoofAttackError, "IP spoofing attack?! " +
- "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " +
- "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
+ "HTTP_CLIENT_IP=#{@req.client_ip.inspect} " +
+ "HTTP_X_FORWARDED_FOR=#{@req.x_forwarded_for.inspect}"
end
# We assume these things about the IP headers:
@@ -147,8 +156,9 @@ module ActionDispatch
protected
def ips_from(header)
+ return [] unless header
# Split the comma-separated list into an array of strings
- ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
+ ips = header.strip.split(/[,\s]+/)
ips.select do |ip|
begin
# Only return IPs that are valid according to the IPAddr#new method
diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb
index b9ca524309..1555ff72af 100644
--- a/actionpack/lib/action_dispatch/middleware/request_id.rb
+++ b/actionpack/lib/action_dispatch/middleware/request_id.rb
@@ -13,22 +13,23 @@ module ActionDispatch
# from multiple pieces of the stack.
class RequestId
X_REQUEST_ID = "X-Request-Id".freeze # :nodoc:
- ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id".freeze # :nodoc:
- HTTP_X_REQUEST_ID = "HTTP_X_REQUEST_ID".freeze # :nodoc:
def initialize(app)
@app = app
end
def call(env)
- env[ACTION_DISPATCH_REQUEST_ID] = external_request_id(env) || internal_request_id
- @app.call(env).tap { |_status, headers, _body| headers[X_REQUEST_ID] = env[ACTION_DISPATCH_REQUEST_ID] }
+ req = ActionDispatch::Request.new env
+ req.request_id = make_request_id(req.x_request_id)
+ @app.call(env).tap { |_status, headers, _body| headers[X_REQUEST_ID] = req.request_id }
end
private
- def external_request_id(env)
- if request_id = env[HTTP_X_REQUEST_ID].presence
+ def make_request_id(request_id)
+ if request_id.presence
request_id.gsub(/[^\w\-]/, "".freeze).first(255)
+ else
+ internal_request_id
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index 84df55fd5a..5fb5953811 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -7,14 +7,22 @@ require 'action_dispatch/request/session'
module ActionDispatch
module Session
class SessionRestoreError < StandardError #:nodoc:
- attr_reader :original_exception
- def initialize(const_error)
- @original_exception = const_error
+ def initialize(const_error = nil)
+ if const_error
+ ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \
+ "Exceptions will automatically capture the original exception.", caller)
+ end
super("Session contains objects whose class definition isn't available.\n" +
"Remember to require the classes for all objects kept in the session.\n" +
- "(Original exception: #{const_error.message} [#{const_error.class}])\n")
+ "(Original exception: #{$!.message} [#{$!.class}])\n")
+ set_backtrace $!.backtrace
+ end
+
+ def original_exception
+ ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller)
+ cause
end
end
@@ -36,6 +44,11 @@ module ActionDispatch
@default_options.delete(:sidbits)
@default_options.delete(:secure_random)
end
+
+ private
+ def make_request(env)
+ ActionDispatch::Request.new env
+ end
end
module StaleSessionCheck
@@ -54,8 +67,8 @@ module ActionDispatch
begin
# Note that the regexp does not allow $1 to end with a ':'
$1.constantize
- rescue LoadError, NameError => e
- raise ActionDispatch::Session::SessionRestoreError, e, e.backtrace
+ rescue LoadError, NameError
+ raise ActionDispatch::Session::SessionRestoreError
end
retry
else
@@ -65,8 +78,8 @@ module ActionDispatch
end
module SessionObject # :nodoc:
- def prepare_session(env)
- Request::Session.create(self, env, @default_options)
+ def prepare_session(req)
+ Request::Session.create(self, req, @default_options)
end
def loaded_session?(session)
@@ -74,15 +87,14 @@ module ActionDispatch
end
end
- class AbstractStore < Rack::Session::Abstract::ID
+ class AbstractStore < Rack::Session::Abstract::Persisted
include Compatibility
include StaleSessionCheck
include SessionObject
private
- def set_cookie(env, session_id, cookie)
- request = ActionDispatch::Request.new(env)
+ def set_cookie(request, session_id, cookie)
request.cookie_jar[key] = cookie
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
index 857e49a682..589ae46e38 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
@@ -18,7 +18,7 @@ module ActionDispatch
end
# Get a session from the cache.
- def get_session(env, sid)
+ def find_session(env, sid)
unless sid and session = @cache.read(cache_key(sid))
sid, session = generate_sid, {}
end
@@ -26,7 +26,7 @@ module ActionDispatch
end
# Set a session in the cache.
- def set_session(env, sid, session, options)
+ def write_session(env, sid, session, options)
key = cache_key(sid)
if session
@cache.write(key, session, :expires_in => options[:expire_after])
@@ -37,7 +37,7 @@ module ActionDispatch
end
# Remove a session from the cache.
- def destroy_session(env, sid, options)
+ def delete_session(env, sid, options)
@cache.delete(cache_key(sid))
generate_sid
end
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index d8f9614904..0e636b8257 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -53,7 +53,7 @@ module ActionDispatch
#
# Note that changing the secret key will invalidate all existing sessions!
#
- # Because CookieStore extends Rack::Session::Abstract::ID, many of the
+ # Because CookieStore extends Rack::Session::Abstract::Persisted, many of the
# options described there can be used to customize the session cookie that
# is generated. For example:
#
@@ -62,25 +62,21 @@ module ActionDispatch
# would set the session cookie to expire automatically 14 days after creation.
# Other useful options include <tt>:key</tt>, <tt>:secure</tt> and
# <tt>:httponly</tt>.
- class CookieStore < Rack::Session::Abstract::ID
- include Compatibility
- include StaleSessionCheck
- include SessionObject
-
+ class CookieStore < AbstractStore
def initialize(app, options={})
super(app, options.merge!(:cookie_only => true))
end
- def destroy_session(env, session_id, options)
+ def delete_session(req, session_id, options)
new_sid = generate_sid unless options[:drop]
# Reset hash and Assign the new session id
- env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {}
+ req.set_header("action_dispatch.request.unsigned_session_cookie", new_sid ? { "session_id" => new_sid } : {})
new_sid
end
- def load_session(env)
+ def load_session(req)
stale_session_check! do
- data = unpacked_cookie_data(env)
+ data = unpacked_cookie_data(req)
data = persistent_session_id!(data)
[data["session_id"], data]
end
@@ -88,20 +84,21 @@ module ActionDispatch
private
- def extract_session_id(env)
+ def extract_session_id(req)
stale_session_check! do
- unpacked_cookie_data(env)["session_id"]
+ unpacked_cookie_data(req)["session_id"]
end
end
- def unpacked_cookie_data(env)
- env["action_dispatch.request.unsigned_session_cookie"] ||= begin
- stale_session_check! do
- if data = get_cookie(env)
+ def unpacked_cookie_data(req)
+ req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k|
+ v = stale_session_check! do
+ if data = get_cookie(req)
data.stringify_keys!
end
data || {}
end
+ req.set_header k, v
end
end
@@ -111,21 +108,20 @@ module ActionDispatch
data
end
- def set_session(env, sid, session_data, options)
+ def write_session(req, sid, session_data, options)
session_data["session_id"] = sid
session_data
end
- def set_cookie(env, session_id, cookie)
- cookie_jar(env)[@key] = cookie
+ def set_cookie(request, session_id, cookie)
+ cookie_jar(request)[@key] = cookie
end
- def get_cookie(env)
- cookie_jar(env)[@key]
+ def get_cookie(req)
+ cookie_jar(req)[@key]
end
- def cookie_jar(env)
- request = ActionDispatch::Request.new(env)
+ def cookie_jar(request)
request.cookie_jar.signed_or_encrypted
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index f0779279c1..64695f9738 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -27,24 +27,26 @@ module ActionDispatch
end
def call(env)
+ request = ActionDispatch::Request.new env
@app.call(env)
rescue Exception => exception
- if env['action_dispatch.show_exceptions'] == false
- raise exception
+ if request.show_exceptions?
+ render_exception(request, exception)
else
- render_exception(env, exception)
+ raise exception
end
end
private
- def render_exception(env, exception)
- wrapper = ExceptionWrapper.new(env, exception)
+ def render_exception(request, exception)
+ backtrace_cleaner = request.get_header 'action_dispatch.backtrace_cleaner'
+ wrapper = ExceptionWrapper.new(backtrace_cleaner, exception)
status = wrapper.status_code
- env["action_dispatch.exception"] = wrapper.exception
- env["action_dispatch.original_path"] = env["PATH_INFO"]
- env["PATH_INFO"] = "/#{status}"
- response = @exceptions_app.call(env)
+ request.set_header "action_dispatch.exception", wrapper.exception
+ request.set_header "action_dispatch.original_path", request.path_info
+ request.path_info = "/#{status}"
+ response = @exceptions_app.call(request.env)
response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response
rescue Exception => failsafe_error
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb
index 0c7caef25d..47f475559a 100644
--- a/actionpack/lib/action_dispatch/middleware/ssl.rb
+++ b/actionpack/lib/action_dispatch/middleware/ssl.rb
@@ -1,72 +1,129 @@
module ActionDispatch
+ # This middleware is added to the stack when `config.force_ssl = true`.
+ # It does three jobs to enforce secure HTTP requests:
+ #
+ # 1. TLS redirect. http:// requests are permanently redirected to https://
+ # with the same URL host, path, etc. Pass `:host` and/or `:port` to
+ # modify the destination URL. This is always enabled.
+ #
+ # 2. Secure cookies. Sets the `secure` flag on cookies to tell browsers they
+ # mustn't be sent along with http:// requests. This is always enabled.
+ #
+ # 3. HTTP Strict Transport Security (HSTS). Tells the browser to remember
+ # this site as TLS-only and automatically redirect non-TLS requests.
+ # Enabled by default. Pass `hsts: false` to disable.
+ #
+ # Configure HSTS with `hsts: { … }`:
+ # * `expires`: How long, in seconds, these settings will stick. Defaults to
+ # `180.days` (recommended). The minimum required to qualify for browser
+ # preload lists is `18.weeks`.
+ # * `subdomains`: Set to `true` to tell the browser to apply these settings
+ # to all subdomains. This protects your cookies from interception by a
+ # vulnerable site on a subdomain. Defaults to `false`.
+ # * `preload`: Advertise that this site may be included in browsers'
+ # preloaded HSTS lists. HSTS protects your site on every visit *except the
+ # first visit* since it hasn't seen your HSTS header yet. To close this
+ # gap, browser vendors include a baked-in list of HSTS-enabled sites.
+ # Go to https://hstspreload.appspot.com to submit your site for inclusion.
+ #
+ # Disabling HSTS: To turn off HSTS, omitting the header is not enough.
+ # Browsers will remember the original HSTS directive until it expires.
+ # Instead, use the header to tell browsers to expire HSTS immediately.
+ # Setting `hsts: false` is a shortcut for `hsts: { expires: 0 }`.
class SSL
- YEAR = 31536000
+ # Default to 180 days, the low end for https://www.ssllabs.com/ssltest/
+ # and greater than the 18-week requirement for browser preload lists.
+ HSTS_EXPIRES_IN = 15552000
def self.default_hsts_options
- { :expires => YEAR, :subdomains => false }
+ { expires: HSTS_EXPIRES_IN, subdomains: false, preload: false }
end
- def initialize(app, options = {})
+ def initialize(app, redirect: {}, hsts: {}, **options)
@app = app
- @hsts = options.fetch(:hsts, {})
- @hsts = {} if @hsts == true
- @hsts = self.class.default_hsts_options.merge(@hsts) if @hsts
+ if options[:host] || options[:port]
+ ActiveSupport::Deprecation.warn <<-end_warning.strip_heredoc
+ The `:host` and `:port` options are moving within `:redirect`:
+ `config.ssl_options = { redirect: { host: …, port: … }}`.
+ end_warning
+ @redirect = options.slice(:host, :port)
+ else
+ @redirect = redirect
+ end
- @host = options[:host]
- @port = options[:port]
+ @hsts_header = build_hsts_header(normalize_hsts_options(hsts))
end
def call(env)
- request = Request.new(env)
+ request = Request.new env
if request.ssl?
- status, headers, body = @app.call(env)
- headers = hsts_headers.merge(headers)
- flag_cookies_as_secure!(headers)
- [status, headers, body]
+ @app.call(env).tap do |status, headers, body|
+ set_hsts_header! headers
+ flag_cookies_as_secure! headers
+ end
else
- redirect_to_https(request)
+ redirect_to_https request
end
end
private
- def redirect_to_https(request)
- host = @host || request.host
- port = @port || request.port
-
- location = "https://#{host}"
- location << ":#{port}" if port != 80
- location << request.fullpath
-
- headers = { 'Content-Type' => 'text/html', 'Location' => location }
-
- [301, headers, []]
+ def set_hsts_header!(headers)
+ headers['Strict-Transport-Security'.freeze] ||= @hsts_header
end
- # http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02
- def hsts_headers
- if @hsts
- value = "max-age=#{@hsts[:expires].to_i}"
- value += "; includeSubDomains" if @hsts[:subdomains]
- { 'Strict-Transport-Security' => value }
+ def normalize_hsts_options(options)
+ case options
+ # Explicitly disabling HSTS clears the existing setting from browsers
+ # by setting expiry to 0.
+ when false
+ self.class.default_hsts_options.merge(expires: 0)
+ # Default to enabled, with default options.
+ when nil, true
+ self.class.default_hsts_options
else
- {}
+ self.class.default_hsts_options.merge(options)
end
end
+ # http://tools.ietf.org/html/rfc6797#section-6.1
+ def build_hsts_header(hsts)
+ value = "max-age=#{hsts[:expires].to_i}"
+ value << "; includeSubDomains" if hsts[:subdomains]
+ value << "; preload" if hsts[:preload]
+ value
+ end
+
def flag_cookies_as_secure!(headers)
- if cookies = headers['Set-Cookie']
- cookies = cookies.split("\n")
+ if cookies = headers['Set-Cookie'.freeze]
+ cookies = cookies.split("\n".freeze)
- headers['Set-Cookie'] = cookies.map { |cookie|
+ headers['Set-Cookie'.freeze] = cookies.map { |cookie|
if cookie !~ /;\s*secure\s*(;|$)/i
"#{cookie}; secure"
else
cookie
end
- }.join("\n")
+ }.join("\n".freeze)
end
end
+
+ def redirect_to_https(request)
+ [ @redirect.fetch(:status, 301),
+ { 'Content-Type' => 'text/html',
+ 'Location' => https_location_for(request) },
+ @redirect.fetch(:body, []) ]
+ end
+
+ def https_location_for(request)
+ host = @redirect[:host] || request.host
+ port = @redirect[:port] || request.port
+
+ location = "https://#{host}"
+ location << ":#{port}" if port != 80 && port != 443
+ location << request.fullpath
+ location
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb
index bbf734f103..44fc1ee736 100644
--- a/actionpack/lib/action_dispatch/middleware/stack.rb
+++ b/actionpack/lib/action_dispatch/middleware/stack.rb
@@ -4,50 +4,27 @@ require "active_support/dependencies"
module ActionDispatch
class MiddlewareStack
class Middleware
- attr_reader :args, :block, :name, :classcache
+ attr_reader :args, :block, :klass
- def initialize(klass_or_name, *args, &block)
- @klass = nil
-
- if klass_or_name.respond_to?(:name)
- @klass = klass_or_name
- @name = @klass.name
- else
- @name = klass_or_name.to_s
- end
-
- @classcache = ActiveSupport::Dependencies::Reference
- @args, @block = args, block
+ def initialize(klass, args, block)
+ @klass = klass
+ @args = args
+ @block = block
end
- def klass
- @klass || classcache[@name]
- end
+ def name; klass.name; end
- def ==(middleware)
- case middleware
- when Middleware
- klass == middleware.klass
- when Class
- klass == middleware
+ def inspect
+ if klass.is_a?(Class)
+ klass.to_s
else
- normalize(@name) == normalize(middleware)
+ klass.class.to_s
end
end
- def inspect
- klass.to_s
- end
-
def build(app)
klass.new(app, *args, &block)
end
-
- private
-
- def normalize(object)
- object.to_s.strip.sub(/^::/, '')
- end
end
include Enumerable
@@ -75,19 +52,17 @@ module ActionDispatch
middlewares[i]
end
- def unshift(*args, &block)
- middleware = self.class::Middleware.new(*args, &block)
- middlewares.unshift(middleware)
+ def unshift(klass, *args, &block)
+ middlewares.unshift(build_middleware(klass, args, block))
end
def initialize_copy(other)
self.middlewares = other.middlewares.dup
end
- def insert(index, *args, &block)
+ def insert(index, klass, *args, &block)
index = assert_index(index, :before)
- middleware = self.class::Middleware.new(*args, &block)
- middlewares.insert(index, middleware)
+ middlewares.insert(index, build_middleware(klass, args, block))
end
alias_method :insert_before, :insert
@@ -104,26 +79,46 @@ module ActionDispatch
end
def delete(target)
- middlewares.delete target
+ target = get_class target
+ middlewares.delete_if { |m| m.klass == target }
end
- def use(*args, &block)
- middleware = self.class::Middleware.new(*args, &block)
- middlewares.push(middleware)
+ def use(klass, *args, &block)
+ middlewares.push(build_middleware(klass, args, block))
end
- def build(app = nil, &block)
- app ||= block
- raise "MiddlewareStack#build requires an app" unless app
+ def build(app = Proc.new)
middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) }
end
- protected
+ private
def assert_index(index, where)
- i = index.is_a?(Integer) ? index : middlewares.index(index)
+ index = get_class index
+ i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index }
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
i
end
+
+ def get_class(klass)
+ if klass.is_a?(String) || klass.is_a?(Symbol)
+ classcache = ActiveSupport::Dependencies::Reference
+ converted_klass = classcache[klass.to_s]
+ ActiveSupport::Deprecation.warn <<-eowarn
+Passing strings or symbols to the middleware builder is deprecated, please change
+them to actual class references. For example:
+
+ "#{klass}" => #{converted_klass}
+
+ eowarn
+ converted_klass
+ else
+ klass
+ end
+ end
+
+ def build_middleware(klass, args, block)
+ Middleware.new(get_class(klass), args, block)
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index fdd1bc4e69..ea9ab3821d 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -3,32 +3,37 @@ require 'active_support/core_ext/uri'
module ActionDispatch
# This middleware returns a file's contents from disk in the body response.
- # When initialized it can accept an optional 'Cache-Control' header which
- # will be set when a response containing a file's contents is delivered.
+ # When initialized, it can accept optional HTTP headers, which will be set
+ # when a response containing a file's contents is delivered.
#
# This middleware will render the file specified in `env["PATH_INFO"]`
- # where the base path is in the +root+ directory. For example if the +root+
- # is set to `public/` then a request with `env["PATH_INFO"]` of
- # `assets/application.js` will return a response with contents of a file
+ # where the base path is in the +root+ directory. For example, if the +root+
+ # is set to `public/`, then a request with `env["PATH_INFO"]` of
+ # `assets/application.js` will return a response with the contents of a file
# located at `public/assets/application.js` if the file exists. If the file
- # does not exist a 404 "File not Found" response will be returned.
+ # does not exist, a 404 "File not Found" response will be returned.
class FileHandler
- def initialize(root, cache_control)
+ def initialize(root, index: 'index', headers: {})
@root = root.chomp('/')
- @compiled_root = /^#{Regexp.escape(root)}/
- headers = cache_control && { 'Cache-Control' => cache_control }
- @file_server = ::Rack::File.new(@root, headers)
+ @file_server = ::Rack::File.new(@root, headers)
+ @index = index
end
+ # Takes a path to a file. If the file is found, has valid encoding, and has
+ # correct read permissions, the return value is a URI-escaped string
+ # representing the filename. Otherwise, false is returned.
+ #
+ # Used by the `Static` class to check the existence of a valid file
+ # in the server's `public/` directory (see Static#call).
def match?(path)
- path = URI.parser.unescape(path)
+ path = ::Rack::Utils.unescape_path path
return false unless path.valid_encoding?
path = Rack::Utils.clean_path_info path
- paths = [path, "#{path}#{ext}", "#{path}/index#{ext}"]
+ paths = [path, "#{path}#{ext}", "#{path}/#{@index}#{ext}"]
if match = paths.detect { |p|
- path = File.join(@root, p)
+ path = File.join(@root, p.force_encoding('UTF-8'.freeze))
begin
File.file?(path) && File.readable?(path)
rescue SystemCallError
@@ -36,31 +41,35 @@ module ActionDispatch
end
}
- return ::Rack::Utils.escape(match)
+ return ::Rack::Utils.escape_path(match)
end
end
def call(env)
- path = env['PATH_INFO']
+ serve ActionDispatch::Request.new env
+ end
+
+ def serve(request)
+ path = request.path_info
gzip_path = gzip_file_path(path)
- if gzip_path && gzip_encoding_accepted?(env)
- env['PATH_INFO'] = gzip_path
- status, headers, body = @file_server.call(env)
+ if gzip_path && gzip_encoding_accepted?(request)
+ request.path_info = gzip_path
+ status, headers, body = @file_server.call(request.env)
if status == 304
return [status, headers, body]
end
headers['Content-Encoding'] = 'gzip'
headers['Content-Type'] = content_type(path)
else
- status, headers, body = @file_server.call(env)
+ status, headers, body = @file_server.call(request.env)
end
headers['Vary'] = 'Accept-Encoding' if gzip_path
return [status, headers, body]
ensure
- env['PATH_INFO'] = path
+ request.path_info = path
end
private
@@ -69,17 +78,17 @@ module ActionDispatch
end
def content_type(path)
- ::Rack::Mime.mime_type(::File.extname(path), 'text/plain')
+ ::Rack::Mime.mime_type(::File.extname(path), 'text/plain'.freeze)
end
- def gzip_encoding_accepted?(env)
- env['HTTP_ACCEPT_ENCODING'] =~ /\bgzip\b/i
+ def gzip_encoding_accepted?(request)
+ request.accept_encoding =~ /\bgzip\b/i
end
def gzip_file_path(path)
can_gzip_mime = content_type(path) =~ /\A(?:text\/|application\/javascript)/
gzip_path = "#{path}.gz"
- if can_gzip_mime && File.exist?(File.join(@root, ::Rack::Utils.unescape(gzip_path)))
+ if can_gzip_mime && File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path)))
gzip_path
else
false
@@ -88,7 +97,7 @@ module ActionDispatch
end
# This middleware will attempt to return the contents of a file's body from
- # disk in the response. If a file is not found on disk, the request will be
+ # disk in the response. If a file is not found on disk, the request will be
# delegated to the application stack. This middleware is commonly initialized
# to serve assets from a server's `public/` directory.
#
@@ -97,22 +106,30 @@ module ActionDispatch
# produce a directory traversal using this middleware. Only 'GET' and 'HEAD'
# requests will result in a file being returned.
class Static
- def initialize(app, path, cache_control=nil)
+ def initialize(app, path, deprecated_cache_control = :not_set, index: 'index', headers: {})
+ if deprecated_cache_control != :not_set
+ ActiveSupport::Deprecation.warn("The `cache_control` argument is deprecated," \
+ "replaced by `headers: { 'Cache-Control' => #{deprecated_cache_control} }`, " \
+ " and will be removed in Rails 5.1.")
+ headers['Cache-Control'.freeze] = deprecated_cache_control
+ end
+
@app = app
- @file_handler = FileHandler.new(path, cache_control)
+ @file_handler = FileHandler.new(path, index: index, headers: headers)
end
def call(env)
- case env['REQUEST_METHOD']
- when 'GET', 'HEAD'
- path = env['PATH_INFO'].chomp('/')
+ req = ActionDispatch::Request.new env
+
+ if req.get? || req.head?
+ path = req.path_info.chomp('/'.freeze)
if match = @file_handler.match?(path)
- env["PATH_INFO"] = match
- return @file_handler.call(env)
+ req.path_info = match
+ return @file_handler.serve(req)
end
end
- @app.call(env)
+ @app.call(req.env)
end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb
index c1e8b6cae3..5060da9369 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb
@@ -1,6 +1,6 @@
<header>
<h1>
- <%= @exception.original_exception.class.to_s %> in
+ <%= @exception.cause.class.to_s %> in
<%= @request.parameters["controller"].camelize if @request.parameters["controller"] %>#<%= @request.parameters["action"] %>
</h1>
</header>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb
index 77bcd26726..78d52acd96 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb
@@ -1,4 +1,4 @@
-<%= @exception.original_exception.class.to_s %> in <%= @request.parameters["controller"].camelize if @request.parameters["controller"] %>#<%= @request.parameters["action"] %>
+<%= @exception.cause.class.to_s %> in <%= @request.parameters["controller"].camelize if @request.parameters["controller"] %>#<%= @request.parameters["action"] %>
Showing <%= @exception.file_name %> where line #<%= @exception.line_number %> raised:
<%= @exception.message %>
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb
index 973627f106..9e7fcbd849 100644
--- a/actionpack/lib/action_dispatch/request/session.rb
+++ b/actionpack/lib/action_dispatch/request/session.rb
@@ -1,56 +1,56 @@
require 'rack/session/abstract/id'
module ActionDispatch
- class Request < Rack::Request
+ class Request
# Session is responsible for lazily loading the session from store.
class Session # :nodoc:
- ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc:
- ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc:
+ ENV_SESSION_KEY = Rack::RACK_SESSION # :nodoc:
+ ENV_SESSION_OPTIONS_KEY = Rack::RACK_SESSION_OPTIONS # :nodoc:
# Singleton object used to determine if an optional param wasn't specified
Unspecified = Object.new
-
- def self.create(store, env, default_options)
- session_was = find env
- session = Request::Session.new(store, env)
+
+ # Creates a session hash, merging the properties of the previous session if any
+ def self.create(store, req, default_options)
+ session_was = find req
+ session = Request::Session.new(store, req)
session.merge! session_was if session_was
- set(env, session)
- Options.set(env, Request::Session::Options.new(store, env, default_options))
+ set(req, session)
+ Options.set(req, Request::Session::Options.new(store, default_options))
session
end
- def self.find(env)
- env[ENV_SESSION_KEY]
+ def self.find(req)
+ req.get_header ENV_SESSION_KEY
end
- def self.set(env, session)
- env[ENV_SESSION_KEY] = session
+ def self.set(req, session)
+ req.set_header ENV_SESSION_KEY, session
end
class Options #:nodoc:
- def self.set(env, options)
- env[ENV_SESSION_OPTIONS_KEY] = options
+ def self.set(req, options)
+ req.set_header ENV_SESSION_OPTIONS_KEY, options
end
- def self.find(env)
- env[ENV_SESSION_OPTIONS_KEY]
+ def self.find(req)
+ req.get_header ENV_SESSION_OPTIONS_KEY
end
- def initialize(by, env, default_options)
+ def initialize(by, default_options)
@by = by
- @env = env
@delegate = default_options.dup
end
def [](key)
- if key == :id
- @delegate.fetch(key) {
- @delegate[:id] = @by.send(:extract_session_id, @env)
- }
- else
- @delegate[key]
- end
+ @delegate[key]
+ end
+
+ def id(req)
+ @delegate.fetch(:id) {
+ @by.send(:extract_session_id, req)
+ }
end
def []=(k,v); @delegate[k] = v; end
@@ -58,38 +58,40 @@ module ActionDispatch
def values_at(*args); @delegate.values_at(*args); end
end
- def initialize(by, env)
+ def initialize(by, req)
@by = by
- @env = env
+ @req = req
@delegate = {}
@loaded = false
@exists = nil # we haven't checked yet
end
def id
- options[:id]
+ options.id(@req)
end
def options
- Options.find @env
+ Options.find @req
end
def destroy
clear
options = self.options || {}
- new_sid = @by.send(:destroy_session, @env, options[:id], options)
- options[:id] = new_sid # Reset session id with a new value or nil
+ @by.send(:delete_session, @req, options.id(@req), options)
# Load the new sid to be written with the response
@loaded = false
load_for_write!
end
+ # Returns value of the key stored in the session or
+ # nil if the given key is not found in the session.
def [](key)
load_for_read!
@delegate[key.to_s]
end
+ # Returns true if the session has the given key or false.
def has_key?(key)
load_for_read!
@delegate.key?(key.to_s)
@@ -97,39 +99,69 @@ module ActionDispatch
alias :key? :has_key?
alias :include? :has_key?
+ # Returns keys of the session as Array.
def keys
@delegate.keys
end
+ # Returns values of the session as Array.
def values
@delegate.values
end
+ # Writes given value to given key of the session.
def []=(key, value)
load_for_write!
@delegate[key.to_s] = value
end
+ # Clears the session.
def clear
load_for_write!
@delegate.clear
end
+ # Returns the session as Hash.
def to_hash
load_for_read!
@delegate.dup.delete_if { |_,v| v.nil? }
end
+ # Updates the session with given Hash.
+ #
+ # session.to_hash
+ # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2"}
+ #
+ # session.update({ "foo" => "bar" })
+ # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2", "foo" => "bar"}
+ #
+ # session.to_hash
+ # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2", "foo" => "bar"}
def update(hash)
load_for_write!
@delegate.update stringify_keys(hash)
end
+ # Deletes given key from the session.
def delete(key)
load_for_write!
@delegate.delete key.to_s
end
+ # Returns value of given key from the session, or raises +KeyError+
+ # if can't find given key in case of not setted dafault value.
+ # Returns default value if specified.
+ #
+ # session.fetch(:foo)
+ # # => KeyError: key not found: "foo"
+ #
+ # session.fetch(:foo, :bar)
+ # # => :bar
+ #
+ # session.fetch(:foo) do
+ # :bar
+ # end
+ # # => :bar
def fetch(key, default=Unspecified, &block)
load_for_read!
if default == Unspecified
@@ -149,7 +181,7 @@ module ActionDispatch
def exists?
return @exists unless @exists.nil?
- @exists = @by.send(:session_exists?, @env)
+ @exists = @by.send(:session_exists?, @req)
end
def loaded?
@@ -177,7 +209,7 @@ module ActionDispatch
end
def load!
- id, session = @by.load_session @env
+ id, session = @by.load_session @req
options[:id] = id
@delegate.replace(stringify_keys(session))
@loaded = true
diff --git a/actionpack/lib/action_dispatch/request/utils.rb b/actionpack/lib/action_dispatch/request/utils.rb
index 1c9371d89c..bb3df3c311 100644
--- a/actionpack/lib/action_dispatch/request/utils.rb
+++ b/actionpack/lib/action_dispatch/request/utils.rb
@@ -1,28 +1,64 @@
module ActionDispatch
- class Request < Rack::Request
+ class Request
class Utils # :nodoc:
mattr_accessor :perform_deep_munge
self.perform_deep_munge = true
- class << self
- # Remove nils from the params hash
- def deep_munge(hash, keys = [])
- return hash unless perform_deep_munge
+ def self.normalize_encode_params(params)
+ if perform_deep_munge
+ NoNilParamEncoder.normalize_encode_params params
+ else
+ ParamEncoder.normalize_encode_params params
+ end
+ end
+
+ def self.check_param_encoding(params)
+ case params
+ when Array
+ params.each { |element| check_param_encoding(element) }
+ when Hash
+ params.each_value { |value| check_param_encoding(value) }
+ when String
+ unless params.valid_encoding?
+ # Raise Rack::Utils::InvalidParameterError for consistency with Rack.
+ # ActionDispatch::Request#GET will re-raise as a BadRequest error.
+ raise Rack::Utils::InvalidParameterError, "Non UTF-8 value: #{params}"
+ end
+ end
+ end
- hash.each do |k, v|
- keys << k
- case v
- when Array
- v.grep(Hash) { |x| deep_munge(x, keys) }
- v.compact!
- when Hash
- deep_munge(v, keys)
+ class ParamEncoder # :nodoc:
+ # Convert nested Hash to HashWithIndifferentAccess.
+ #
+ def self.normalize_encode_params(params)
+ case params
+ when Array
+ handle_array params
+ when Hash
+ if params.has_key?(:tempfile)
+ ActionDispatch::Http::UploadedFile.new(params)
+ else
+ params.each_with_object({}) do |(key, val), new_hash|
+ new_hash[key] = normalize_encode_params(val)
+ end.with_indifferent_access
end
- keys.pop
+ else
+ params
end
+ end
+
+ def self.handle_array(params)
+ params.map! { |el| normalize_encode_params(el) }
+ end
+ end
- hash
+ # Remove nils from the params hash
+ class NoNilParamEncoder < ParamEncoder # :nodoc:
+ def self.handle_array(params)
+ list = super
+ list.compact!
+ list
end
end
end
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index ce03164ca9..59c3f9248f 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -1,8 +1,3 @@
-# encoding: UTF-8
-require 'active_support/core_ext/object/to_param'
-require 'active_support/core_ext/regexp'
-require 'active_support/dependencies/autoload'
-
module ActionDispatch
# The routing module provides URL rewriting in native Ruby. It's a way to
# redirect incoming requests to controllers and actions. This replaces
@@ -58,7 +53,7 @@ module ActionDispatch
# resources :posts, :comments
# end
#
- # Alternately, you can add prefixes to your path without using a separate
+ # Alternatively, you can add prefixes to your path without using a separate
# directory by using +scope+. +scope+ takes additional options which
# apply to all enclosed routes.
#
@@ -151,6 +146,7 @@ module ActionDispatch
# get 'geocode/:postalcode' => :show, constraints: {
# postalcode: /\d{5}(-\d{4})?/
# }
+ # end
#
# Constraints can include the 'ignorecase' and 'extended syntax' regular
# expression modifiers:
@@ -232,7 +228,6 @@ module ActionDispatch
# def send_to_jail
# get '/jail'
# assert_response :success
- # assert_template "jail/front"
# end
#
# def goes_to_login
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index c513737fc2..f3a5268d2e 100644
--- a/actionpack/lib/action_dispatch/routing/inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -16,10 +16,6 @@ module ActionDispatch
app.app
end
- def verb
- super.source.gsub(/[$^]/, '')
- end
-
def path
super.spec.to_s
end
@@ -45,7 +41,7 @@ module ActionDispatch
end
def internal?
- controller.to_s =~ %r{\Arails/(info|mailers|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}\z}
+ controller.to_s =~ %r{\Arails/(info|mailers|welcome)}
end
def engine?
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 34b5b48f3a..7c0404ca62 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,10 +1,8 @@
-require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/module/remove_method'
-require 'active_support/inflector'
+require 'active_support/core_ext/regexp'
require 'action_dispatch/routing/redirection'
require 'action_dispatch/routing/endpoint'
@@ -16,7 +14,10 @@ module ActionDispatch
class Constraints < Endpoint #:nodoc:
attr_reader :app, :constraints
- def initialize(app, constraints, dispatcher_p)
+ SERVE = ->(app, req) { app.serve req }
+ CALL = ->(app, req) { app.call req.env }
+
+ def initialize(app, constraints, strategy)
# Unwrap Constraints objects. I don't actually think it's possible
# to pass a Constraints object to this constructor, but there were
# multiple places that kept testing children of this object. I
@@ -26,12 +27,12 @@ module ActionDispatch
app = app.app
end
- @dispatcher = dispatcher_p
+ @strategy = strategy
@app, @constraints, = app, constraints
end
- def dispatcher?; @dispatcher; end
+ def dispatcher?; @strategy == SERVE; end
def matches?(req)
@constraints.all? do |constraint|
@@ -43,11 +44,7 @@ module ActionDispatch
def serve(req)
return [ 404, {'X-Cascade' => 'pass'}, [] ] unless matches?(req)
- if dispatcher?
- @app.serve req
- else
- @app.call req.env
- end
+ @strategy.call @app, req
end
private
@@ -59,101 +56,168 @@ module ActionDispatch
class Mapping #:nodoc:
ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
- attr_reader :requirements, :conditions, :defaults
- attr_reader :to, :default_controller, :default_action, :as, :anchor
+ attr_reader :requirements, :defaults
+ attr_reader :to, :default_controller, :default_action
+ attr_reader :required_defaults, :ast
- def self.build(scope, set, path, as, options)
+ def self.build(scope, set, ast, controller, default_action, to, via, formatted, options_constraints, anchor, options)
options = scope[:options].merge(options) if scope[:options]
- options.delete :only
- options.delete :except
- options.delete :shallow_path
- options.delete :shallow_prefix
- options.delete :shallow
+ defaults = (scope[:defaults] || {}).dup
+ scope_constraints = scope[:constraints] || {}
- defaults = (scope[:defaults] || {}).merge options.delete(:defaults) || {}
+ new set, ast, defaults, controller, default_action, scope[:module], to, formatted, scope_constraints, scope[:blocks] || [], via, options_constraints, anchor, options
+ end
- new scope, set, path, defaults, as, options
+ def self.check_via(via)
+ if via.empty?
+ msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
+ "If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
+ "If you want to expose your action to GET, use `get` in the router:\n" \
+ " Instead of: match \"controller#action\"\n" \
+ " Do: get \"controller#action\""
+ raise ArgumentError, msg
+ end
+ via
end
- def initialize(scope, set, path, defaults, as, options)
- @requirements, @conditions = {}, {}
- @defaults = defaults
- @set = set
+ def self.normalize_path(path, format)
+ path = Mapper.normalize_path(path)
- @to = options.delete :to
- @default_controller = options.delete(:controller) || scope[:controller]
- @default_action = options.delete(:action) || scope[:action]
- @as = as
- @anchor = options.delete :anchor
+ if format == true
+ "#{path}.:format"
+ elsif optional_format?(path, format)
+ "#{path}(.:format)"
+ else
+ path
+ end
+ end
- formatted = options.delete :format
- via = Array(options.delete(:via) { [] })
- options_constraints = options.delete :constraints
+ def self.optional_format?(path, format)
+ format != false && !path.include?(':format') && !path.end_with?('/')
+ end
- path = normalize_path! path, formatted
- ast = path_ast path
- path_params = path_params ast
+ def initialize(set, ast, defaults, controller, default_action, modyoule, to, formatted, scope_constraints, blocks, via, options_constraints, anchor, options)
+ @defaults = defaults
+ @set = set
+
+ @to = to
+ @default_controller = controller
+ @default_action = default_action
+ @ast = ast
+ @anchor = anchor
+ @via = via
- options = normalize_options!(options, formatted, path_params, ast, scope[:module])
+ path_params = ast.find_all(&:symbol?).map(&:to_sym)
+ options = add_wildcard_options(options, formatted, ast)
- split_constraints(path_params, scope[:constraints]) if scope[:constraints]
- constraints = constraints(options, path_params)
+ options = normalize_options!(options, path_params, modyoule)
- split_constraints path_params, constraints
+ split_options = constraints(options, path_params)
- @blocks = blocks(options_constraints, scope[:blocks])
+ constraints = scope_constraints.merge Hash[split_options[:constraints] || []]
if options_constraints.is_a?(Hash)
- split_constraints path_params, options_constraints
- options_constraints.each do |key, default|
- if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
- @defaults[key] ||= default
- end
- end
+ @defaults = Hash[options_constraints.find_all { |key, default|
+ URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
+ }].merge @defaults
+ @blocks = blocks
+ constraints.merge! options_constraints
+ else
+ @blocks = blocks(options_constraints)
end
- normalize_format!(formatted)
+ requirements, conditions = split_constraints path_params, constraints
+ verify_regexp_requirements requirements.map(&:last).grep(Regexp)
+
+ formats = normalize_format(formatted)
- @conditions[:path_info] = path
- @conditions[:parsed_path_info] = ast
+ @requirements = formats[:requirements].merge Hash[requirements]
+ @conditions = Hash[conditions]
+ @defaults = formats[:defaults].merge(@defaults).merge(normalize_defaults(options))
- add_request_method(via, @conditions)
- normalize_defaults!(options)
+ @required_defaults = (split_options[:required_defaults] || []).map(&:first)
end
- def to_route
- [ app(@blocks), conditions, requirements, defaults, as, anchor ]
+ def make_route(name, precedence)
+ route = Journey::Route.new(name,
+ application,
+ path,
+ conditions,
+ required_defaults,
+ defaults,
+ request_method,
+ precedence)
+
+ route
end
- private
+ def application
+ app(@blocks)
+ end
+
+ def path
+ build_path @ast, requirements, @anchor
+ end
- def normalize_path!(path, format)
- path = Mapper.normalize_path(path)
+ def conditions
+ build_conditions @conditions, @set.request_class
+ end
- if format == true
- "#{path}.:format"
- elsif optional_format?(path, format)
- "#{path}(.:format)"
- else
- path
- end
- end
+ def build_conditions(current_conditions, request_class)
+ conditions = current_conditions.dup
- def optional_format?(path, format)
- format != false && !path.include?(':format') && !path.end_with?('/')
+ conditions.keep_if do |k, _|
+ request_class.public_method_defined?(k)
end
+ end
+ private :build_conditions
+
+ def request_method
+ @via.map { |x| Journey::Route.verb_matcher(x) }
+ end
+ private :request_method
+
+ JOINED_SEPARATORS = SEPARATORS.join # :nodoc:
+
+ def build_path(ast, requirements, anchor)
+ pattern = Journey::Path::Pattern.new(ast, requirements, JOINED_SEPARATORS, anchor)
+
+ # Get all the symbol nodes followed by literals that are not the
+ # dummy node.
+ symbols = ast.find_all { |n|
+ n.cat? && n.left.symbol? && n.right.cat? && n.right.left.literal?
+ }.map(&:left)
- def normalize_options!(options, formatted, path_params, path_ast, modyoule)
+ # Get all the symbol nodes preceded by literals.
+ symbols.concat ast.find_all { |n|
+ n.cat? && n.left.literal? && n.right.cat? && n.right.left.symbol?
+ }.map { |n| n.right.left }
+
+ symbols.each { |x|
+ x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
+ }
+
+ pattern
+ end
+ private :build_path
+
+
+ private
+ def add_wildcard_options(options, formatted, path_ast)
# Add a constraint for wildcard route to make it non-greedy and match the
# optional format part of the route by default
if formatted != false
- path_ast.grep(Journey::Nodes::Star) do |node|
- options[node.name.to_sym] ||= /.+?/
- end
+ path_ast.grep(Journey::Nodes::Star).each_with_object({}) { |node, hash|
+ hash[node.name.to_sym] ||= /.+?/
+ }.merge options
+ else
+ options
end
+ end
+ def normalize_options!(options, path_params, modyoule)
if path_params.include?(:controller)
raise ArgumentError, ":controller segment is not allowed within a namespace block" if modyoule
@@ -178,74 +242,54 @@ module ActionDispatch
end
def split_constraints(path_params, constraints)
- constraints.each_pair do |key, requirement|
- if path_params.include?(key) || key == :controller
- verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
- @requirements[key] = requirement
- else
- @conditions[key] = requirement
- end
- end
- end
-
- def normalize_format!(formatted)
- if formatted == true
- @requirements[:format] ||= /.+/
- elsif Regexp === formatted
- @requirements[:format] = formatted
- @defaults[:format] = nil
- elsif String === formatted
- @requirements[:format] = Regexp.compile(formatted)
- @defaults[:format] = formatted
+ constraints.partition do |key, requirement|
+ path_params.include?(key) || key == :controller
end
end
- def verify_regexp_requirement(requirement)
- if requirement.source =~ ANCHOR_CHARACTERS_REGEX
- raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
- end
-
- if requirement.multiline?
- raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
+ def normalize_format(formatted)
+ case formatted
+ when true
+ { requirements: { format: /.+/ },
+ defaults: {} }
+ when Regexp
+ { requirements: { format: formatted },
+ defaults: { format: nil } }
+ when String
+ { requirements: { format: Regexp.compile(formatted) },
+ defaults: { format: formatted } }
+ else
+ { requirements: { }, defaults: { } }
end
end
- def normalize_defaults!(options)
- options.each_pair do |key, default|
- unless Regexp === default
- @defaults[key] = default
+ def verify_regexp_requirements(requirements)
+ requirements.each do |requirement|
+ if requirement.source =~ ANCHOR_CHARACTERS_REGEX
+ raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
end
- end
- end
- def verify_callable_constraint(callable_constraint)
- unless callable_constraint.respond_to?(:call) || callable_constraint.respond_to?(:matches?)
- raise ArgumentError, "Invalid constraint: #{callable_constraint.inspect} must respond to :call or :matches?"
+ if requirement.multiline?
+ raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
+ end
end
end
- def add_request_method(via, conditions)
- return if via == [:all]
-
- if via.empty?
- msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
- "If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
- "If you want to expose your action to GET, use `get` in the router:\n" \
- " Instead of: match \"controller#action\"\n" \
- " Do: get \"controller#action\""
- raise ArgumentError, msg
- end
-
- conditions[:request_method] = via.map { |m| m.to_s.dasherize.upcase }
+ def normalize_defaults(options)
+ Hash[options.reject { |_, default| Regexp === default }]
end
def app(blocks)
- if to.respond_to?(:call)
- Constraints.new(to, blocks, false)
- elsif blocks.any?
- Constraints.new(dispatcher(defaults), blocks, true)
+ if to.is_a?(Class) && to < ActionController::Metal
+ Routing::RouteSet::StaticDispatcher.new to
else
- dispatcher(defaults)
+ if to.respond_to?(:call)
+ Constraints.new(to, blocks, Constraints::CALL)
+ elsif blocks.any?
+ Constraints.new(dispatcher(defaults.key?(:controller)), blocks, Constraints::SERVE)
+ else
+ dispatcher(defaults.key?(:controller))
+ end
end
end
@@ -303,40 +347,29 @@ module ActionDispatch
yield
end
- def blocks(options_constraints, scope_blocks)
- if options_constraints && !options_constraints.is_a?(Hash)
- verify_callable_constraint(options_constraints)
- [options_constraints]
- else
- scope_blocks || []
+ def blocks(callable_constraint)
+ unless callable_constraint.respond_to?(:call) || callable_constraint.respond_to?(:matches?)
+ raise ArgumentError, "Invalid constraint: #{callable_constraint.inspect} must respond to :call or :matches?"
end
+ [callable_constraint]
end
def constraints(options, path_params)
- constraints = {}
- required_defaults = []
- options.each_pair do |key, option|
+ options.group_by do |key, option|
if Regexp === option
- constraints[key] = option
+ :constraints
else
- required_defaults << key unless path_params.include?(key)
+ if path_params.include?(key)
+ :path_params
+ else
+ :required_defaults
+ end
end
end
- @conditions[:required_defaults] = required_defaults
- constraints
- end
-
- def path_params(ast)
- ast.grep(Journey::Nodes::Symbol).map { |n| n.name.to_sym }
- end
-
- def path_ast(path)
- parser = Journey::Parser.new
- parser.parse path
end
- def dispatcher(defaults)
- @set.dispatcher defaults
+ def dispatcher(raise_on_name_error)
+ Routing::RouteSet::Dispatcher.new raise_on_name_error
end
end
@@ -368,7 +401,8 @@ module ActionDispatch
# because this means it will be matched first. As this is the most popular route
# of most Rails applications, this is beneficial.
def root(options = {})
- match '/', { :as => :root, :via => :get }.merge!(options)
+ name = has_named_route?(:root) ? nil : :root
+ match '/', { as: name, via: :get }.merge!(options)
end
# Matches a url pattern to one or more routes.
@@ -418,7 +452,7 @@ module ActionDispatch
# A pattern can also point to a +Rack+ endpoint i.e. anything that
# responds to +call+:
#
- # match 'photos/:id', to: lambda {|hash| [200, {}, ["Coming soon"]] }, via: :get
+ # match 'photos/:id', to: -> (hash) { [200, {}, ["Coming soon"]] }, via: :get
# match 'photos/:id', to: PhotoRackApp, via: :get
# # Yes, controller actions are just rack endpoints
# match 'photos/:id', to: PhotosController.action(:show), via: :get
@@ -443,6 +477,21 @@ module ActionDispatch
# dynamic segment used to generate the routes).
# You can access that segment from your controller using
# <tt>params[<:param>]</tt>.
+ # In your router:
+ #
+ # resources :user, param: :name
+ #
+ # You can override <tt>ActiveRecord::Base#to_param</tt> of a related
+ # model to construct a URL:
+ #
+ # class User < ActiveRecord::Base
+ # def to_param
+ # name
+ # end
+ # end
+ #
+ # user = User.find_by(name: 'Phusion')
+ # user_path(user) # => "/users/Phusion"
#
# [:path]
# The path prefix for the routes.
@@ -470,7 +519,7 @@ module ActionDispatch
# +call+ or a string representing a controller's action.
#
# match 'path', to: 'controller#action', via: :get
- # match 'path', to: lambda { |env| [200, {}, ["Success!"]] }, via: :get
+ # match 'path', to: -> (env) { [200, {}, ["Success!"]] }, via: :get
# match 'path', to: RackApp, via: :get
#
# [:on]
@@ -588,7 +637,7 @@ module ActionDispatch
# Query if the following named route was already defined.
def has_named_route?(name)
- @set.named_routes.routes[name.to_sym]
+ @set.named_routes.key? name
end
private
@@ -616,6 +665,7 @@ module ActionDispatch
super(options)
else
prefix_options = options.slice(*_route.segment_keys)
+ prefix_options[:relative_url_root] = ''.freeze
# we must actually delete prefix segment keys to avoid passing them to next url_for
_route.segment_keys.each { |k| options.delete(k) }
_routes.url_helpers.send("#{name}_path", prefix_options)
@@ -670,7 +720,11 @@ module ActionDispatch
def map_method(method, args, &block)
options = args.extract_options!
options[:via] = method
- match(*args, options, &block)
+ if options.key?(:defaults)
+ defaults(options.delete(:defaults)) { match(*args, options, &block) }
+ else
+ match(*args, options, &block)
+ end
self
end
end
@@ -773,8 +827,8 @@ module ActionDispatch
end
if options[:constraints].is_a?(Hash)
- defaults = options[:constraints].select do
- |k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
+ defaults = options[:constraints].select do |k, v|
+ URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
end
(options[:defaults] ||= {}).reverse_merge!(defaults)
@@ -782,16 +836,25 @@ module ActionDispatch
block, options[:constraints] = options[:constraints], {}
end
+ if options.key?(:only) || options.key?(:except)
+ scope[:action_options] = { only: options.delete(:only),
+ except: options.delete(:except) }
+ end
+
+ if options.key? :anchor
+ raise ArgumentError, 'anchor is ignored unless passed to `match`'
+ end
+
@scope.options.each do |option|
if option == :blocks
value = block
elsif option == :options
value = options
else
- value = options.delete(option)
+ value = options.delete(option) { POISON }
end
- if value
+ unless POISON == value
scope[option] = send("merge_#{option}_scope", @scope[option], value)
end
end
@@ -803,14 +866,18 @@ module ActionDispatch
@scope = @scope.parent
end
+ POISON = Object.new # :nodoc:
+
# Scopes routes to a specific controller
#
# controller "food" do
- # match "bacon", action: "bacon"
+ # match "bacon", action: :bacon, via: :get
# end
- def controller(controller, options={})
- options[:controller] = controller
- scope(options) { yield }
+ def controller(controller)
+ @scope = @scope.new(controller: controller)
+ yield
+ ensure
+ @scope = @scope.parent
end
# Scopes routes to a specific namespace. For example:
@@ -856,13 +923,14 @@ module ActionDispatch
defaults = {
module: path,
- path: options.fetch(:path, path),
as: options.fetch(:as, path),
shallow_path: options.fetch(:path, path),
shallow_prefix: options.fetch(:as, path)
}
- scope(defaults.merge!(options)) { yield }
+ path_scope(options.delete(:path) { path }) do
+ scope(defaults.merge!(options)) { yield }
+ end
end
# === Parameter Restriction
@@ -899,7 +967,7 @@ module ActionDispatch
#
# Requests to routes can be constrained based on specific criteria:
#
- # constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
+ # constraints(-> (req) { req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
# resources :iphones
# end
#
@@ -930,7 +998,10 @@ module ActionDispatch
# end
# Using this, the +:id+ parameter here will default to 'home'.
def defaults(defaults = {})
- scope(:defaults => defaults) { yield }
+ @scope = @scope.new(defaults: merge_defaults_scope(@scope[:defaults], defaults))
+ yield
+ ensure
+ @scope = @scope.parent
end
private
@@ -962,6 +1033,14 @@ module ActionDispatch
child
end
+ def merge_via_scope(parent, child) #:nodoc:
+ child
+ end
+
+ def merge_format_scope(parent, child) #:nodoc:
+ child
+ end
+
def merge_path_names_scope(parent, child) #:nodoc:
merge_options_scope(parent, child)
end
@@ -981,16 +1060,12 @@ module ActionDispatch
end
def merge_options_scope(parent, child) #:nodoc:
- (parent || {}).except(*override_keys(child)).merge!(child)
+ (parent || {}).merge(child)
end
def merge_shallow_scope(parent, child) #:nodoc:
child ? true : false
end
-
- def override_keys(child) #:nodoc:
- child.key?(:only) || child.key?(:except) ? [:only, :except] : []
- end
end
# Resource routing allows you to quickly declare all of the common routes
@@ -1040,27 +1115,34 @@ module ActionDispatch
CANONICAL_ACTIONS = %w(index create new show update destroy)
class Resource #:nodoc:
- attr_reader :controller, :path, :options, :param
+ attr_reader :controller, :path, :param
- def initialize(entities, options = {})
+ def initialize(entities, api_only, shallow, options = {})
@name = entities.to_s
@path = (options[:path] || @name).to_s
@controller = (options[:controller] || @name).to_s
@as = options[:as]
@param = (options[:param] || :id).to_sym
@options = options
- @shallow = false
+ @shallow = shallow
+ @api_only = api_only
+ @only = options.delete :only
+ @except = options.delete :except
end
def default_actions
- [:index, :create, :new, :show, :update, :destroy, :edit]
+ if @api_only
+ [:index, :create, :show, :update, :destroy]
+ else
+ [:index, :create, :new, :show, :update, :destroy, :edit]
+ end
end
def actions
- if only = @options[:only]
- Array(only).map(&:to_sym)
- elsif except = @options[:except]
- default_actions - Array(except).map(&:to_sym)
+ if @only
+ Array(@only).map(&:to_sym)
+ elsif @except
+ default_actions - Array(@except).map(&:to_sym)
else
default_actions
end
@@ -1087,7 +1169,7 @@ module ActionDispatch
end
def resource_scope
- { :controller => controller }
+ controller
end
alias :collection_scope :path
@@ -1110,17 +1192,15 @@ module ActionDispatch
"#{path}/:#{nested_param}"
end
- def shallow=(value)
- @shallow = value
- end
-
def shallow?
@shallow
end
+
+ def singleton?; false; end
end
class SingletonResource < Resource #:nodoc:
- def initialize(entities, options)
+ def initialize(entities, api_only, shallow, options)
super
@as = nil
@controller = (options[:controller] || plural).to_s
@@ -1128,7 +1208,11 @@ module ActionDispatch
end
def default_actions
- [:show, :create, :update, :destroy, :new, :edit]
+ if @api_only
+ [:show, :create, :update, :destroy]
+ else
+ [:show, :create, :update, :destroy, :new, :edit]
+ end
end
def plural
@@ -1144,6 +1228,8 @@ module ActionDispatch
alias :member_scope :path
alias :nested_scope :path
+
+ def singleton?; true; end
end
def resources_path_names(options)
@@ -1178,20 +1264,23 @@ module ActionDispatch
return self
end
- resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
- yield if block_given?
+ with_scope_level(:resource) do
+ options = apply_action_options options
+ resource_scope(SingletonResource.new(resources.pop, api_only?, @scope[:shallow], options)) do
+ yield if block_given?
- concerns(options[:concerns]) if options[:concerns]
+ concerns(options[:concerns]) if options[:concerns]
- collection do
- post :create
- end if parent_resource.actions.include?(:create)
+ collection do
+ post :create
+ end if parent_resource.actions.include?(:create)
- new do
- get :new
- end if parent_resource.actions.include?(:new)
+ new do
+ get :new
+ end if parent_resource.actions.include?(:new)
- set_member_mappings_for_resource
+ set_member_mappings_for_resource
+ end
end
self
@@ -1336,21 +1425,24 @@ module ActionDispatch
return self
end
- resource_scope(:resources, Resource.new(resources.pop, options)) do
- yield if block_given?
+ with_scope_level(:resources) do
+ options = apply_action_options options
+ resource_scope(Resource.new(resources.pop, api_only?, @scope[:shallow], options)) do
+ yield if block_given?
- concerns(options[:concerns]) if options[:concerns]
+ concerns(options[:concerns]) if options[:concerns]
- collection do
- get :index if parent_resource.actions.include?(:index)
- post :create if parent_resource.actions.include?(:create)
- end
+ collection do
+ get :index if parent_resource.actions.include?(:index)
+ post :create if parent_resource.actions.include?(:create)
+ end
- new do
- get :new
- end if parent_resource.actions.include?(:new)
+ new do
+ get :new
+ end if parent_resource.actions.include?(:new)
- set_member_mappings_for_resource
+ set_member_mappings_for_resource
+ end
end
self
@@ -1374,7 +1466,7 @@ module ActionDispatch
end
with_scope_level(:collection) do
- scope(parent_resource.collection_scope) do
+ path_scope(parent_resource.collection_scope) do
yield
end
end
@@ -1398,9 +1490,11 @@ module ActionDispatch
with_scope_level(:member) do
if shallow?
- shallow_scope(parent_resource.member_scope) { yield }
+ shallow_scope {
+ path_scope(parent_resource.member_scope) { yield }
+ }
else
- scope(parent_resource.member_scope) { yield }
+ path_scope(parent_resource.member_scope) { yield }
end
end
end
@@ -1411,7 +1505,7 @@ module ActionDispatch
end
with_scope_level(:new) do
- scope(parent_resource.new_scope(action_path(:new))) do
+ path_scope(parent_resource.new_scope(action_path(:new))) do
yield
end
end
@@ -1424,9 +1518,15 @@ module ActionDispatch
with_scope_level(:nested) do
if shallow? && shallow_nesting_depth >= 1
- shallow_scope(parent_resource.nested_scope, nested_options) { yield }
+ shallow_scope do
+ path_scope(parent_resource.nested_scope) do
+ scope(nested_options) { yield }
+ end
+ end
else
- scope(parent_resource.nested_scope, nested_options) { yield }
+ path_scope(parent_resource.nested_scope) do
+ scope(nested_options) { yield }
+ end
end
end
end
@@ -1441,18 +1541,22 @@ module ActionDispatch
end
def shallow
- scope(:shallow => true) do
- yield
- end
+ @scope = @scope.new(shallow: true)
+ yield
+ ensure
+ @scope = @scope.parent
end
def shallow?
- parent_resource.instance_of?(Resource) && @scope[:shallow]
+ !parent_resource.singleton? && @scope[:shallow]
end
- # match 'path' => 'controller#action'
- # match 'path', to: 'controller#action'
- # match 'path', 'otherpath', on: :member, via: :get
+ # Matches a url pattern to one or more routes.
+ # For more information, see match[rdoc-ref:Base#match].
+ #
+ # match 'path' => 'controller#action', via: patch
+ # match 'path', to: 'controller#action', via: :post
+ # match 'path', 'otherpath', on: :member, via: :get
def match(path, *rest)
if rest.empty? && Hash === path
options = path
@@ -1478,8 +1582,6 @@ module ActionDispatch
paths = [path] + rest
end
- options[:anchor] = true unless options.key?(:anchor)
-
if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
end
@@ -1488,48 +1590,85 @@ module ActionDispatch
options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
end
- paths.each do |_path|
+ controller = options.delete(:controller) || @scope[:controller]
+ option_path = options.delete :path
+ to = options.delete :to
+ via = Mapping.check_via Array(options.delete(:via) {
+ @scope[:via]
+ })
+ formatted = options.delete(:format) { @scope[:format] }
+ anchor = options.delete(:anchor) { true }
+ options_constraints = options.delete(:constraints) || {}
+
+ path_types = paths.group_by(&:class)
+ path_types.fetch(String, []).each do |_path|
route_options = options.dup
- route_options[:path] ||= _path if _path.is_a?(String)
+ if _path && option_path
+ ActiveSupport::Deprecation.warn <<-eowarn
+Specifying strings for both :path and the route path is deprecated. Change things like this:
+
+ match #{_path.inspect}, :path => #{option_path.inspect}
- path_without_format = _path.to_s.sub(/\(\.:format\)$/, '')
- if using_match_shorthand?(path_without_format, route_options)
- route_options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
- route_options[:to].tr!("-", "_")
+to this:
+
+ match #{option_path.inspect}, :as => #{_path.inspect}, :action => #{path.inspect}
+ eowarn
+ route_options[:action] = _path
+ route_options[:as] = _path
+ _path = option_path
end
+ to = get_to_from_path(_path, to, route_options[:action])
+ decomposed_match(_path, controller, route_options, _path, to, via, formatted, anchor, options_constraints)
+ end
- decomposed_match(_path, route_options)
+ path_types.fetch(Symbol, []).each do |action|
+ route_options = options.dup
+ decomposed_match(action, controller, route_options, option_path, to, via, formatted, anchor, options_constraints)
end
+
self
end
- def using_match_shorthand?(path, options)
- path && (options[:to] || options[:action]).nil? && path =~ %r{^/?[-\w]+/[-\w/]+$}
+ def get_to_from_path(path, to, action)
+ return to if to || action
+
+ path_without_format = path.sub(/\(\.:format\)$/, '')
+ if using_match_shorthand?(path_without_format)
+ path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1').tr("-", "_")
+ else
+ nil
+ end
+ end
+
+ def using_match_shorthand?(path)
+ path =~ %r{^/?[-\w]+/[-\w/]+$}
end
- def decomposed_match(path, options) # :nodoc:
+ def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc:
if on = options.delete(:on)
- send(on) { decomposed_match(path, options) }
+ send(on) { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) }
else
case @scope.scope_level
when :resources
- nested { decomposed_match(path, options) }
+ nested { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) }
when :resource
- member { decomposed_match(path, options) }
+ member { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) }
else
- add_route(path, options)
+ add_route(path, controller, options, _path, to, via, formatted, anchor, options_constraints)
end
end
end
- def add_route(action, options) # :nodoc:
- path = path_for_action(action, options.delete(:path))
+ def add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc:
+ path = path_for_action(action, _path)
raise ArgumentError, "path is required" if path.blank?
- action = action.to_s.dup
+ action = action.to_s
+
+ default_action = options.delete(:action) || @scope[:action]
if action =~ /^[\w\-\/]+$/
- options[:action] ||= action.tr('-', '_') unless action.include?("/")
+ default_action ||= action.tr('-', '_') unless action.include?("/")
else
action = nil
end
@@ -1540,9 +1679,11 @@ module ActionDispatch
name_for_action(options.delete(:as), action)
end
- mapping = Mapping.build(@scope, @set, URI.parser.escape(path), as, options)
- app, conditions, requirements, defaults, as, anchor = mapping.to_route
- @set.add_route(app, conditions, requirements, defaults, as, anchor)
+ path = Mapping.normalize_path URI.parser.escape(path), formatted
+ ast = Journey::Parser.parse path
+
+ mapping = Mapping.build(@scope, @set, ast, controller, default_action, to, via, formatted, options_constraints, anchor, options)
+ @set.add_route(mapping, ast, as, anchor)
end
def root(path, options={})
@@ -1556,7 +1697,7 @@ module ActionDispatch
if @scope.resources?
with_scope_level(:root) do
- scope(parent_resource.path) do
+ path_scope(parent_resource.path) do
super(options)
end
end
@@ -1601,23 +1742,20 @@ module ActionDispatch
return true
end
- unless action_options?(options)
- options.merge!(scope_action_options) if scope_action_options?
- end
-
false
end
- def action_options?(options) #:nodoc:
- options[:only] || options[:except]
+ def apply_action_options(options) # :nodoc:
+ return options if action_options? options
+ options.merge scope_action_options
end
- def scope_action_options? #:nodoc:
- @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
+ def action_options?(options) #:nodoc:
+ options[:only] || options[:except]
end
def scope_action_options #:nodoc:
- @scope[:options].slice(:only, :except)
+ @scope[:action_options] || {}
end
def resource_scope? #:nodoc:
@@ -1632,18 +1770,6 @@ module ActionDispatch
@scope.nested?
end
- def with_exclusive_scope
- begin
- @scope = @scope.new(:as => nil, :path => nil)
-
- with_scope_level(:exclusive) do
- yield
- end
- ensure
- @scope = @scope.parent
- end
- end
-
def with_scope_level(kind)
@scope = @scope.new_level(kind)
yield
@@ -1651,16 +1777,11 @@ module ActionDispatch
@scope = @scope.parent
end
- def resource_scope(kind, resource) #:nodoc:
- resource.shallow = @scope[:shallow]
+ def resource_scope(resource) #:nodoc:
@scope = @scope.new(:scope_level_resource => resource)
- @nesting.push(resource)
- with_scope_level(kind) do
- scope(parent_resource.resource_scope) { yield }
- end
+ controller(resource.resource_scope) { yield }
ensure
- @nesting.pop
@scope = @scope.parent
end
@@ -1673,12 +1794,10 @@ module ActionDispatch
options
end
- def nesting_depth #:nodoc:
- @nesting.size
- end
-
def shallow_nesting_depth #:nodoc:
- @nesting.select(&:shallow?).size
+ @scope.find_all { |node|
+ node.frame[:scope_level_resource]
+ }.count { |node| node.frame[:scope_level_resource].shallow? }
end
def param_constraint? #:nodoc:
@@ -1693,27 +1812,28 @@ module ActionDispatch
resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
end
- def shallow_scope(path, options = {}) #:nodoc:
+ def shallow_scope #:nodoc:
scope = { :as => @scope[:shallow_prefix],
:path => @scope[:shallow_path] }
@scope = @scope.new scope
- scope(path, options) { yield }
+ yield
ensure
@scope = @scope.parent
end
def path_for_action(action, path) #:nodoc:
- if path.blank? && canonical_action?(action)
+ return "#{@scope[:path]}/#{path}" if path
+
+ if canonical_action?(action)
@scope[:path].to_s
else
- "#{@scope[:path]}/#{action_path(action, path)}"
+ "#{@scope[:path]}/#{action_path(action)}"
end
end
- def action_path(name, path = nil) #:nodoc:
- name = name.to_sym if name.is_a?(String)
- path || @scope[:path_names][name] || name.to_s
+ def action_path(name) #:nodoc:
+ @scope[:path_names][name.to_sym] || name
end
def prefix_name_for_action(as, action) #:nodoc:
@@ -1747,7 +1867,7 @@ module ActionDispatch
# and return nil in case it isn't. Otherwise, we pass the invalid name
# forward so the underlying router engine treats it and raises an exception.
if as.nil?
- candidate unless candidate !~ /\A[_a-z]/i || @set.named_routes.key?(candidate)
+ candidate unless candidate !~ /\A[_a-z]/i || has_named_route?(candidate)
else
candidate
end
@@ -1765,6 +1885,18 @@ module ActionDispatch
delete :destroy if parent_resource.actions.include?(:destroy)
end
end
+
+ def api_only?
+ @set.api_only?
+ end
+ private
+
+ def path_scope(path)
+ @scope = @scope.new(path: merge_path_scope(@scope[:path], path))
+ yield
+ ensure
+ @scope = @scope.parent
+ end
end
# Routing Concerns allow you to declare common routes that can be reused
@@ -1875,14 +2007,14 @@ module ActionDispatch
class Scope # :nodoc:
OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module,
:controller, :action, :path_names, :constraints,
- :shallow, :blocks, :defaults, :options]
+ :shallow, :blocks, :defaults, :via, :format, :options]
RESOURCE_SCOPES = [:resource, :resources]
RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
attr_reader :parent, :scope_level
- def initialize(hash, parent = {}, scope_level = nil)
+ def initialize(hash, parent = NULL, scope_level = nil)
@hash = hash
@parent = parent
@scope_level = scope_level
@@ -1930,27 +2062,34 @@ module ActionDispatch
end
def new_level(level)
- self.class.new(self, self, level)
- end
-
- def fetch(key, &block)
- @hash.fetch(key, &block)
+ self.class.new(frame, self, level)
end
def [](key)
- @hash.fetch(key) { @parent[key] }
+ scope = find { |node| node.frame.key? key }
+ scope && scope.frame[key]
end
- def []=(k,v)
- @hash[k] = v
+ include Enumerable
+
+ def each
+ node = self
+ loop do
+ break if node.equal? NULL
+ yield node
+ node = node.parent
+ end
end
+
+ def frame; @hash; end
+
+ NULL = Scope.new(nil, nil)
end
def initialize(set) #:nodoc:
@set = set
@scope = Scope.new({ :path_names => @set.resources_path_names })
@concerns = {}
- @nesting = []
end
include Base
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
index 3c1c4fadf6..d6987f4d09 100644
--- a/actionpack/lib/action_dispatch/routing/redirection.rb
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -24,7 +24,7 @@ module ActionDispatch
def serve(req)
req.check_path_parameters!
uri = URI.parse(path(req.path_parameters, req))
-
+
unless uri.host
if relative_path?(uri.path)
uri.path = "#{req.script_name}/#{uri.path}"
@@ -32,7 +32,7 @@ module ActionDispatch
uri.path = req.script_name.empty? ? "/" : req.script_name
end
end
-
+
uri.scheme ||= req.scheme
uri.host ||= req.host
uri.port ||= req.port unless req.standard_port?
@@ -124,7 +124,7 @@ module ActionDispatch
url_options[:script_name] = request.script_name
end
end
-
+
ActionDispatch::Http::URL.url_for url_options
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 0f3734dd74..c4228df925 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -1,6 +1,4 @@
require 'action_dispatch/journey'
-require 'forwardable'
-require 'thread_safe'
require 'active_support/concern'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
@@ -21,65 +19,45 @@ module ActionDispatch
alias inspect to_s
class Dispatcher < Routing::Endpoint
- def initialize(defaults)
- @defaults = defaults
- @controller_class_names = ThreadSafe::Cache.new
+ def initialize(raise_on_name_error)
+ @raise_on_name_error = raise_on_name_error
end
def dispatcher?; true; end
def serve(req)
- req.check_path_parameters!
- params = req.path_parameters
-
- prepare_params!(params)
-
- # Just raise undefined constant errors if a controller was specified as default.
- unless controller = controller(params, @defaults.key?(:controller))
+ params = req.path_parameters
+ controller = controller req
+ res = controller.make_response! req
+ dispatch(controller, params[:action], req, res)
+ rescue NameError => e
+ if @raise_on_name_error
+ raise ActionController::RoutingError, e.message, e.backtrace
+ else
return [404, {'X-Cascade' => 'pass'}, []]
end
-
- dispatch(controller, params[:action], req.env)
- end
-
- def prepare_params!(params)
- normalize_controller!(params)
- merge_default_action!(params)
- end
-
- # If this is a default_controller (i.e. a controller specified by the user)
- # we should raise an error in case it's not found, because it usually means
- # a user error. However, if the controller was retrieved through a dynamic
- # segment, as in :controller(/:action), we should simply return nil and
- # delegate the control back to Rack cascade. Besides, if this is not a default
- # controller, it means we should respect the @scope[:module] parameter.
- def controller(params, default_controller=true)
- if params && params.key?(:controller)
- controller_param = params[:controller]
- controller_reference(controller_param)
- end
- rescue NameError => e
- raise ActionController::RoutingError, e.message, e.backtrace if default_controller
end
private
- def controller_reference(controller_param)
- const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
- ActiveSupport::Dependencies.constantize(const_name)
+ def controller(req)
+ req.controller_class
end
- def dispatch(controller, action, env)
- controller.action(action).call(env)
+ def dispatch(controller, action, req, res)
+ controller.dispatch(action, req, res)
end
+ end
- def normalize_controller!(params)
- params[:controller] = params[:controller].underscore if params.key?(:controller)
+ class StaticDispatcher < Dispatcher
+ def initialize(controller_class)
+ super(false)
+ @controller_class = controller_class
end
- def merge_default_action!(params)
- params[:action] ||= 'index'
- end
+ private
+
+ def controller(_); @controller_class; end
end
# A NamedRouteCollection instance is a collection of named routes, and also
@@ -88,6 +66,7 @@ module ActionDispatch
class NamedRouteCollection
include Enumerable
attr_reader :routes, :url_helpers_module, :path_helpers_module
+ private :routes
def initialize
@routes = {}
@@ -142,6 +121,7 @@ module ActionDispatch
end
def key?(name)
+ return unless name
routes.key? name.to_sym
end
@@ -199,9 +179,9 @@ module ActionDispatch
private
def optimized_helper(args)
- params = parameterize_args(args) { |k|
+ params = parameterize_args(args) do
raise_generation_error(args)
- }
+ end
@route.format params
end
@@ -226,7 +206,7 @@ module ActionDispatch
params = parameterize_args(args) { |missing_key|
missing_keys << missing_key
}
- constraints = Hash[@route.requirements.merge(params).sort]
+ constraints = Hash[@route.requirements.merge(params).sort_by{|k,v| k.to_s}]
message = "No route matches #{constraints.inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}"
@@ -267,9 +247,13 @@ module ActionDispatch
path_params -= controller_options.keys
path_params -= result.keys
end
- path_params -= inner_options.keys
- path_params.take(args.size).each do |param|
- result[param] = args.shift
+ inner_options.each_key do |key|
+ path_params.delete(key)
+ end
+
+ args.each_with_index do |arg, index|
+ param = path_params[index]
+ result[param] = arg if param
end
end
@@ -319,17 +303,23 @@ module ActionDispatch
end
def self.new_with_config(config)
+ route_set_config = DEFAULT_CONFIG
+
+ # engines apparently don't have this set
if config.respond_to? :relative_url_root
- new Config.new config.relative_url_root
- else
- # engines apparently don't have this set
- new
+ route_set_config.relative_url_root = config.relative_url_root
end
+
+ if config.respond_to? :api_only
+ route_set_config.api_only = config.api_only
+ end
+
+ new route_set_config
end
- Config = Struct.new :relative_url_root
+ Config = Struct.new :relative_url_root, :api_only
- DEFAULT_CONFIG = Config.new(nil)
+ DEFAULT_CONFIG = Config.new(nil, false)
def initialize(config = DEFAULT_CONFIG)
self.named_routes = NamedRouteCollection.new
@@ -345,17 +335,26 @@ module ActionDispatch
@set = Journey::Routes.new
@router = Journey::Router.new @set
- @formatter = Journey::Formatter.new @set
+ @formatter = Journey::Formatter.new self
end
def relative_url_root
@config.relative_url_root
end
+ def api_only?
+ @config.api_only
+ end
+
def request_class
ActionDispatch::Request
end
+ def make_request(env)
+ request_class.new env
+ end
+ private :make_request
+
def draw(&block)
clear! unless @disable_clear_and_finalize
eval_block(block)
@@ -372,10 +371,6 @@ module ActionDispatch
end
def eval_block(block)
- if block.arity == 1
- raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
- "Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
- end
mapper = Mapper.new(self)
if default_scope
mapper.with_default_scope(default_scope, &block)
@@ -399,10 +394,6 @@ module ActionDispatch
@prepend.each { |blk| eval_block(blk) }
end
- def dispatcher(defaults)
- Routing::RouteSet::Dispatcher.new(defaults)
- end
-
module MountedHelpers
extend ActiveSupport::Concern
include UrlFor
@@ -498,7 +489,7 @@ module ActionDispatch
routes.empty?
end
- def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
+ def add_route(mapping, path_ast, name, anchor)
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
if name && named_routes[name]
@@ -509,74 +500,17 @@ module ActionDispatch
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
end
- path = conditions.delete :path_info
- ast = conditions.delete :parsed_path_info
- path = build_path(path, ast, requirements, anchor)
- conditions = build_conditions(conditions, path.names.map(&:to_sym))
-
- route = @set.add_route(app, path, conditions, defaults, name)
+ route = @set.add_route(name, mapping)
named_routes[name] = route if name
route
end
- def build_path(path, ast, requirements, anchor)
- strexp = Journey::Router::Strexp.new(
- ast,
- path,
- requirements,
- SEPARATORS,
- anchor)
-
- pattern = Journey::Path::Pattern.new(strexp)
-
- builder = Journey::GTG::Builder.new pattern.spec
-
- # Get all the symbol nodes followed by literals that are not the
- # dummy node.
- symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
- builder.followpos(n).first.literal?
- }
-
- # Get all the symbol nodes preceded by literals.
- symbols.concat pattern.spec.find_all(&:literal?).map { |n|
- builder.followpos(n).first
- }.find_all(&:symbol?)
-
- symbols.each { |x|
- x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
- }
-
- pattern
- end
- private :build_path
-
- def build_conditions(current_conditions, path_values)
- conditions = current_conditions.dup
-
- # Rack-Mount requires that :request_method be a regular expression.
- # :request_method represents the HTTP verb that matches this route.
- #
- # Here we munge values before they get sent on to rack-mount.
- verbs = conditions[:request_method] || []
- unless verbs.empty?
- conditions[:request_method] = %r[^#{verbs.join('|')}$]
- end
-
- conditions.keep_if do |k, _|
- k == :action || k == :controller || k == :required_defaults ||
- request_class.public_method_defined?(k) || path_values.include?(k)
- end
- end
- private :build_conditions
-
class Generator
PARAMETERIZE = lambda do |name, value|
if name == :controller
value
- elsif value.is_a?(Array)
- value.map(&:to_param).join('/')
- elsif param = value.to_param
- param
+ else
+ value.to_param
end
end
@@ -584,8 +518,8 @@ module ActionDispatch
def initialize(named_route, options, recall, set)
@named_route = named_route
- @options = options.dup
- @recall = recall.dup
+ @options = options
+ @recall = recall
@set = set
normalize_recall!
@@ -607,7 +541,7 @@ module ActionDispatch
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
if !named_route_exists? || segment_keys.include?(key)
- @options[key] = @recall.delete(key)
+ @options[key] = @recall[key]
end
end
end
@@ -661,12 +595,18 @@ module ActionDispatch
# Remove leading slashes from controllers
def normalize_controller!
- @options[:controller] = controller.sub(%r{^/}, '') if controller
+ if controller
+ if controller.start_with?("/".freeze)
+ @options[:controller] = controller[1..-1]
+ else
+ @options[:controller] = controller
+ end
+ end
end
# Move 'index' action from options to recall
def normalize_action!
- if @options[:action] == 'index'
+ if @options[:action] == 'index'.freeze
@recall[:action] = @options.delete(:action)
end
end
@@ -711,14 +651,18 @@ module ActionDispatch
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
:trailing_slash, :anchor, :params, :only_path, :script_name,
- :original_script_name]
+ :original_script_name, :relative_url_root]
def optimize_routes_generation?
default_url_options.empty?
end
def find_script_name(options)
- options.delete(:script_name) || relative_url_root || ''
+ options.delete(:script_name) || find_relative_url_root(options) || ''
+ end
+
+ def find_relative_url_root(options)
+ options.delete(:relative_url_root) || relative_url_root
end
def path_for(options, route_name = nil)
@@ -764,7 +708,7 @@ module ActionDispatch
end
def call(env)
- req = request_class.new(env)
+ req = make_request(env)
req.path_info = Journey::Router::Utils.normalize_path(req.path_info)
@router.serve(req)
end
@@ -780,7 +724,7 @@ module ActionDispatch
raise ActionController::RoutingError, e.message
end
- req = request_class.new(env)
+ req = make_request(env)
@router.recognize(req) do |route, params|
params.merge!(extras)
params.each do |key, value|
@@ -793,14 +737,13 @@ module ActionDispatch
req.path_parameters = old_params.merge params
app = route.app
if app.matches?(req) && app.dispatcher?
- dispatcher = app.app
-
- if dispatcher.controller(params, false)
- dispatcher.prepare_params!(params)
- return params
- else
+ begin
+ req.controller_class
+ rescue NameError
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
end
+
+ return req.path_parameters
end
end
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index eb554ec383..b6c031dcf4 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -1,7 +1,7 @@
module ActionDispatch
module Routing
# In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
- # is also possible: an URL can be generated from one of your routing definitions.
+ # is also possible: a URL can be generated from one of your routing definitions.
# URL generation functionality is centralized in this module.
#
# See ActionDispatch::Routing for general information about routing and routes.rb.
@@ -52,9 +52,11 @@ module ActionDispatch
# argument.
#
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
- # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
- # in full. However, mailers don't have hostname information, and that's why you'll still
- # have to specify the <tt>:host</tt> argument when generating URLs in mailers.
+ # So within mailers, you only have to type +url_for+ instead of 'ActionController::UrlFor#url_for'
+ # in full. However, mailers don't have hostname information, and you still have to provide
+ # the +:host+ argument or set the default host that will be used in all mailers using the
+ # configuration option +config.action_mailer.default_url_options+. For more information on
+ # url_for in mailers read the ActionMailer#Base documentation.
#
#
# == URL generation for named routes
@@ -147,6 +149,20 @@ module ActionDispatch
# # => 'http://somehost.org/myapp/tasks/testing'
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
# # => '/myapp/tasks/testing'
+ #
+ # Missing routes keys may be filled in from the current request's parameters
+ # (e.g. +:controller+, +:action+, +:id+ and any other parameters that are
+ # placed in the path). Given that the current action has been reached
+ # through `GET /users/1`:
+ #
+ # url_for(only_path: true) # => '/users/1'
+ # url_for(only_path: true, action: 'edit') # => '/users/1/edit'
+ # url_for(only_path: true, action: 'edit', id: 2) # => '/users/2/edit'
+ #
+ # Notice that no +:id+ parameter was provided to the first +url_for+ call
+ # and the helper used the one from the route's path. Any path parameter
+ # implicitly used by +url_for+ can always be overwritten like shown on the
+ # last +url_for+ calls.
def url_for(options = nil)
case options
when nil
@@ -155,12 +171,17 @@ module ActionDispatch
route_name = options.delete :use_route
_routes.url_for(options.symbolize_keys.reverse_merge!(url_options),
route_name)
+ when ActionController::Parameters
+ route_name = options.delete :use_route
+ _routes.url_for(options.to_unsafe_h.symbolize_keys.
+ reverse_merge!(url_options), route_name)
when String
options
when Symbol
HelperMethodBuilder.url.handle_string_call self, options
when Array
- polymorphic_url(options, options.extract_options!)
+ components = options.dup
+ polymorphic_url(components, components.extract_options!)
when Class
HelperMethodBuilder.url.handle_class_call self, options
else
diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb
index 21b3b89d22..fae266273e 100644
--- a/actionpack/lib/action_dispatch/testing/assertions.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions.rb
@@ -12,7 +12,7 @@ module ActionDispatch
include Rails::Dom::Testing::Assertions
def html_document
- @html_document ||= if @response.content_type === Mime::XML
+ @html_document ||= if @response.content_type.to_s =~ /xml\z/
Nokogiri::XML::Document.parse(@response.body)
else
Nokogiri::HTML::Document.parse(@response.body)
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index 13a72220b3..eab20b075d 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -3,6 +3,13 @@ module ActionDispatch
module Assertions
# A small suite of assertions that test responses from \Rails applications.
module ResponseAssertions
+ RESPONSE_PREDICATES = { # :nodoc:
+ success: :successful?,
+ missing: :not_found?,
+ redirect: :redirection?,
+ error: :server_error?,
+ }
+
# Asserts that the response is one of the following types:
#
# * <tt>:success</tt> - Status code was in the 200-299 range
@@ -14,17 +21,15 @@ module ActionDispatch
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
#
- # # assert that the response was a redirection
+ # # Asserts that the response was a redirection
# assert_response :redirect
#
- # # assert that the response code was status code 401 (unauthorized)
+ # # Asserts that the response code was status code 401 (unauthorized)
# assert_response 401
def assert_response(type, message = nil)
- message ||= "Expected response to be a <#{type}>, but was <#{@response.response_code}>"
-
if Symbol === type
if [:success, :missing, :redirect, :error].include?(type)
- assert @response.send("#{type}?"), message
+ assert_predicate @response, RESPONSE_PREDICATES[type], message
else
code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
if code.nil?
@@ -37,20 +42,20 @@ module ActionDispatch
end
end
- # Assert that the redirection options passed in match those of the redirect called in the latest action.
+ # Asserts that the redirection options passed in match those of the redirect called in the latest action.
# This match can be partial, such that <tt>assert_redirected_to(controller: "weblog")</tt> will also
# match the redirection of <tt>redirect_to(controller: "weblog", action: "show")</tt> and so on.
#
- # # assert that the redirection was to the "index" action on the WeblogController
+ # # Asserts that the redirection was to the "index" action on the WeblogController
# assert_redirected_to controller: "weblog", action: "index"
#
- # # assert that the redirection was to the named route login_url
+ # # Asserts that the redirection was to the named route login_url
# assert_redirected_to login_url
#
- # # assert that the redirection was to the url for @customer
+ # # Asserts that the redirection was to the url for @customer
# assert_redirected_to @customer
#
- # # asserts that the redirection matches the regular expression
+ # # Asserts that the redirection matches the regular expression
# assert_redirected_to %r(\Ahttp://example.org)
def assert_redirected_to(options = {}, message=nil)
assert_response(:redirect, message)
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index c94eea9134..78ef860548 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -14,14 +14,14 @@ module ActionDispatch
# requiring a specific HTTP method. The hash should contain a :path with the incoming request path
# and a :method containing the required HTTP verb.
#
- # # assert that POSTing to /items will call the create action on ItemsController
+ # # Asserts that POSTing to /items will call the create action on ItemsController
# assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
#
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
- # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
+ # to assert that values in the query string will end up in the params hash correctly. To test query strings you must use the
# extras argument, appending the query string on the path directly will not work. For example:
#
- # # assert that a path of '/items/list/1?view=print' returns the correct options
+ # # Asserts that a path of '/items/list/1?view=print' returns the correct options
# assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
#
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
@@ -86,8 +86,8 @@ module ActionDispatch
end
# Load routes.rb if it hasn't been loaded.
- generated_path, extra_keys = @routes.generate_extras(options, defaults)
- found_extras = options.reject { |k, _| ! extra_keys.include? k }
+ generated_path, query_string_keys = @routes.generate_extras(options, defaults)
+ found_extras = options.reject { |k, _| ! query_string_keys.include? k }
msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
assert_equal(extras, found_extras, msg)
@@ -104,13 +104,13 @@ module ActionDispatch
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
# +message+ parameter allows you to specify a custom error message to display upon failure.
#
- # # Assert a basic route: a controller with the default action (index)
+ # # Asserts a basic route: a controller with the default action (index)
# assert_routing '/home', controller: 'home', action: 'index'
#
# # Test a route generated with a specific controller, action, and parameter (id)
# assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23
#
- # # Assert a basic route (controller + default action), with an error message if it fails
+ # # Asserts a basic route (controller + default action), with an error message if it fails
# assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'
#
# # Tests a route, providing a defaults hash
@@ -165,7 +165,7 @@ module ActionDispatch
# ROUTES TODO: These assertions should really work in an integration context
def method_missing(selector, *args, &block)
- if defined?(@controller) && @controller && @routes && @routes.named_routes.route_defined?(selector)
+ if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
@controller.send(selector, *args, &block)
else
super
@@ -183,7 +183,7 @@ module ActionDispatch
end
# Assume given controller
- request = ActionController::TestRequest.new
+ request = ActionController::TestRequest.create
if path =~ %r{://}
fail_on(URI::InvalidURIError, msg) do
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 9390e2937a..790f9ea5d2 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -2,6 +2,7 @@ require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/string/strip'
require 'rack/test'
require 'minitest'
@@ -80,7 +81,7 @@ module ActionDispatch
#
# xhr :get, '/feed', params: { since: 201501011400 }
def xml_http_request(request_method, path, *args)
- if kwarg_request?(*args)
+ if kwarg_request?(args)
params, headers, env = args.first.values_at(:params, :headers, :env)
else
params = args[0]
@@ -130,35 +131,35 @@ module ActionDispatch
# Performs a GET request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def get_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`get_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`get_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:get, path, *args)
end
# Performs a POST request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def post_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`post_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`post_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:post, path, *args)
end
# Performs a PATCH request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def patch_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`patch_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`patch_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:patch, path, *args)
end
# Performs a PUT request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def put_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`put_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`put_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:put, path, *args)
end
# Performs a DELETE request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
def delete_via_redirect(path, *args)
- ActiveSupport::Deprecation.warn('`delete_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ ActiveSupport::Deprecation.warn('`delete_via_redirect` is deprecated and will be removed in Rails 5.1. Please use follow_redirect! manually after the request call for the same behavior.')
request_via_redirect(:delete, path, *args)
end
end
@@ -290,16 +291,16 @@ module ActionDispatch
end
def process_with_kwargs(http_method, path, *args)
- if kwarg_request?(*args)
+ if kwarg_request?(args)
process(http_method, path, *args)
else
- non_kwarg_request_warning if args.present?
+ non_kwarg_request_warning if args.any?
process(http_method, path, { params: args[0], headers: args[1] })
end
end
REQUEST_KWARGS = %i(params headers env xhr)
- def kwarg_request?(*args)
+ def kwarg_request?(args)
args[0].respond_to?(:keys) && args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
end
@@ -324,7 +325,11 @@ module ActionDispatch
if path =~ %r{://}
location = URI.parse(path)
https! URI::HTTPS === location if location.scheme
- host! "#{location.host}:#{location.port}" if location.host
+ if url_host = location.host
+ default = Rack::Request::DEFAULT_PORTS[location.scheme]
+ url_host += ":#{location.port}" if default != location.port
+ host! url_host
+ end
path = location.query ? "#{location.path}?#{location.query}" : location.path
end
@@ -349,15 +354,15 @@ module ActionDispatch
if xhr
headers ||= {}
headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
- headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ headers['HTTP_ACCEPT'] ||= [Mime[:js], Mime[:html], Mime[:xml], 'text/xml', '*/*'].join(', ')
end
# this modifies the passed request_env directly
if headers.present?
- Http::Headers.new(request_env).merge!(headers)
+ Http::Headers.from_hash(request_env).merge!(headers)
end
if env.present?
- Http::Headers.new(request_env).merge!(env)
+ Http::Headers.from_hash(request_env).merge!(env)
end
session = Rack::Test::Session.new(_mock_session)
@@ -373,7 +378,7 @@ module ActionDispatch
@html_document = nil
@url_options = nil
- @controller = session.last_request.env['action_controller.instance']
+ @controller = @request.controller_instance
response.status
end
@@ -390,7 +395,7 @@ module ActionDispatch
attr_reader :app
- def before_setup
+ def before_setup # :nodoc:
@app = nil
@integration_session = nil
super
@@ -428,7 +433,6 @@ module ActionDispatch
# reset the html_document variable, except for cookies/assigns calls
unless method == 'cookies' || method == 'assigns'
@html_document = nil
- reset_template_assertion
end
integration_session.__send__(method, *args).tap do
@@ -583,7 +587,7 @@ module ActionDispatch
# https!(false)
# get "/articles/all"
# assert_response :success
- # assert assigns(:articles)
+ # assert_select 'h1', 'Articles'
# end
# end
#
@@ -622,7 +626,7 @@ module ActionDispatch
# def browses_site
# get "/products/all"
# assert_response :success
- # assert assigns(:products)
+ # assert_select 'h1', 'Products'
# end
# end
#
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
index 630e6a9b78..c28d701b48 100644
--- a/actionpack/lib/action_dispatch/testing/test_process.rb
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -5,9 +5,9 @@ require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
module TestProcess
def assigns(key = nil)
- assigns = {}.with_indifferent_access
- @controller.view_assigns.each { |k, v| assigns.regular_writer(k, v) }
- key.nil? ? assigns : assigns[key]
+ raise NoMethodError,
+ "assigns has been extracted to a gem. To continue using it,
+ add `gem 'rails-controller-testing'` to your Gemfile."
end
def session
@@ -19,7 +19,7 @@ module ActionDispatch
end
def cookies
- @request.cookie_jar
+ @cookie_jar ||= Cookies::CookieJar.build(@request, @request.cookies)
end
def redirect_to_url
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index 4b9a088265..ad1a7f7109 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -4,19 +4,22 @@ require 'rack/utils'
module ActionDispatch
class TestRequest < Request
DEFAULT_ENV = Rack::MockRequest.env_for('/',
- 'HTTP_HOST' => 'test.host',
- 'REMOTE_ADDR' => '0.0.0.0',
- 'HTTP_USER_AGENT' => 'Rails Testing'
+ 'HTTP_HOST' => 'test.host',
+ 'REMOTE_ADDR' => '0.0.0.0',
+ 'HTTP_USER_AGENT' => 'Rails Testing',
)
- def self.new(env = {})
- super
+ # 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
+ env["rack.request.cookie_hash"] ||= {}.with_indifferent_access
+ new(default_env.merge(env))
end
- def initialize(env = {})
- env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
- super(default_env.merge(env))
+ def self.default_env
+ DEFAULT_ENV
end
+ private_class_method :default_env
def request_method=(method)
@env['REQUEST_METHOD'] = method.to_s.upcase
@@ -62,17 +65,5 @@ module ActionDispatch
@env.delete('action_dispatch.request.accepts')
@env['HTTP_ACCEPT'] = Array(mime_types).collect(&:to_s).join(",")
end
-
- alias :rack_cookies :cookies
-
- def cookies
- @cookies ||= {}.with_indifferent_access
- end
-
- private
-
- def default_env
- DEFAULT_ENV
- end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb
index a9b88ac5fd..4b79a90242 100644
--- a/actionpack/lib/action_dispatch/testing/test_response.rb
+++ b/actionpack/lib/action_dispatch/testing/test_response.rb
@@ -7,7 +7,7 @@ module ActionDispatch
# See Response for more information on controller response objects.
class TestResponse < Response
def self.from_response(response)
- new response.status, response.headers, response.body, default_headers: nil
+ new response.status, response.headers, response.body
end
# Was the response successful?
@@ -16,9 +16,6 @@ module ActionDispatch
# Was the URL not found?
alias_method :missing?, :not_found?
- # Were we redirected?
- alias_method :redirect?, :redirection?
-
# Was there a server-side error?
alias_method :error?, :server_error?
end
diff --git a/actionpack/test/abstract/collector_test.rb b/actionpack/test/abstract/collector_test.rb
index fc59bf19c4..edbb84d462 100644
--- a/actionpack/test/abstract/collector_test.rb
+++ b/actionpack/test/abstract/collector_test.rb
@@ -53,9 +53,9 @@ module AbstractController
collector.html
collector.text(:foo)
collector.js(:bar) { :baz }
- assert_equal [Mime::HTML, [], nil], collector.responses[0]
- assert_equal [Mime::TEXT, [:foo], nil], collector.responses[1]
- assert_equal [Mime::JS, [:bar]], collector.responses[2][0,2]
+ assert_equal [Mime[:html], [], nil], collector.responses[0]
+ assert_equal [Mime[:text], [:foo], nil], collector.responses[1]
+ assert_equal [Mime[:js], [:bar]], collector.responses[2][0,2]
assert_equal :baz, collector.responses[2][2].call
end
end
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb
index 8289252dfc..1435928578 100644
--- a/actionpack/test/abstract/translation_test.rb
+++ b/actionpack/test/abstract/translation_test.rb
@@ -24,7 +24,6 @@ module AbstractController
},
},
})
- @controller.stubs(action_name: :index)
end
def test_action_controller_base_responds_to_translate
@@ -44,25 +43,34 @@ module AbstractController
end
def test_lazy_lookup
- assert_equal 'bar', @controller.t('.foo')
+ @controller.stub :action_name, :index do
+ assert_equal 'bar', @controller.t('.foo')
+ end
end
def test_lazy_lookup_with_symbol
- assert_equal 'bar', @controller.t(:'.foo')
+ @controller.stub :action_name, :index do
+ assert_equal 'bar', @controller.t(:'.foo')
+ end
end
def test_lazy_lookup_fallback
- assert_equal 'no_action_tr', @controller.t(:'.no_action')
+ @controller.stub :action_name, :index do
+ assert_equal 'no_action_tr', @controller.t(:'.no_action')
+ end
end
def test_default_translation
- assert_equal 'bar', @controller.t('one.two')
+ @controller.stub :action_name, :index do
+ assert_equal 'bar', @controller.t('one.two')
+ end
end
def test_localize
time, expected = Time.gm(2000), 'Sat, 01 Jan 2000 00:00:00 +0000'
- I18n.stubs(:localize).with(time).returns(expected)
- assert_equal expected, @controller.l(time)
+ I18n.stub :localize, expected do
+ assert_equal expected, @controller.l(time)
+ end
end
end
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 62ff1be5c9..ef7aab72c6 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -14,8 +14,11 @@ silence_warnings do
end
require 'drb'
-require 'drb/unix'
-require 'tempfile'
+begin
+ require 'drb/unix'
+rescue LoadError
+ puts "'drb/unix' is not available"
+end
PROCESS_COUNT = (ENV['N'] || 4).to_i
@@ -38,6 +41,8 @@ module Rails
def env
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "test")
end
+
+ def root; end;
end
end
@@ -59,6 +64,10 @@ FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
+SharedTestRoutes.draw do
+ get ':controller(/:action)'
+end
+
module ActionDispatch
module SharedRoutes
def before_setup
@@ -66,35 +75,10 @@ module ActionDispatch
super
end
end
-
- # Hold off drawing routes until all the possible controller classes
- # have been loaded.
- module DrawOnce
- class << self
- attr_accessor :drew
- end
- self.drew = false
-
- def before_setup
- super
- return if DrawOnce.drew
-
- SharedTestRoutes.draw do
- get ':controller(/:action)'
- end
-
- ActionDispatch::IntegrationTest.app.routes.draw do
- get ':controller(/:action)'
- end
-
- DrawOnce.drew = true
- end
- end
end
module ActiveSupport
class TestCase
- include ActionDispatch::DrawOnce
if RUBY_ENGINE == "ruby" && PROCESS_COUNT > 0
parallelize_me!
end
@@ -115,44 +99,54 @@ class RoutedRackApp
end
class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
- include ActionDispatch::SharedRoutes
-
def self.build_app(routes = nil)
RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware|
- middleware.use "ActionDispatch::ShowExceptions", ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public")
- middleware.use "ActionDispatch::DebugExceptions"
- middleware.use "ActionDispatch::Callbacks"
- middleware.use "ActionDispatch::ParamsParser"
- middleware.use "ActionDispatch::Cookies"
- middleware.use "ActionDispatch::Flash"
- middleware.use "Rack::Head"
+ middleware.use ActionDispatch::ShowExceptions, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public")
+ middleware.use ActionDispatch::DebugExceptions
+ middleware.use ActionDispatch::Callbacks
+ middleware.use ActionDispatch::Cookies
+ middleware.use ActionDispatch::Flash
+ middleware.use Rack::Head
yield(middleware) if block_given?
end
end
self.app = build_app
- # Stub Rails dispatcher so it does not get controller references and
- # simply return the controller#action as Rack::Body.
- class StubDispatcher < ::ActionDispatch::Routing::RouteSet::Dispatcher
- protected
- def controller_reference(controller_param)
- controller_param
+ app.routes.draw do
+ get ':controller(/:action)'
+ end
+
+ class DeadEndRoutes < ActionDispatch::Routing::RouteSet
+ # Stub Rails dispatcher so it does not get controller references and
+ # simply return the controller#action as Rack::Body.
+ class NullController < ::ActionController::Metal
+ def initialize(controller_name)
+ @controller = controller_name
+ end
+
+ def make_response!(request)
+ self.class.make_response! request
+ end
+
+ def dispatch(action, req, res)
+ [200, {'Content-Type' => 'text/html'}, ["#{@controller}##{action}"]]
+ end
+ end
+
+ class NullControllerRequest < DelegateClass(ActionDispatch::Request)
+ def controller_class
+ NullController.new params[:controller]
+ end
end
- def dispatch(controller, action, env)
- [200, {'Content-Type' => 'text/html'}, ["#{controller}##{action}"]]
+ def make_request env
+ NullControllerRequest.new super
end
end
- def self.stub_controllers
- old_dispatcher = ActionDispatch::Routing::RouteSet::Dispatcher
- ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher }
- ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, StubDispatcher }
- yield ActionDispatch::Routing::RouteSet.new
- ensure
- ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher }
- ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, old_dispatcher }
+ def self.stub_controllers(config = ActionDispatch::Routing::RouteSet::DEFAULT_CONFIG)
+ yield DeadEndRoutes.new(config)
end
def with_routing(&block)
@@ -228,6 +222,10 @@ class Rack::TestCase < ActionDispatch::IntegrationTest
end
module ActionController
+ class API
+ extend AbstractController::Railties::RoutesHelpers.with(SharedTestRoutes)
+ end
+
class Base
# This stub emulates the Railtie including the URL helpers from a Rails application
extend AbstractController::Railties::RoutesHelpers.with(SharedTestRoutes)
@@ -338,45 +336,43 @@ module RoutingTestHelpers
end
class TestSet < ActionDispatch::Routing::RouteSet
- attr_reader :strict
-
- def initialize(block, strict = false)
- @block = block
- @strict = strict
- super()
- end
-
- class Dispatcher < ActionDispatch::Routing::RouteSet::Dispatcher
- def initialize(defaults, set, block)
- super(defaults)
+ class Request < DelegateClass(ActionDispatch::Request)
+ def initialize(target, helpers, block, strict)
+ super(target)
+ @helpers = helpers
@block = block
- @set = set
- end
-
- def controller(params, default_controller=true)
- super(params, @set.strict)
+ @strict = strict
end
- def controller_reference(controller_param)
+ def controller_class
+ helpers = @helpers
block = @block
- set = @set
- super if @set.strict
- Class.new(ActionController::Base) {
- include set.url_helpers
+ Class.new(@strict ? super : ActionController::Base) {
+ include helpers
define_method(:process) { |name| block.call(self) }
def to_a; [200, {}, []]; end
}
end
end
- def dispatcher defaults
- TestSet::Dispatcher.new defaults, self, @block
+ attr_reader :strict
+
+ def initialize(block, strict = false)
+ @block = block
+ @strict = strict
+ super()
+ end
+
+ private
+
+ def make_request(env)
+ Request.new super, url_helpers, @block, strict
end
end
end
class ResourcesController < ActionController::Base
- def index() render :nothing => true end
+ def index() head :ok end
alias_method :show, :index
end
@@ -384,13 +380,11 @@ class ThreadsController < ResourcesController; end
class MessagesController < ResourcesController; end
class CommentsController < ResourcesController; end
class ReviewsController < ResourcesController; end
-class LogosController < ResourcesController; end
class AccountsController < ResourcesController; end
class AdminController < ResourcesController; end
class ProductsController < ResourcesController; end
class ImagesController < ResourcesController; end
-class PreferencesController < ResourcesController; end
module Backoffice
class ProductsController < ResourcesController; end
@@ -411,7 +405,7 @@ def jruby_skip(message = '')
skip message if defined?(JRUBY_VERSION)
end
-require 'mocha/setup' # FIXME: stop using mocha
+require 'active_support/testing/method_call_assertions'
class ForkingExecutor
class Server
@@ -483,3 +477,7 @@ if RUBY_ENGINE == "ruby" && PROCESS_COUNT > 0
# Use N processes (N defaults to 4)
Minitest.parallel_executor = ForkingExecutor.new(PROCESS_COUNT)
end
+
+class ActiveSupport::TestCase
+ include ActiveSupport::Testing::MethodCallAssertions
+end
diff --git a/actionpack/test/assertions/response_assertions_test.rb b/actionpack/test/assertions/response_assertions_test.rb
index 5e64cae7e2..82c747680d 100644
--- a/actionpack/test/assertions/response_assertions_test.rb
+++ b/actionpack/test/assertions/response_assertions_test.rb
@@ -7,7 +7,7 @@ module ActionDispatch
include ResponseAssertions
FakeResponse = Struct.new(:response_code) do
- [:success, :missing, :redirect, :error].each do |sym|
+ [:successful, :not_found, :redirection, :server_error].each do |sym|
define_method("#{sym}?") do
sym == response_code
end
@@ -16,7 +16,7 @@ module ActionDispatch
def test_assert_response_predicate_methods
[:success, :missing, :redirect, :error].each do |sym|
- @response = FakeResponse.new sym
+ @response = FakeResponse.new RESPONSE_PREDICATES[sym].to_s.sub(/\?/, '').to_sym
assert_response sym
assert_raises(Minitest::Assertion) {
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 21586e2193..899d92f815 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -5,9 +5,6 @@ class ActionPackAssertionsController < ActionController::Base
def nothing() head :ok end
- def hello_world() render :template => "test/hello_world"; end
- def hello_repeating_in_path() render :template => "test/hello/hello"; end
-
def hello_xml_world() render :template => "test/hello_xml_world"; end
def hello_xml_world_pdf
@@ -20,8 +17,6 @@ class ActionPackAssertionsController < ActionController::Base
render :template => "test/hello_xml_world"
end
- def partial() render :partial => 'test/partial'; end
-
def redirect_internal() redirect_to "/nothing"; end
def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end
@@ -48,12 +43,12 @@ class ActionPackAssertionsController < ActionController::Base
def flash_me
flash['hello'] = 'my name is inigo montoya...'
- render :text => "Inconceivable!"
+ render plain: "Inconceivable!"
end
def flash_me_naked
flash.clear
- render :text => "wow!"
+ render plain: "wow!"
end
def assign_this
@@ -62,40 +57,30 @@ class ActionPackAssertionsController < ActionController::Base
end
def render_based_on_parameters
- render :text => "Mr. #{params[:name]}"
+ render plain: "Mr. #{params[:name]}"
end
def render_url
- render :text => "<div>#{url_for(:action => 'flash_me', :only_path => true)}</div>"
+ render html: "<div>#{url_for(action: 'flash_me', only_path: true)}</div>"
end
def render_text_with_custom_content_type
- render :text => "Hello!", :content_type => Mime::RSS
- end
-
- def render_with_layout
- @variable_for_layout = nil
- render "test/hello_world", :layout => "layouts/standard"
- end
-
- def render_with_layout_and_partial
- @variable_for_layout = nil
- render "test/hello_world_with_partial", :layout => "layouts/standard"
+ render body: "Hello!", content_type: Mime[:rss]
end
def session_stuffing
session['xmas'] = 'turkey'
- render :text => "ho ho ho"
+ render plain: "ho ho ho"
end
def raise_exception_on_get
raise "get" if request.get?
- render :text => "request method: #{request.env['REQUEST_METHOD']}"
+ render plain: "request method: #{request.env['REQUEST_METHOD']}"
end
def raise_exception_on_post
raise "post" if request.post?
- render :text => "request method: #{request.env['REQUEST_METHOD']}"
+ render plain: "request method: #{request.env['REQUEST_METHOD']}"
end
def render_file_absolute_path
@@ -116,14 +101,14 @@ class AssertResponseWithUnexpectedErrorController < ActionController::Base
end
def show
- render :text => "Boom", :status => 500
+ render plain: "Boom", status: 500
end
end
module Admin
class InnerModuleController < ActionController::Base
def index
- render :nothing => true
+ head :ok
end
def redirect_to_index
@@ -304,14 +289,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
assert session.empty?
end
- def test_render_template_action
- process :nothing
- assert_template nil
-
- process :hello_world
- assert_template 'hello_world'
- end
-
def test_redirection_location
process :redirect_internal
assert_equal 'http://test.host/nothing', @response.redirect_url
@@ -341,7 +318,7 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_missing_response_code
process :response404
- assert @response.missing?
+ assert @response.not_found?
end
def test_client_error_response_code
@@ -369,12 +346,12 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_successful_response_code
process :nothing
- assert @response.success?
+ assert @response.successful?
end
def test_response_object
process :nothing
- assert_kind_of ActionController::TestResponse, @response
+ assert_kind_of ActionDispatch::TestResponse, @response
end
def test_render_based_on_parameters
@@ -455,192 +432,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
end
end
-class AssertTemplateTest < ActionController::TestCase
- tests ActionPackAssertionsController
-
- def test_with_invalid_hash_keys_raises_argument_error
- assert_raise(ArgumentError) do
- assert_template foo: "bar"
- end
- end
-
- def test_with_partial
- get :partial
- assert_template :partial => '_partial'
- end
-
- def test_file_with_absolute_path_success
- get :render_file_absolute_path
- assert_template :file => File.expand_path('../../../README.rdoc', __FILE__)
- end
-
- def test_file_with_relative_path_success
- get :render_file_relative_path
- assert_template :file => 'README.rdoc'
- end
-
- def test_with_file_failure
- get :render_file_absolute_path
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template :file => 'test/hello_world'
- end
-
- get :render_file_absolute_path
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template file: nil
- end
- end
-
- def test_with_nil_passes_when_no_template_rendered
- get :nothing
- assert_template nil
- end
-
- def test_with_nil_fails_when_template_rendered
- get :hello_world
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template nil
- end
- end
-
- def test_with_empty_string_fails_when_template_rendered
- get :hello_world
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template ""
- end
- end
-
- def test_with_empty_string_fails_when_no_template_rendered
- get :nothing
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template ""
- end
- end
-
- def test_passes_with_correct_string
- get :hello_world
- assert_template 'hello_world'
- assert_template 'test/hello_world'
- end
-
- def test_passes_with_correct_symbol
- get :hello_world
- assert_template :hello_world
- end
-
- def test_fails_with_incorrect_string
- get :hello_world
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template 'hello_planet'
- end
- end
-
- def test_fails_with_incorrect_string_that_matches
- get :hello_world
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template 'est/he'
- end
- end
-
- def test_fails_with_repeated_name_in_path
- get :hello_repeating_in_path
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template 'test/hello'
- end
- end
-
- def test_fails_with_incorrect_symbol
- get :hello_world
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template :hello_planet
- end
- end
-
- def test_fails_with_incorrect_symbol_that_matches
- get :hello_world
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template :"est/he"
- end
- end
-
- def test_fails_with_wrong_layout
- get :render_with_layout
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template :layout => "application"
- end
- end
-
- def test_fails_expecting_no_layout
- get :render_with_layout
- assert_raise(ActiveSupport::TestCase::Assertion) do
- assert_template :layout => nil
- end
- end
-
- def test_fails_expecting_not_known_layout
- get :render_with_layout
- assert_raise(ArgumentError) do
- assert_template :layout => 1
- end
- end
-
- def test_passes_with_correct_layout
- get :render_with_layout
- assert_template :layout => "layouts/standard"
- end
-
- def test_passes_with_layout_and_partial
- get :render_with_layout_and_partial
- assert_template :layout => "layouts/standard"
- end
-
- def test_passed_with_no_layout
- get :hello_world
- assert_template :layout => nil
- end
-
- def test_passed_with_no_layout_false
- get :hello_world
- assert_template :layout => false
- end
-
- def test_passes_with_correct_layout_without_layouts_prefix
- get :render_with_layout
- assert_template :layout => "standard"
- end
-
- def test_passes_with_correct_layout_symbol
- get :render_with_layout
- assert_template :layout => :standard
- end
-
- def test_assert_template_reset_between_requests
- get :hello_world
- assert_template 'test/hello_world'
-
- get :nothing
- assert_template nil
-
- get :partial
- assert_template partial: 'test/_partial'
-
- get :nothing
- assert_template partial: nil
-
- get :render_with_layout
- assert_template layout: 'layouts/standard'
-
- get :nothing
- assert_template layout: nil
-
- get :render_file_relative_path
- assert_template file: 'README.rdoc'
-
- get :nothing
- assert_template file: nil
- end
-end
-
class ActionPackHeaderTest < ActionController::TestCase
tests ActionPackAssertionsController
diff --git a/actionpack/test/controller/api/conditional_get_test.rb b/actionpack/test/controller/api/conditional_get_test.rb
new file mode 100644
index 0000000000..b4f1673be0
--- /dev/null
+++ b/actionpack/test/controller/api/conditional_get_test.rb
@@ -0,0 +1,57 @@
+require 'abstract_unit'
+require 'active_support/core_ext/integer/time'
+require 'active_support/core_ext/numeric/time'
+
+class ConditionalGetApiController < ActionController::API
+ before_action :handle_last_modified_and_etags, only: :two
+
+ def one
+ if stale?(last_modified: Time.now.utc.beginning_of_day, etag: [:foo, 123])
+ render plain: "Hi!"
+ end
+ end
+
+ def two
+ render plain: "Hi!"
+ end
+
+ private
+
+ def handle_last_modified_and_etags
+ fresh_when(last_modified: Time.now.utc.beginning_of_day, etag: [ :foo, 123 ])
+ end
+end
+
+class ConditionalGetApiTest < ActionController::TestCase
+ tests ConditionalGetApiController
+
+ def setup
+ @last_modified = Time.now.utc.beginning_of_day.httpdate
+ end
+
+ def test_request_gets_last_modified
+ get :two
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ assert_response :success
+ end
+
+ def test_request_obeys_last_modified
+ @request.if_modified_since = @last_modified
+ get :two
+ assert_response :not_modified
+ end
+
+ def test_last_modified_works_with_less_than_too
+ @request.if_modified_since = 5.years.ago.httpdate
+ get :two
+ assert_response :success
+ end
+
+ def test_request_not_modified
+ @request.if_modified_since = @last_modified
+ get :one
+ assert_equal 304, @response.status.to_i
+ assert @response.body.blank?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+end
diff --git a/actionpack/test/controller/api/data_streaming_test.rb b/actionpack/test/controller/api/data_streaming_test.rb
new file mode 100644
index 0000000000..0e7d97d1f4
--- /dev/null
+++ b/actionpack/test/controller/api/data_streaming_test.rb
@@ -0,0 +1,26 @@
+require 'abstract_unit'
+
+module TestApiFileUtils
+ def file_path() File.expand_path(__FILE__) end
+ def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end
+end
+
+class DataStreamingApiController < ActionController::API
+ include TestApiFileUtils
+
+ def one; end
+ def two
+ send_data(file_data, {})
+ end
+end
+
+class DataStreamingApiTest < ActionController::TestCase
+ include TestApiFileUtils
+ tests DataStreamingApiController
+
+ def test_data
+ response = process('two')
+ assert_kind_of String, response.body
+ assert_equal file_data, response.body
+ end
+end
diff --git a/actionpack/test/controller/api/force_ssl_test.rb b/actionpack/test/controller/api/force_ssl_test.rb
new file mode 100644
index 0000000000..8578340d82
--- /dev/null
+++ b/actionpack/test/controller/api/force_ssl_test.rb
@@ -0,0 +1,20 @@
+require 'abstract_unit'
+
+class ForceSSLApiController < ActionController::API
+ force_ssl
+
+ def one; end
+ def two
+ head :ok
+ end
+end
+
+class ForceSSLApiTest < ActionController::TestCase
+ tests ForceSSLApiController
+
+ def test_redirects_to_https
+ get :two
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_api/two", redirect_to_url
+ end
+end
diff --git a/actionpack/test/controller/api/implicit_render_test.rb b/actionpack/test/controller/api/implicit_render_test.rb
new file mode 100644
index 0000000000..26f9cd8f78
--- /dev/null
+++ b/actionpack/test/controller/api/implicit_render_test.rb
@@ -0,0 +1,15 @@
+require 'abstract_unit'
+
+class ImplicitRenderAPITestController < ActionController::API
+ def empty_action
+ end
+end
+
+class ImplicitRenderAPITest < ActionController::TestCase
+ tests ImplicitRenderAPITestController
+
+ def test_implicit_no_content_response
+ get :empty_action
+ assert_response :no_content
+ end
+end
diff --git a/actionpack/test/controller/api/params_wrapper_test.rb b/actionpack/test/controller/api/params_wrapper_test.rb
new file mode 100644
index 0000000000..53b3a0c3cc
--- /dev/null
+++ b/actionpack/test/controller/api/params_wrapper_test.rb
@@ -0,0 +1,26 @@
+require 'abstract_unit'
+
+class ParamsWrapperForApiTest < ActionController::TestCase
+ class UsersController < ActionController::API
+ attr_accessor :last_parameters
+
+ wrap_parameters :person, format: [:json]
+
+ def test
+ self.last_parameters = params.except(:controller, :action).to_unsafe_h
+ head :ok
+ end
+ end
+
+ class Person; end
+
+ tests UsersController
+
+ def test_specify_wrapper_name
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :test, params: { 'username' => 'sikachu' }
+
+ expected = { 'username' => 'sikachu', 'person' => { 'username' => 'sikachu' }}
+ assert_equal expected, @controller.last_parameters
+ end
+end
diff --git a/actionpack/test/controller/api/redirect_to_test.rb b/actionpack/test/controller/api/redirect_to_test.rb
new file mode 100644
index 0000000000..18877c4b3a
--- /dev/null
+++ b/actionpack/test/controller/api/redirect_to_test.rb
@@ -0,0 +1,19 @@
+require 'abstract_unit'
+
+class RedirectToApiController < ActionController::API
+ def one
+ redirect_to action: "two"
+ end
+
+ def two; end
+end
+
+class RedirectToApiTest < ActionController::TestCase
+ tests RedirectToApiController
+
+ def test_redirect_to
+ get :one
+ assert_response :redirect
+ assert_equal "http://test.host/redirect_to_api/two", redirect_to_url
+ end
+end
diff --git a/actionpack/test/controller/api/renderers_test.rb b/actionpack/test/controller/api/renderers_test.rb
new file mode 100644
index 0000000000..9405538833
--- /dev/null
+++ b/actionpack/test/controller/api/renderers_test.rb
@@ -0,0 +1,38 @@
+require 'abstract_unit'
+require 'active_support/core_ext/hash/conversions'
+
+class RenderersApiController < ActionController::API
+ class Model
+ def to_json(options = {})
+ { a: 'b' }.to_json(options)
+ end
+
+ def to_xml(options = {})
+ { a: 'b' }.to_xml(options)
+ end
+ end
+
+ def one
+ render json: Model.new
+ end
+
+ def two
+ render xml: Model.new
+ end
+end
+
+class RenderersApiTest < ActionController::TestCase
+ tests RenderersApiController
+
+ def test_render_json
+ get :one
+ assert_response :success
+ assert_equal({ a: 'b' }.to_json, @response.body)
+ end
+
+ def test_render_xml
+ get :two
+ assert_response :success
+ assert_equal({ a: 'b' }.to_xml, @response.body)
+ end
+end
diff --git a/actionpack/test/controller/api/url_for_test.rb b/actionpack/test/controller/api/url_for_test.rb
new file mode 100644
index 0000000000..0d8691a091
--- /dev/null
+++ b/actionpack/test/controller/api/url_for_test.rb
@@ -0,0 +1,20 @@
+require 'abstract_unit'
+
+class UrlForApiController < ActionController::API
+ def one; end
+ def two; end
+end
+
+class UrlForApiTest < ActionController::TestCase
+ tests UrlForApiController
+
+ def setup
+ super
+ @request.host = 'www.example.com'
+ end
+
+ def test_url_for
+ get :one
+ assert_equal "http://www.example.com/url_for_api/one", @controller.url_for
+ end
+end
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index f7ad8e5158..fb60dbd993 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -13,7 +13,7 @@ end
class NonEmptyController < ActionController::Base
def public_action
- render :nothing => true
+ head :ok
end
end
@@ -29,7 +29,7 @@ end
class OptionalDefaultUrlOptionsController < ActionController::Base
def show
- render nothing: true
+ head :ok
end
def default_url_options
@@ -53,7 +53,7 @@ end
class ActionMissingController < ActionController::Base
def action_missing(action)
- render :text => "Response for #{action}"
+ render plain: "Response for #{action}"
end
end
@@ -93,6 +93,8 @@ end
class ControllerInstanceTests < ActiveSupport::TestCase
def setup
@empty = EmptyController.new
+ @empty.set_request!(ActionDispatch::Request.new({}))
+ @empty.set_response!(EmptyController.make_response!(@empty.request))
@contained = Submodule::ContainedEmptyController.new
@empty_controllers = [@empty, @contained]
end
@@ -127,8 +129,6 @@ class PerformActionTest < ActionController::TestCase
# a more accurate simulation of what happens in "real life".
@controller.logger = ActiveSupport::Logger.new(nil)
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@request.host = "www.nextangle.com"
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index 2d6607041d..bc0ffd3eaa 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -22,8 +22,6 @@ class FragmentCachingMetalTest < ActionController::TestCase
@controller.perform_caching = true
@controller.cache_store = @store
@params = { controller: 'posts', action: 'index' }
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@controller.params = @params
@controller.request = @request
@controller.response = @response
@@ -52,8 +50,6 @@ class FragmentCachingTest < ActionController::TestCase
@controller.perform_caching = true
@controller.cache_store = @store
@params = {:controller => 'posts', :action => 'index'}
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@controller.params = @params
@controller.request = @request
@controller.response = @response
@@ -166,6 +162,8 @@ class FunctionalCachingController < CachingController
end
def formatted_fragment_cached_with_variant
+ request.variant = :phone if params[:v] == "phone"
+
respond_to do |format|
format.html.phone
format.html
@@ -183,8 +181,6 @@ class FunctionalFragmentCachingTest < ActionController::TestCase
@controller = FunctionalCachingController.new
@controller.perform_caching = true
@controller.cache_store = @store
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
end
def test_fragment_caching
@@ -268,9 +264,7 @@ CACHED
def test_fragment_caching_with_variant
- @request.variant = :phone
-
- get :formatted_fragment_cached_with_variant, format: "html"
+ get :formatted_fragment_cached_with_variant, format: "html", params: { v: :phone }
assert_response :success
expected_body = "<body>\n<p>PHONE</p>\n</body>\n"
@@ -305,30 +299,42 @@ class CacheHelperOutputBufferTest < ActionController::TestCase
def test_output_buffer
output_buffer = ActionView::OutputBuffer.new
controller = MockController.new
- cache_helper = Object.new
+ cache_helper = Class.new do
+ def self.controller; end;
+ def self.output_buffer; end;
+ def self.output_buffer=; end;
+ end
cache_helper.extend(ActionView::Helpers::CacheHelper)
- cache_helper.expects(:controller).returns(controller).at_least(0)
- cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0)
- # if the output_buffer is changed, the new one should be html_safe and of the same type
- cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0)
- assert_nothing_raised do
- cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil }
+ cache_helper.stub :controller, controller do
+ cache_helper.stub :output_buffer, output_buffer do
+ assert_called_with cache_helper, :output_buffer=, [output_buffer.class.new(output_buffer)] do
+ assert_nothing_raised do
+ cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil }
+ end
+ end
+ end
end
end
def test_safe_buffer
output_buffer = ActiveSupport::SafeBuffer.new
controller = MockController.new
- cache_helper = Object.new
+ cache_helper = Class.new do
+ def self.controller; end;
+ def self.output_buffer; end;
+ def self.output_buffer=; end;
+ end
cache_helper.extend(ActionView::Helpers::CacheHelper)
- cache_helper.expects(:controller).returns(controller).at_least(0)
- cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0)
- # if the output_buffer is changed, the new one should be html_safe and of the same type
- cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0)
- assert_nothing_raised do
- cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil }
+ cache_helper.stub :controller, controller do
+ cache_helper.stub :output_buffer, output_buffer do
+ assert_called_with cache_helper, :output_buffer=, [output_buffer.class.new(output_buffer)] do
+ assert_nothing_raised do
+ cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil }
+ end
+ end
+ end
end
end
end
@@ -352,6 +358,8 @@ class ViewCacheDependencyTest < ActionController::TestCase
end
class CollectionCacheController < ActionController::Base
+ attr_accessor :partial_rendered_times
+
def index
@customers = [Customer.new('david', params[:id] || 1)]
end
@@ -377,14 +385,17 @@ class AutomaticCollectionCacheTest < ActionController::TestCase
super
@controller = CollectionCacheController.new
@controller.perform_caching = true
+ @controller.partial_rendered_times = 0
@controller.cache_store = ActiveSupport::Cache::MemoryStore.new
+ ActionView::PartialRenderer.collection_cache = @controller.cache_store
end
def test_collection_fetches_cached_views
get :index
+ assert_equal 1, @controller.partial_rendered_times
- ActionView::PartialRenderer.expects(:collection_with_template).never
get :index
+ assert_equal 1, @controller.partial_rendered_times
end
def test_preserves_order_when_reading_from_cache_plus_rendering
@@ -402,8 +413,9 @@ class AutomaticCollectionCacheTest < ActionController::TestCase
def test_caching_works_with_beginning_comment
get :index_with_comment
+ assert_equal 1, @controller.partial_rendered_times
- ActionView::PartialRenderer.expects(:collection_with_template).never
get :index_with_comment
+ assert_equal 1, @controller.partial_rendered_times
end
end
diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb
index 89667df3a4..c02607b55e 100644
--- a/actionpack/test/controller/content_type_test.rb
+++ b/actionpack/test/controller/content_type_test.rb
@@ -3,30 +3,30 @@ require 'abstract_unit'
class OldContentTypeController < ActionController::Base
# :ported:
def render_content_type_from_body
- response.content_type = Mime::RSS
- render :text => "hello world!"
+ response.content_type = Mime[:rss]
+ render body: "hello world!"
end
# :ported:
def render_defaults
- render :text => "hello world!"
+ render body: "hello world!"
end
# :ported:
def render_content_type_from_render
- render :text => "hello world!", :content_type => Mime::RSS
+ render body: "hello world!", :content_type => Mime[:rss]
end
# :ported:
def render_charset_from_body
response.charset = "utf-16"
- render :text => "hello world!"
+ render body: "hello world!"
end
# :ported:
def render_nil_charset_from_body
response.charset = nil
- render :text => "hello world!"
+ render body: "hello world!"
end
def render_default_for_erb
@@ -36,16 +36,16 @@ class OldContentTypeController < ActionController::Base
end
def render_change_for_builder
- response.content_type = Mime::HTML
+ response.content_type = Mime[:html]
render :action => "render_default_for_builder"
end
def render_default_content_types_for_respond_to
respond_to do |format|
- format.html { render :text => "hello world!" }
- format.xml { render :action => "render_default_content_types_for_respond_to" }
- format.js { render :text => "hello world!" }
- format.rss { render :text => "hello world!", :content_type => Mime::XML }
+ format.html { render body: "hello world!" }
+ format.xml { render action: "render_default_content_types_for_respond_to" }
+ format.js { render body: "hello world!" }
+ format.rss { render body: "hello world!", content_type: Mime[:xml] }
end
end
end
@@ -64,68 +64,68 @@ class ContentTypeTest < ActionController::TestCase
def test_render_defaults
get :render_defaults
assert_equal "utf-8", @response.charset
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:text], @response.content_type
end
def test_render_changed_charset_default
with_default_charset "utf-16" do
get :render_defaults
assert_equal "utf-16", @response.charset
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:text], @response.content_type
end
end
# :ported:
def test_content_type_from_body
get :render_content_type_from_body
- assert_equal Mime::RSS, @response.content_type
+ assert_equal Mime[:rss], @response.content_type
assert_equal "utf-8", @response.charset
end
# :ported:
def test_content_type_from_render
get :render_content_type_from_render
- assert_equal Mime::RSS, @response.content_type
+ assert_equal Mime[:rss], @response.content_type
assert_equal "utf-8", @response.charset
end
# :ported:
def test_charset_from_body
get :render_charset_from_body
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:text], @response.content_type
assert_equal "utf-16", @response.charset
end
# :ported:
def test_nil_charset_from_body
get :render_nil_charset_from_body
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:text], @response.content_type
assert_equal "utf-8", @response.charset, @response.headers.inspect
end
def test_nil_default_for_erb
with_default_charset nil do
get :render_default_for_erb
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:html], @response.content_type
assert_nil @response.charset, @response.headers.inspect
end
end
def test_default_for_erb
get :render_default_for_erb
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:html], @response.content_type
assert_equal "utf-8", @response.charset
end
def test_default_for_builder
get :render_default_for_builder
- assert_equal Mime::XML, @response.content_type
+ assert_equal Mime[:xml], @response.content_type
assert_equal "utf-8", @response.charset
end
def test_change_for_builder
get :render_change_for_builder
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:html], @response.content_type
assert_equal "utf-8", @response.charset
end
@@ -144,24 +144,24 @@ class AcceptBasedContentTypeTest < ActionController::TestCase
tests OldContentTypeController
def test_render_default_content_types_for_respond_to
- @request.accept = Mime::HTML.to_s
+ @request.accept = Mime[:html].to_s
get :render_default_content_types_for_respond_to
- assert_equal Mime::HTML, @response.content_type
+ assert_equal Mime[:html], @response.content_type
- @request.accept = Mime::JS.to_s
+ @request.accept = Mime[:js].to_s
get :render_default_content_types_for_respond_to
- assert_equal Mime::JS, @response.content_type
+ assert_equal Mime[:js], @response.content_type
end
def test_render_default_content_types_for_respond_to_with_template
- @request.accept = Mime::XML.to_s
+ @request.accept = Mime[:xml].to_s
get :render_default_content_types_for_respond_to
- assert_equal Mime::XML, @response.content_type
+ assert_equal Mime[:xml], @response.content_type
end
def test_render_default_content_types_for_respond_to_with_overwrite
- @request.accept = Mime::RSS.to_s
+ @request.accept = Mime[:rss].to_s
get :render_default_content_types_for_respond_to
- assert_equal Mime::XML, @response.content_type
+ assert_equal Mime[:xml], @response.content_type
end
end
diff --git a/actionpack/test/controller/default_url_options_with_before_action_test.rb b/actionpack/test/controller/default_url_options_with_before_action_test.rb
index 230f40d7ad..12fbe0424e 100644
--- a/actionpack/test/controller/default_url_options_with_before_action_test.rb
+++ b/actionpack/test/controller/default_url_options_with_before_action_test.rb
@@ -6,7 +6,7 @@ class ControllerWithBeforeActionAndDefaultUrlOptions < ActionController::Base
after_action { I18n.locale = "en" }
def target
- render :text => "final response"
+ render plain: "final response"
end
def redirect
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index a1ce12a13e..08271012e9 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -13,16 +13,6 @@ class ActionController::Base
filters.map!(&:raw_filter)
end
end
-
- def assigns(key = nil)
- assigns = {}
- instance_variables.each do |ivar|
- next if ActionController::Base.protected_instance_variables.include?(ivar)
- assigns[ivar[1..-1]] = instance_variable_get(ivar)
- end
-
- key.nil? ? assigns : assigns[key.to_s]
- end
end
class FilterTest < ActionController::TestCase
@@ -50,7 +40,7 @@ class FilterTest < ActionController::TestCase
before_action :ensure_login, :except => [:go_wild]
def go_wild
- render :text => "gobble"
+ render plain: "gobble"
end
end
@@ -61,7 +51,7 @@ class FilterTest < ActionController::TestCase
(1..3).each do |i|
define_method "fail_#{i}" do
- render :text => i.to_s
+ render plain: i.to_s
end
end
@@ -232,7 +222,7 @@ class FilterTest < ActionController::TestCase
skip_before_action :clean_up_tmp, only: :login, if: -> { true }
def login
- render text: 'ok'
+ render plain: 'ok'
end
end
@@ -244,7 +234,7 @@ class FilterTest < ActionController::TestCase
skip_before_action :clean_up_tmp, if: -> { true }, except: :login
def login
- render text: 'ok'
+ render plain: 'ok'
end
end
@@ -268,11 +258,11 @@ class FilterTest < ActionController::TestCase
before_action :ensure_login, :only => :index
def index
- render :text => 'ok'
+ render plain: 'ok'
end
def public
- render :text => 'ok'
+ render plain: 'ok'
end
end
@@ -282,7 +272,7 @@ class FilterTest < ActionController::TestCase
before_action :ensure_login
def index
- render :text => 'ok'
+ render plain: 'ok'
end
private
@@ -393,7 +383,7 @@ class FilterTest < ActionController::TestCase
before_action(AuditFilter)
def show
- render :text => "hello"
+ render plain: "hello"
end
end
@@ -431,11 +421,11 @@ class FilterTest < ActionController::TestCase
before_action :second, :only => :foo
def foo
- render :text => 'foo'
+ render plain: 'foo'
end
def bar
- render :text => 'bar'
+ render plain: 'bar'
end
protected
@@ -452,7 +442,7 @@ class FilterTest < ActionController::TestCase
before_action :choose
%w(foo bar baz).each do |action|
- define_method(action) { render :text => action }
+ define_method(action) { render plain: action }
end
private
@@ -481,7 +471,7 @@ class FilterTest < ActionController::TestCase
@ran_filter << 'between_before_all_and_after_all'
end
def show
- render :text => 'hello'
+ render plain: 'hello'
end
end
@@ -491,7 +481,7 @@ class FilterTest < ActionController::TestCase
def around(controller)
yield
rescue ErrorToRescue => ex
- controller.__send__ :render, :text => "I rescued this: #{ex.inspect}"
+ controller.__send__ :render, plain: "I rescued this: #{ex.inspect}"
end
end
@@ -560,7 +550,7 @@ class FilterTest < ActionController::TestCase
def test_after_actions_are_not_run_if_around_action_does_not_yield
controller = NonYieldingAroundFilterController.new
test_process(controller, "index")
- assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters']
+ assert_equal ["filter_one", "it didn't yield"], controller.instance_variable_get(:@filters)
end
def test_added_action_to_inheritance_graph
@@ -577,140 +567,141 @@ class FilterTest < ActionController::TestCase
def test_running_actions
test_process(PrependingController)
- assert_equal %w( wonderful_life ensure_login ), assigns["ran_filter"]
+ assert_equal %w( wonderful_life ensure_login ),
+ @controller.instance_variable_get(:@ran_filter)
end
def test_running_actions_with_proc
test_process(ProcController)
- assert assigns["ran_proc_action"]
+ assert @controller.instance_variable_get(:@ran_proc_action)
end
def test_running_actions_with_implicit_proc
test_process(ImplicitProcController)
- assert assigns["ran_proc_action"]
+ assert @controller.instance_variable_get(:@ran_proc_action)
end
def test_running_actions_with_class
test_process(AuditController)
- assert assigns["was_audited"]
+ assert @controller.instance_variable_get(:@was_audited)
end
def test_running_anomolous_yet_valid_condition_actions
test_process(AnomolousYetValidConditionController)
- assert_equal %w( ensure_login ), assigns["ran_filter"]
- assert assigns["ran_class_action"]
- assert assigns["ran_proc_action1"]
- assert assigns["ran_proc_action2"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
+ assert @controller.instance_variable_get(:@ran_class_action)
+ assert @controller.instance_variable_get(:@ran_proc_action1)
+ assert @controller.instance_variable_get(:@ran_proc_action2)
test_process(AnomolousYetValidConditionController, "show_without_action")
- assert_nil assigns["ran_filter"]
- assert !assigns["ran_class_action"]
- assert !assigns["ran_proc_action1"]
- assert !assigns["ran_proc_action2"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
+ assert_not @controller.instance_variable_defined?(:@ran_class_action)
+ assert_not @controller.instance_variable_defined?(:@ran_proc_action1)
+ assert_not @controller.instance_variable_defined?(:@ran_proc_action2)
end
def test_running_conditional_options
test_process(ConditionalOptionsFilter)
- assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
end
def test_running_conditional_skip_options
test_process(ConditionalOptionsSkipFilter)
- assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
end
def test_if_is_ignored_when_used_with_only
test_process(SkipFilterUsingOnlyAndIf, 'login')
- assert_nil assigns['ran_filter']
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
end
def test_except_is_ignored_when_used_with_if
test_process(SkipFilterUsingIfAndExcept, 'login')
- assert_equal %w(ensure_login), assigns["ran_filter"]
+ assert_equal %w(ensure_login), @controller.instance_variable_get(:@ran_filter)
end
def test_skipping_class_actions
test_process(ClassController)
- assert_equal true, assigns["ran_class_action"]
+ assert_equal true, @controller.instance_variable_get(:@ran_class_action)
skipping_class_controller = Class.new(ClassController) do
skip_before_action ConditionalClassFilter
end
test_process(skipping_class_controller)
- assert_nil assigns['ran_class_action']
+ assert_not @controller.instance_variable_defined?(:@ran_class_action)
end
def test_running_collection_condition_actions
test_process(ConditionalCollectionFilterController)
- assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
test_process(ConditionalCollectionFilterController, "show_without_action")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
test_process(ConditionalCollectionFilterController, "another_action")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
end
def test_running_only_condition_actions
test_process(OnlyConditionSymController)
- assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
test_process(OnlyConditionSymController, "show_without_action")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
test_process(OnlyConditionProcController)
- assert assigns["ran_proc_action"]
+ assert @controller.instance_variable_get(:@ran_proc_action)
test_process(OnlyConditionProcController, "show_without_action")
- assert !assigns["ran_proc_action"]
+ assert_not @controller.instance_variable_defined?(:@ran_proc_action)
test_process(OnlyConditionClassController)
- assert assigns["ran_class_action"]
+ assert @controller.instance_variable_get(:@ran_class_action)
test_process(OnlyConditionClassController, "show_without_action")
- assert !assigns["ran_class_action"]
+ assert_not @controller.instance_variable_defined?(:@ran_class_action)
end
def test_running_except_condition_actions
test_process(ExceptConditionSymController)
- assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
test_process(ExceptConditionSymController, "show_without_action")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
test_process(ExceptConditionProcController)
- assert assigns["ran_proc_action"]
+ assert @controller.instance_variable_get(:@ran_proc_action)
test_process(ExceptConditionProcController, "show_without_action")
- assert !assigns["ran_proc_action"]
+ assert_not @controller.instance_variable_defined?(:@ran_proc_action)
test_process(ExceptConditionClassController)
- assert assigns["ran_class_action"]
+ assert @controller.instance_variable_get(:@ran_class_action)
test_process(ExceptConditionClassController, "show_without_action")
- assert !assigns["ran_class_action"]
+ assert_not @controller.instance_variable_defined?(:@ran_class_action)
end
def test_running_only_condition_and_conditional_options
test_process(OnlyConditionalOptionsFilter, "show")
- assert_not assigns["ran_conditional_index_proc"]
+ assert_not @controller.instance_variable_defined?(:@ran_conditional_index_proc)
end
def test_running_before_and_after_condition_actions
test_process(BeforeAndAfterConditionController)
- assert_equal %w( ensure_login clean_up_tmp), assigns["ran_filter"]
+ assert_equal %w( ensure_login clean_up_tmp), @controller.instance_variable_get(:@ran_filter)
test_process(BeforeAndAfterConditionController, "show_without_action")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
end
def test_around_action
test_process(AroundFilterController)
- assert assigns["before_ran"]
- assert assigns["after_ran"]
+ assert @controller.instance_variable_get(:@before_ran)
+ assert @controller.instance_variable_get(:@after_ran)
end
def test_before_after_class_action
test_process(BeforeAfterClassFilterController)
- assert assigns["before_ran"]
- assert assigns["after_ran"]
+ assert @controller.instance_variable_get(:@before_ran)
+ assert @controller.instance_variable_get(:@after_ran)
end
def test_having_properties_in_around_action
test_process(AroundFilterController)
- assert_equal "before and after", assigns["execution_log"]
+ assert_equal "before and after", @controller.instance_variable_get(:@execution_log)
end
def test_prepending_and_appending_around_action
@@ -723,33 +714,33 @@ class FilterTest < ActionController::TestCase
def test_rendering_breaks_actioning_chain
response = test_process(RenderingController)
assert_equal "something else", response.body
- assert !assigns["ran_action"]
+ assert_not @controller.instance_variable_defined?(:@ran_action)
end
def test_before_action_rendering_breaks_actioning_chain_for_after_action
test_process(RenderingController)
- assert_equal %w( before_action_rendering ), assigns["ran_filter"]
- assert !assigns["ran_action"]
+ assert_equal %w( before_action_rendering ), @controller.instance_variable_get(:@ran_filter)
+ assert_not @controller.instance_variable_defined?(:@ran_action)
end
def test_before_action_redirects_breaks_actioning_chain_for_after_action
test_process(BeforeActionRedirectionController)
assert_response :redirect
assert_equal "http://test.host/filter_test/before_action_redirection/target_of_redirection", redirect_to_url
- assert_equal %w( before_action_redirects ), assigns["ran_filter"]
+ assert_equal %w( before_action_redirects ), @controller.instance_variable_get(:@ran_filter)
end
def test_before_action_rendering_breaks_actioning_chain_for_preprend_after_action
test_process(RenderingForPrependAfterActionController)
- assert_equal %w( before_action_rendering ), assigns["ran_filter"]
- assert !assigns["ran_action"]
+ assert_equal %w( before_action_rendering ), @controller.instance_variable_get(:@ran_filter)
+ assert_not @controller.instance_variable_defined?(:@ran_action)
end
def test_before_action_redirects_breaks_actioning_chain_for_preprend_after_action
test_process(BeforeActionRedirectionForPrependAfterActionController)
assert_response :redirect
assert_equal "http://test.host/filter_test/before_action_redirection_for_prepend_after_action/target_of_redirection", redirect_to_url
- assert_equal %w( before_action_redirects ), assigns["ran_filter"]
+ assert_equal %w( before_action_redirects ), @controller.instance_variable_get(:@ran_filter)
end
def test_actions_with_mixed_specialization_run_in_order
@@ -766,35 +757,34 @@ class FilterTest < ActionController::TestCase
def test_dynamic_dispatch
%w(foo bar baz).each do |action|
- request = ActionController::TestRequest.new
- request.query_parameters[:choose] = action
- response = DynamicDispatchController.action(action).call(request.env).last
+ @request.query_parameters[:choose] = action
+ response = DynamicDispatchController.action(action).call(@request.env).last
assert_equal action, response.body
end
end
def test_running_prepended_before_and_after_action
test_process(PrependingBeforeAndAfterController)
- assert_equal %w( before_all between_before_all_and_after_all after_all ), assigns["ran_filter"]
+ assert_equal %w( before_all between_before_all_and_after_all after_all ), @controller.instance_variable_get(:@ran_filter)
end
def test_skipping_and_limiting_controller
test_process(SkippingAndLimitedController, "index")
- assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert_equal %w( ensure_login ), @controller.instance_variable_get(:@ran_filter)
test_process(SkippingAndLimitedController, "public")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
end
def test_skipping_and_reordering_controller
test_process(SkippingAndReorderingController, "index")
- assert_equal %w( find_record ensure_login ), assigns["ran_filter"]
+ assert_equal %w( find_record ensure_login ), @controller.instance_variable_get(:@ran_filter)
end
def test_conditional_skipping_of_actions
test_process(ConditionalSkippingController, "login")
- assert_nil assigns["ran_filter"]
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
test_process(ConditionalSkippingController, "change_password")
- assert_equal %w( ensure_login find_user ), assigns["ran_filter"]
+ assert_equal %w( ensure_login find_user ), @controller.instance_variable_get(:@ran_filter)
test_process(ConditionalSkippingController, "login")
assert !@controller.instance_variable_defined?("@ran_after_action")
@@ -804,23 +794,23 @@ class FilterTest < ActionController::TestCase
def test_conditional_skipping_of_actions_when_parent_action_is_also_conditional
test_process(ChildOfConditionalParentController)
- assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter']
+ assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), @controller.instance_variable_get(:@ran_filter)
test_process(ChildOfConditionalParentController, 'another_action')
- assert_nil assigns['ran_filter']
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
end
def test_condition_skipping_of_actions_when_siblings_also_have_conditions
test_process(ChildOfConditionalParentController)
- assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter']
+ assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), @controller.instance_variable_get(:@ran_filter)
test_process(AnotherChildOfConditionalParentController)
- assert_equal %w( conditional_in_parent_after ), assigns['ran_filter']
+ assert_equal %w( conditional_in_parent_after ), @controller.instance_variable_get(:@ran_filter)
test_process(ChildOfConditionalParentController)
- assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter']
+ assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), @controller.instance_variable_get(:@ran_filter)
end
def test_changing_the_requirements
test_process(ChangingTheRequirementsController, "go_wild")
- assert_nil assigns['ran_filter']
+ assert_not @controller.instance_variable_defined?(:@ran_filter)
end
def test_a_rescuing_around_action
@@ -829,27 +819,25 @@ class FilterTest < ActionController::TestCase
response = test_process(RescuedController)
end
- assert response.success?
+ assert response.successful?
assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body)
end
def test_actions_obey_only_and_except_for_implicit_actions
test_process(ImplicitActionsController, 'show')
- assert_equal 'Except', assigns(:except)
- assert_nil assigns(:only)
+ assert_equal 'Except', @controller.instance_variable_get(:@except)
+ assert_not @controller.instance_variable_defined?(:@only)
assert_equal 'show', response.body
test_process(ImplicitActionsController, 'edit')
- assert_equal 'Only', assigns(:only)
- assert_nil assigns(:except)
+ assert_equal 'Only', @controller.instance_variable_get(:@only)
+ assert_not @controller.instance_variable_defined?(:@except)
assert_equal 'edit', response.body
end
private
def test_process(controller, action = "show")
@controller = controller.is_a?(Class) ? controller.new : controller
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
process(action)
end
@@ -1010,8 +998,8 @@ class YieldingAroundFiltersTest < ActionController::TestCase
def test_with_proc
test_process(ControllerWithProcFilter,'no_raise')
- assert assigns['before']
- assert assigns['after']
+ assert @controller.instance_variable_get(:@before)
+ assert @controller.instance_variable_get(:@after)
end
def test_nested_actions
@@ -1032,12 +1020,12 @@ class YieldingAroundFiltersTest < ActionController::TestCase
def test_action_order_with_all_action_types
test_process(ControllerWithAllTypesOfFilters,'no_raise')
- assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) after around (after yield)', assigns['ran_filter'].join(' ')
+ assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) after around (after yield)', @controller.instance_variable_get(:@ran_filter).join(' ')
end
def test_action_order_with_skip_action_method
test_process(ControllerWithTwoLessFilters,'no_raise')
- assert_equal 'before around (before yield) around (after yield)', assigns['ran_filter'].join(' ')
+ assert_equal 'before around (before yield) around (after yield)', @controller.instance_variable_get(:@ran_filter).join(' ')
end
def test_first_action_in_multiple_before_action_chain_halts
@@ -1063,7 +1051,7 @@ class YieldingAroundFiltersTest < ActionController::TestCase
def test_skipping_with_skip_action_callback
test_process(SkipFilterUsingSkipActionCallback,'no_raise')
- assert_equal 'before around (before yield) around (after yield)', assigns['ran_filter'].join(' ')
+ assert_equal 'before around (before yield) around (after yield)', @controller.instance_variable_get(:@ran_filter).join(' ')
end
def test_deprecated_skip_action_callback
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index 0ff0a1ef61..b063d769a4 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -57,7 +57,7 @@ class FlashTest < ActionController::TestCase
def std_action
@flash_copy = {}.update(flash)
- render :nothing => true
+ head :ok
end
def filter_halting_action
@@ -103,54 +103,55 @@ class FlashTest < ActionController::TestCase
get :set_flash
get :use_flash
- assert_equal "hello", assigns["flash_copy"]["that"]
- assert_equal "hello", assigns["flashy"]
+ assert_equal "hello", @controller.instance_variable_get(:@flash_copy)["that"]
+ assert_equal "hello", @controller.instance_variable_get(:@flashy)
get :use_flash
- assert_nil assigns["flash_copy"]["that"], "On second flash"
+ assert_nil @controller.instance_variable_get(:@flash_copy)["that"], "On second flash"
end
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
- assert_equal "hello", assigns["flash_copy"]["that"]
- assert_equal "hello", assigns["flashy"]
+ assert_equal "hello", @controller.instance_variable_get(:@flash_copy)["that"]
+ assert_equal "hello", @controller.instance_variable_get(:@flashy)
get :use_flash
- assert_equal "hello", assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello", @controller.instance_variable_get(:@flash_copy)["that"], "On second flash"
get :use_flash
- assert_nil assigns["flash_copy"]["that"], "On third flash"
+ assert_nil @controller.instance_variable_get(:@flash_copy)["that"], "On third flash"
end
def test_flash_now
get :set_flash_now
- assert_equal "hello", assigns["flash_copy"]["that"]
- assert_equal "bar" , assigns["flash_copy"]["foo"]
- assert_equal "hello", assigns["flashy"]
+ assert_equal "hello", @controller.instance_variable_get(:@flash_copy)["that"]
+ assert_equal "bar", @controller.instance_variable_get(:@flash_copy)["foo"]
+ assert_equal "hello", @controller.instance_variable_get(:@flashy)
get :attempt_to_use_flash_now
- assert_nil assigns["flash_copy"]["that"]
- assert_nil assigns["flash_copy"]["foo"]
- assert_nil assigns["flashy"]
+ assert_nil @controller.instance_variable_get(:@flash_copy)["that"]
+ assert_nil @controller.instance_variable_get(:@flash_copy)["foo"]
+ assert_nil @controller.instance_variable_get(:@flashy)
end
def test_update_flash
get :set_flash
get :use_flash_and_update_it
- assert_equal "hello", assigns["flash_copy"]["that"]
- assert_equal "hello again", assigns["flash_copy"]["this"]
+ assert_equal "hello", @controller.instance_variable_get(:@flash_copy)["that"]
+ assert_equal "hello again", @controller.instance_variable_get(:@flash_copy)["this"]
get :use_flash
- assert_nil assigns["flash_copy"]["that"], "On second flash"
- assert_equal "hello again", assigns["flash_copy"]["this"], "On second flash"
+ assert_nil @controller.instance_variable_get(:@flash_copy)["that"], "On second flash"
+ assert_equal "hello again",
+ @controller.instance_variable_get(:@flash_copy)["this"], "On second flash"
end
def test_flash_after_reset_session
get :use_flash_after_reset_session
- assert_equal "hello", assigns["flashy_that"]
- assert_equal "good-bye", assigns["flashy_this"]
- assert_nil assigns["flashy_that_reset"]
+ assert_equal "hello", @controller.instance_variable_get(:@flashy_that)
+ assert_equal "good-bye", @controller.instance_variable_get(:@flashy_this)
+ assert_nil @controller.instance_variable_get(:@flashy_that_reset)
end
def test_does_not_set_the_session_if_the_flash_is_empty
@@ -160,13 +161,13 @@ class FlashTest < ActionController::TestCase
def test_sweep_after_halted_action_chain
get :std_action
- assert_nil assigns["flash_copy"]["foo"]
+ assert_nil @controller.instance_variable_get(:@flash_copy)["foo"]
get :filter_halting_action
- assert_equal "bar", assigns["flash_copy"]["foo"]
+ assert_equal "bar", @controller.instance_variable_get(:@flash_copy)["foo"]
get :std_action # follow redirection
- assert_equal "bar", assigns["flash_copy"]["foo"]
+ assert_equal "bar", @controller.instance_variable_get(:@flash_copy)["foo"]
get :std_action
- assert_nil assigns["flash_copy"]["foo"]
+ assert_nil @controller.instance_variable_get(:@flash_copy)["foo"]
end
def test_keep_and_discard_return_values
@@ -328,7 +329,7 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest
@app = self.class.build_app(set) do |middleware|
middleware.use ActionDispatch::Session::CookieStore, :key => SessionKey
middleware.use ActionDispatch::Flash
- middleware.delete "ActionDispatch::ShowExceptions"
+ middleware.delete ActionDispatch::ShowExceptions
end
yield
diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb
index 04222745d9..22f1cc7c22 100644
--- a/actionpack/test/controller/force_ssl_test.rb
+++ b/actionpack/test/controller/force_ssl_test.rb
@@ -2,11 +2,11 @@ require 'abstract_unit'
class ForceSSLController < ActionController::Base
def banana
- render :text => "monkey"
+ render plain: "monkey"
end
def cheeseburger
- render :text => "sikachu"
+ render plain: "sikachu"
end
end
@@ -26,7 +26,7 @@ class ForceSSLCustomOptions < ForceSSLController
force_ssl :notice => 'Foo, Bar!', :only => :redirect_notice
def force_ssl_action
- render :text => action_name
+ render plain: action_name
end
alias_method :redirect_host, :force_ssl_action
@@ -40,15 +40,15 @@ class ForceSSLCustomOptions < ForceSSLController
alias_method :redirect_notice, :force_ssl_action
def use_flash
- render :text => flash[:message]
+ render plain: flash[:message]
end
def use_alert
- render :text => flash[:alert]
+ render plain: flash[:alert]
end
def use_notice
- render :text => flash[:notice]
+ render plain: flash[:notice]
end
end
@@ -85,10 +85,10 @@ end
class RedirectToSSL < ForceSSLController
def banana
- force_ssl_redirect || render(:text => 'monkey')
+ force_ssl_redirect || render(plain: 'monkey')
end
def cheeseburger
- force_ssl_redirect('secure.cheeseburger.host') || render(:text => 'ihaz')
+ force_ssl_redirect('secure.cheeseburger.host') || render(plain: 'ihaz')
end
end
@@ -240,8 +240,8 @@ class ForceSSLFlashTest < ActionController::TestCase
@request.env.delete('PATH_INFO')
get :use_flash
- assert_equal "hello", assigns["flash_copy"]["that"]
- assert_equal "hello", assigns["flashy"]
+ assert_equal "hello", @controller.instance_variable_get("@flash_copy")["that"]
+ assert_equal "hello", @controller.instance_variable_get("@flashy")
end
end
@@ -315,7 +315,7 @@ class RedirectToSSLTest < ActionController::TestCase
assert_equal "https://secure.cheeseburger.host/redirect_to_ssl/cheeseburger", redirect_to_url
end
- def test_banana_does_not_redirect_if_already_https
+ def test_cheeseburgers_does_not_redirect_if_already_https
request.env['HTTPS'] = 'on'
get :cheeseburger
assert_response 200
diff --git a/actionpack/test/controller/form_builder_test.rb b/actionpack/test/controller/form_builder_test.rb
new file mode 100644
index 0000000000..99eeaf9ab6
--- /dev/null
+++ b/actionpack/test/controller/form_builder_test.rb
@@ -0,0 +1,17 @@
+require 'abstract_unit'
+
+class FormBuilderController < ActionController::Base
+ class SpecializedFormBuilder < ActionView::Helpers::FormBuilder ; end
+
+ default_form_builder SpecializedFormBuilder
+end
+
+class ControllerFormBuilderTest < ActiveSupport::TestCase
+ setup do
+ @controller = FormBuilderController.new
+ end
+
+ def test_default_form_builder_assigned
+ assert_equal FormBuilderController::SpecializedFormBuilder, @controller.default_form_builder
+ end
+end
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index e263ed341f..3ecfedefd1 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -73,14 +73,8 @@ module LocalAbcHelper
end
class HelperPathsTest < ActiveSupport::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
def test_helpers_paths_priority
- request = ActionController::TestRequest.new
- responses = HelpersPathsController.action(:index).call(request.env)
+ responses = HelpersPathsController.action(:index).call(ActionController::TestRequest::DEFAULT_ENV.dup)
# helpers1_pack was given as a second path, so pack1_helper should be
# included as the second one
@@ -141,8 +135,7 @@ class HelperTest < ActiveSupport::TestCase
end
def call_controller(klass, action)
- request = ActionController::TestRequest.new
- klass.action(action).call(request.env)
+ klass.action(action).call(ActionController::TestRequest::DEFAULT_ENV.dup)
end
def test_helper_for_nested_controller
@@ -158,7 +151,7 @@ class HelperTest < ActiveSupport::TestCase
assert_equal "test: baz", call_controller(Fun::PdfController, "test").last.body
#
# request = ActionController::TestRequest.new
- # response = ActionController::TestResponse.new
+ # response = ActionDispatch::TestResponse.new
# request.action = 'test'
#
# assert_equal 'test: baz', Fun::PdfController.process(request, response).body
@@ -249,7 +242,7 @@ class HelperTest < ActiveSupport::TestCase
end
-class IsolatedHelpersTest < ActiveSupport::TestCase
+class IsolatedHelpersTest < ActionController::TestCase
class A < ActionController::Base
def index
render :inline => '<%= shout %>'
@@ -273,13 +266,11 @@ class IsolatedHelpersTest < ActiveSupport::TestCase
end
def call_controller(klass, action)
- request = ActionController::TestRequest.new
- klass.action(action).call(request.env)
+ klass.action(action).call(@request.env)
end
def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
+ super
@request.action = 'index'
end
diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb
index 20962a90cb..0a5e5402b9 100644
--- a/actionpack/test/controller/http_basic_authentication_test.rb
+++ b/actionpack/test/controller/http_basic_authentication_test.rb
@@ -9,19 +9,19 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
http_basic_authenticate_with :name => "David", :password => "Goliath", :only => :search
def index
- render :text => "Hello Secret"
+ render plain: "Hello Secret"
end
def display
- render :text => 'Definitely Maybe'
+ render plain: 'Definitely Maybe' if @logged_in
end
def show
- render :text => 'Only for loooooong credentials'
+ render plain: 'Only for loooooong credentials'
end
def search
- render :text => 'All inline'
+ render plain: 'All inline'
end
private
@@ -36,7 +36,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
if authenticate_with_http_basic { |username, password| username == 'pretty' && password == 'please' }
@logged_in = true
else
- request_http_basic_authentication("SuperSecret")
+ request_http_basic_authentication("SuperSecret", "Authentication Failed\n")
end
end
@@ -100,11 +100,19 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
assert_no_match(/\n/, result)
end
+ test "succesful authentication with uppercase authorization scheme" do
+ @request.env['HTTP_AUTHORIZATION'] = "BASIC #{::Base64.encode64("lifo:world")}"
+ get :index
+
+ assert_response :success
+ assert_equal 'Hello Secret', @response.body, 'Authentication failed when authorization scheme BASIC'
+ end
+
test "authentication request without credential" do
get :display
assert_response :unauthorized
- assert_equal "HTTP Basic: Access denied.\n", @response.body
+ assert_equal "Authentication Failed\n", @response.body
assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
end
@@ -113,7 +121,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
get :display
assert_response :unauthorized
- assert_equal "HTTP Basic: Access denied.\n", @response.body
+ assert_equal "Authentication Failed\n", @response.body
assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
end
@@ -122,7 +130,6 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 52a0bc9aa3..f06912bd5a 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -10,11 +10,11 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))}
def index
- render :text => "Hello Secret"
+ render plain: "Hello Secret"
end
def display
- render :text => 'Definitely Maybe'
+ render plain: 'Definitely Maybe' if @logged_in
end
private
@@ -124,7 +124,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -134,7 +133,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -144,7 +142,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -156,7 +153,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -167,7 +163,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -180,7 +175,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -191,7 +185,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -201,7 +194,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
put :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
@@ -244,7 +236,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
get :display
assert_response :success
- assert assigns(:logged_in)
assert_equal 'Definitely Maybe', @response.body
end
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index a758df2ec6..9c5a01c318 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -7,15 +7,15 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
before_action :authenticate_long_credentials, only: :show
def index
- render :text => "Hello Secret"
+ render plain: "Hello Secret"
end
def display
- render :text => 'Definitely Maybe'
+ render plain: 'Definitely Maybe'
end
def show
- render :text => 'Only for loooooong credentials'
+ render plain: 'Only for loooooong credentials'
end
private
@@ -30,7 +30,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
if authenticate_with_http_token { |token, options| token == '"quote" pretty' && options[:algorithm] == 'test' }
@logged_in = true
else
- request_http_token_authentication("SuperSecret")
+ request_http_token_authentication("SuperSecret", "Authentication Failed\n")
end
end
@@ -80,18 +80,25 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
end
test "authentication request with badly formatted header" do
- @request.env['HTTP_AUTHORIZATION'] = "Token foobar"
+ @request.env['HTTP_AUTHORIZATION'] = 'Token token$"lifo"'
get :index
assert_response :unauthorized
assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication header was not properly parsed"
end
+ test "successful authentication request with Bearer instead of Token" do
+ @request.env['HTTP_AUTHORIZATION'] = 'Bearer lifo'
+ get :index
+
+ assert_response :success
+ end
+
test "authentication request without credential" do
get :display
assert_response :unauthorized
- assert_equal "HTTP Token: Access denied.\n", @response.body
+ assert_equal "Authentication Failed\n", @response.body
assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate']
end
@@ -100,7 +107,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
get :display
assert_response :unauthorized
- assert_equal "HTTP Token: Access denied.\n", @response.body
+ assert_equal "Authentication Failed\n", @response.body
assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate']
end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index a87059bee4..d0a1d1285f 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -26,297 +26,341 @@ class SessionTest < ActiveSupport::TestCase
end
def test_follow_redirect_raises_when_no_redirect
- @session.stubs(:redirect?).returns(false)
- assert_raise(RuntimeError) { @session.follow_redirect! }
+ @session.stub :redirect?, false do
+ assert_raise(RuntimeError) { @session.follow_redirect! }
+ end
end
def test_request_via_redirect_uses_given_method
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
- @session.expects(:process).with(:put, path, params: args, headers: headers)
- @session.stubs(:redirect?).returns(false)
- @session.request_via_redirect(:put, path, params: args, headers: headers)
+ assert_called_with @session, :process, [:put, path, params: args, headers: headers] do
+ @session.stub :redirect?, false do
+ @session.request_via_redirect(:put, path, params: args, headers: headers)
+ end
+ end
end
def test_deprecated_request_via_redirect_uses_given_method
path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
- @session.expects(:process).with(:put, path, params: args, headers: headers)
- @session.stubs(:redirect?).returns(false)
- assert_deprecated { @session.request_via_redirect(:put, path, args, headers) }
+ assert_called_with @session, :process, [:put, path, params: args, headers: headers] do
+ @session.stub :redirect?, false do
+ assert_deprecated { @session.request_via_redirect(:put, path, args, headers) }
+ end
+ end
end
def test_request_via_redirect_follows_redirects
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
- @session.stubs(:redirect?).returns(true, true, false)
- @session.expects(:follow_redirect!).times(2)
- @session.request_via_redirect(:get, path, params: args, headers: headers)
+ value_series = [true, true, false]
+ assert_called @session, :follow_redirect!, times: 2 do
+ @session.stub :redirect?, ->{ value_series.shift } do
+ @session.request_via_redirect(:get, path, params: args, headers: headers)
+ end
+ end
end
def test_request_via_redirect_returns_status
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
- @session.stubs(:redirect?).returns(false)
- @session.stubs(:status).returns(200)
- assert_equal 200, @session.request_via_redirect(:get, path, params: args, headers: headers)
+ @session.stub :redirect?, false do
+ @session.stub :status, 200 do
+ assert_equal 200, @session.request_via_redirect(:get, path, params: args, headers: headers)
+ end
+ end
end
def test_deprecated_get_via_redirect
path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
- @session.expects(:request_via_redirect).with(:get, path, args, headers)
- assert_deprecated do
- @session.get_via_redirect(path, args, headers)
+ assert_called_with @session, :request_via_redirect, [:get, path, args, headers] do
+ assert_deprecated do
+ @session.get_via_redirect(path, args, headers)
+ end
end
end
def test_deprecated_post_via_redirect
path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
- @session.expects(:request_via_redirect).with(:post, path, args, headers)
- assert_deprecated do
- @session.post_via_redirect(path, args, headers)
+ assert_called_with @session, :request_via_redirect, [:post, path, args, headers] do
+ assert_deprecated do
+ @session.post_via_redirect(path, args, headers)
+ end
end
end
def test_deprecated_patch_via_redirect
path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
- @session.expects(:request_via_redirect).with(:patch, path, args, headers)
- assert_deprecated do
- @session.patch_via_redirect(path, args, headers)
+ assert_called_with @session, :request_via_redirect, [:patch, path, args, headers] do
+ assert_deprecated do
+ @session.patch_via_redirect(path, args, headers)
+ end
end
end
def test_deprecated_put_via_redirect
path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
- @session.expects(:request_via_redirect).with(:put, path, args, headers)
- assert_deprecated do
- @session.put_via_redirect(path, args, headers)
+ assert_called_with @session, :request_via_redirect, [:put, path, args, headers] do
+ assert_deprecated do
+ @session.put_via_redirect(path, args, headers)
+ end
end
end
def test_deprecated_delete_via_redirect
path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
- @session.expects(:request_via_redirect).with(:delete, path, args, headers)
- assert_deprecated do
- @session.delete_via_redirect(path, args, headers)
+ assert_called_with @session, :request_via_redirect, [:delete, path, args, headers] do
+ assert_deprecated do
+ @session.delete_via_redirect(path, args, headers)
+ end
end
end
def test_get
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:get, path, params: params, headers: headers)
- @session.get(path, params: params, headers: headers)
+
+ assert_called_with @session, :process, [:get, path, params: params, headers: headers] do
+ @session.get(path, params: params, headers: headers)
+ end
end
def test_get_with_env_and_headers
path = "/index"; params = "blah"; headers = { location: 'blah' }; env = { 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' }
- @session.expects(:process).with(:get, path, params: params, headers: headers, env: env)
- @session.get(path, params: params, headers: headers, env: env)
+ assert_called_with @session, :process, [:get, path, params: params, headers: headers, env: env] do
+ @session.get(path, params: params, headers: headers, env: env)
+ end
end
def test_deprecated_get
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:get, path, params: params, headers: headers)
- assert_deprecated {
- @session.get(path, params, headers)
- }
+
+ assert_called_with @session, :process, [:get, path, params: params, headers: headers] do
+ assert_deprecated {
+ @session.get(path, params, headers)
+ }
+ end
end
def test_post
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:post, path, params: params, headers: headers)
- assert_deprecated {
- @session.post(path, params, headers)
- }
+ assert_called_with @session, :process, [:post, path, params: params, headers: headers] do
+ assert_deprecated {
+ @session.post(path, params, headers)
+ }
+ end
end
def test_deprecated_post
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:post, path, params: params, headers: headers)
- @session.post(path, params: params, headers: headers)
+ assert_called_with @session, :process, [:post, path, params: params, headers: headers] do
+ @session.post(path, params: params, headers: headers)
+ end
end
def test_patch
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:patch, path, params: params, headers: headers)
- @session.patch(path, params: params, headers: headers)
+ assert_called_with @session, :process, [:patch, path, params: params, headers: headers] do
+ @session.patch(path, params: params, headers: headers)
+ end
end
def test_deprecated_patch
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:patch, path, params: params, headers: headers)
- assert_deprecated {
- @session.patch(path, params, headers)
- }
+ assert_called_with @session, :process, [:patch, path, params: params, headers: headers] do
+ assert_deprecated {
+ @session.patch(path, params, headers)
+ }
+ end
end
def test_put
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:put, path, params: params, headers: headers)
- @session.put(path, params: params, headers: headers)
+ assert_called_with @session, :process, [:put, path, params: params, headers: headers] do
+ @session.put(path, params: params, headers: headers)
+ end
end
def test_deprecated_put
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:put, path, params: params, headers: headers)
- assert_deprecated {
- @session.put(path, params, headers)
- }
+ assert_called_with @session, :process, [:put, path, params: params, headers: headers] do
+ assert_deprecated {
+ @session.put(path, params, headers)
+ }
+ end
end
def test_delete
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:delete, path, params: params, headers: headers)
- assert_deprecated {
- @session.delete(path,params,headers)
- }
+ assert_called_with @session, :process, [:delete, path, params: params, headers: headers] do
+ assert_deprecated {
+ @session.delete(path,params,headers)
+ }
+ end
end
def test_deprecated_delete
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:delete, path, params: params, headers: headers)
- @session.delete(path, params: params, headers: headers)
+ assert_called_with @session, :process, [:delete, path, params: params, headers: headers] do
+ @session.delete(path, params: params, headers: headers)
+ end
end
def test_head
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:head, path, params: params, headers: headers)
- @session.head(path, params: params, headers: headers)
+ assert_called_with @session, :process, [:head, path, params: params, headers: headers] do
+ @session.head(path, params: params, headers: headers)
+ end
end
def deprecated_test_head
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:head, path, params: params, headers: headers)
- assert_deprecated {
- @session.head(path, params, headers)
- }
+ assert_called_with @session, :process, [:head, path, params: params, headers: headers] do
+ assert_deprecated {
+ @session.head(path, params, headers)
+ }
+ end
end
def test_xml_http_request_get
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:get, path, params: params, headers: headers, xhr: true)
- @session.get(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:get, path, params: params, headers: headers, xhr: true] do
+ @session.get(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_xml_http_request_get
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:get, path, params: params, headers: headers, xhr: true)
- @session.get(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:get, path, params: params, headers: headers, xhr: true] do
+ @session.get(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_args_xml_http_request_get
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:get, path, params: params, headers: headers, xhr: true)
- assert_deprecated(/xml_http_request/) {
- @session.xml_http_request(:get, path, params, headers)
- }
+ assert_called_with @session, :process, [:get, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated(/xml_http_request/) {
+ @session.xml_http_request(:get, path, params, headers)
+ }
+ end
end
def test_xml_http_request_post
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:post, path, params: params, headers: headers, xhr: true)
- @session.post(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:post, path, params: params, headers: headers, xhr: true] do
+ @session.post(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_xml_http_request_post
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:post, path, params: params, headers: headers, xhr: true)
- @session.post(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:post, path, params: params, headers: headers, xhr: true] do
+ @session.post(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_args_xml_http_request_post
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:post, path, params: params, headers: headers, xhr: true)
- assert_deprecated(/xml_http_request/) { @session.xml_http_request(:post,path,params,headers) }
+ assert_called_with @session, :process, [:post, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:post,path,params,headers) }
+ end
end
def test_xml_http_request_patch
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:patch, path, params: params, headers: headers, xhr: true)
- @session.patch(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:patch, path, params: params, headers: headers, xhr: true] do
+ @session.patch(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_xml_http_request_patch
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:patch, path, params: params, headers: headers, xhr: true)
- @session.patch(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:patch, path, params: params, headers: headers, xhr: true] do
+ @session.patch(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_args_xml_http_request_patch
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:patch, path, params: params, headers: headers, xhr: true)
- assert_deprecated(/xml_http_request/) { @session.xml_http_request(:patch,path,params,headers) }
+ assert_called_with @session, :process, [:patch, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:patch,path,params,headers) }
+ end
end
def test_xml_http_request_put
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:put, path, params: params, headers: headers, xhr: true)
- @session.put(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:put, path, params: params, headers: headers, xhr: true] do
+ @session.put(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_xml_http_request_put
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:put, path, params: params, headers: headers, xhr: true)
- @session.put(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:put, path, params: params, headers: headers, xhr: true] do
+ @session.put(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_args_xml_http_request_put
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:put, path, params: params, headers: headers, xhr: true)
- assert_deprecated(/xml_http_request/) { @session.xml_http_request(:put, path, params, headers) }
+ assert_called_with @session, :process, [:put, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:put, path, params, headers) }
+ end
end
def test_xml_http_request_delete
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:delete, path, params: params, headers: headers, xhr: true)
- @session.delete(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:delete, path, params: params, headers: headers, xhr: true] do
+ @session.delete(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_xml_http_request_delete
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:delete, path, params: params, headers: headers, xhr: true)
- assert_deprecated { @session.xml_http_request(:delete, path, params: params, headers: headers) }
+ assert_called_with @session, :process, [:delete, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated { @session.xml_http_request(:delete, path, params: params, headers: headers) }
+ end
end
def test_deprecated_args_xml_http_request_delete
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:delete, path, params: params, headers: headers, xhr: true)
- assert_deprecated(/xml_http_request/) { @session.xml_http_request(:delete, path, params, headers) }
+ assert_called_with @session, :process, [:delete, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:delete, path, params, headers) }
+ end
end
def test_xml_http_request_head
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:head, path, params: params, headers: headers, xhr: true)
- @session.head(path, params: params, headers: headers, xhr: true)
+ assert_called_with @session, :process, [:head, path, params: params, headers: headers, xhr: true] do
+ @session.head(path, params: params, headers: headers, xhr: true)
+ end
end
def test_deprecated_xml_http_request_head
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:head, path, params: params, headers: headers, xhr: true)
- assert_deprecated(/xml_http_request/) { @session.xml_http_request(:head, path, params: params, headers: headers) }
+ assert_called_with @session, :process, [:head, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:head, path, params: params, headers: headers) }
+ end
end
def test_deprecated_args_xml_http_request_head
path = "/index"; params = "blah"; headers = { location: 'blah' }
- @session.expects(:process).with(:head, path, params: params, headers: headers, xhr: true)
- assert_deprecated { @session.xml_http_request(:head, path, params, headers) }
+ assert_called_with @session, :process, [:head, path, params: params, headers: headers, xhr: true] do
+ assert_deprecated { @session.xml_http_request(:head, path, params, headers) }
+ end
end
end
class IntegrationTestTest < ActiveSupport::TestCase
def setup
@test = ::ActionDispatch::IntegrationTest.new(:app)
- @test.class.stubs(:fixture_table_names).returns([])
- @session = @test.open_session
end
def test_opens_new_session
session1 = @test.open_session { |sess| }
session2 = @test.open_session # implicit session
- assert_respond_to session1, :assert_template, "open_session makes assert_template available"
- assert_respond_to session2, :assert_template, "open_session makes assert_template available"
assert !session1.equal?(session2)
end
@@ -342,14 +386,8 @@ end
# Tests that integration tests don't call Controller test methods for processing.
# Integration tests have their own setup and teardown.
class IntegrationTestUsesCorrectClass < ActionDispatch::IntegrationTest
- def self.fixture_table_names
- []
- end
-
def test_integration_methods_called
reset!
- @integration_session.stubs(:generic_url_rewriter)
- @integration_session.stubs(:process)
%w( get post head patch put delete ).each do |verb|
assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') }
@@ -361,28 +399,30 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
class IntegrationController < ActionController::Base
def get
respond_to do |format|
- format.html { render :text => "OK", :status => 200 }
- format.js { render :text => "JS OK", :status => 200 }
+ format.html { render plain: "OK", status: 200 }
+ format.js { render plain: "JS OK", status: 200 }
format.xml { render :xml => "<root></root>", :status => 200 }
+ format.rss { render :xml => "<root></root>", :status => 200 }
+ format.atom { render :xml => "<root></root>", :status => 200 }
end
end
def get_with_params
- render :text => "foo: #{params[:foo]}", :status => 200
+ render plain: "foo: #{params[:foo]}", status: 200
end
def post
- render :text => "Created", :status => 201
+ render plain: "Created", status: 201
end
def method
- render :text => "method: #{request.method.downcase}"
+ render plain: "method: #{request.method.downcase}"
end
def cookie_monster
cookies["cookie_1"] = nil
cookies["cookie_3"] = "chocolate"
- render :text => "Gone", :status => 410
+ render plain: "Gone", status: 410
end
def set_cookie
@@ -391,7 +431,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
end
def get_cookie
- render :text => cookies["foo"]
+ render plain: cookies["foo"]
end
def redirect
@@ -420,19 +460,21 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
end
end
- def test_get_xml
- with_test_route_set do
- get "/get", params: {}, headers: {"HTTP_ACCEPT" => "application/xml"}
- assert_equal 200, status
- assert_equal "OK", status_message
- assert_response 200
- assert_response :success
- assert_response :ok
- assert_equal({}, cookies.to_hash)
- assert_equal "<root></root>", body
- assert_equal "<root></root>", response.body
- assert_instance_of Nokogiri::XML::Document, html_document
- assert_equal 1, request_count
+ def test_get_xml_rss_atom
+ %w[ application/xml application/rss+xml application/atom+xml ].each do |mime_string|
+ with_test_route_set do
+ get "/get", headers: {"HTTP_ACCEPT" => mime_string}
+ assert_equal 200, status
+ assert_equal "OK", status_message
+ assert_response 200
+ assert_response :success
+ assert_response :ok
+ assert_equal({}, cookies.to_hash)
+ assert_equal "<root></root>", body
+ assert_equal "<root></root>", response.body
+ assert_instance_of Nokogiri::XML::Document, html_document
+ assert_equal 1, request_count
+ end
end
end
@@ -757,12 +799,31 @@ class MetalIntegrationTest < ActionDispatch::IntegrationTest
assert_equal "http://test.com/", @request.env["HTTP_REFERER"]
end
+ def test_ignores_common_ports_in_host
+ get "http://test.com"
+ assert_equal "test.com", @request.env["HTTP_HOST"]
+
+ get "https://test.com"
+ assert_equal "test.com", @request.env["HTTP_HOST"]
+ end
+
+ def test_keeps_uncommon_ports_in_host
+ get "http://test.com:123"
+ assert_equal "test.com:123", @request.env["HTTP_HOST"]
+
+ get "http://test.com:443"
+ assert_equal "test.com:443", @request.env["HTTP_HOST"]
+
+ get "https://test.com:80"
+ assert_equal "test.com:80", @request.env["HTTP_HOST"]
+ end
+
end
class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def index
- render :text => "index"
+ render plain: "index"
end
end
@@ -849,7 +910,7 @@ end
class EnvironmentFilterIntegrationTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def post
- render :text => "Created", :status => 201
+ render plain: "Created", status: 201
end
end
@@ -882,15 +943,15 @@ end
class UrlOptionsIntegrationTest < ActionDispatch::IntegrationTest
class FooController < ActionController::Base
def index
- render :text => "foo#index"
+ render plain: "foo#index"
end
def show
- render :text => "foo#show"
+ render plain: "foo#show"
end
def edit
- render :text => "foo#show"
+ render plain: "foo#show"
end
end
@@ -900,7 +961,7 @@ class UrlOptionsIntegrationTest < ActionDispatch::IntegrationTest
end
def index
- render :text => "foo#index"
+ render plain: "foo#index"
end
end
diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb
index 0c65270ec1..843dafac06 100644
--- a/actionpack/test/controller/live_stream_test.rb
+++ b/actionpack/test/controller/live_stream_test.rb
@@ -1,5 +1,5 @@
require 'abstract_unit'
-require 'active_support/concurrency/latch'
+require 'concurrent/atomic/count_down_latch'
Thread.abort_on_exception = true
module ActionController
@@ -112,7 +112,7 @@ module ActionController
class TestController < ActionController::Base
include ActionController::Live
- attr_accessor :latch, :tc
+ attr_accessor :latch, :tc, :error_latch
def self.controller_path
'test'
@@ -125,7 +125,7 @@ module ActionController
end
def render_text
- render :text => 'zomg'
+ render plain: 'zomg'
end
def default_header
@@ -145,7 +145,7 @@ module ActionController
response.headers['Content-Type'] = 'text/event-stream'
%w{ hello world }.each do |word|
response.stream.write word
- latch.await
+ latch.wait
end
response.stream.close
end
@@ -162,7 +162,7 @@ module ActionController
end
def with_stale
- render text: 'stale' if stale?(etag: "123", template: false)
+ render plain: 'stale' if stale?(etag: "123", template: false)
end
def exception_in_view
@@ -204,6 +204,12 @@ module ActionController
end
def overfill_buffer_and_die
+ logger = ActionController::Base.logger || Logger.new($stdout)
+ response.stream.on_error do
+ logger.warn 'Error while streaming'
+ error_latch.count_down
+ end
+
# Write until the buffer is full. It doesn't expose that
# information directly, so we must hard-code its size:
10.times do
@@ -212,7 +218,7 @@ module ActionController
# .. plus one more, because the #each frees up a slot:
response.stream.write '.'
- latch.release
+ latch.count_down
# This write will block, and eventually raise
response.stream.write 'x'
@@ -233,7 +239,7 @@ module ActionController
end
logger.info 'Work complete'
- latch.release
+ latch.count_down
end
end
@@ -256,20 +262,12 @@ module ActionController
end
def test_set_cookie
- @controller = TestController.new
get :set_cookie
assert_equal({'hello' => 'world'}, @response.cookies)
assert_equal "hello world", @response.body
end
- def test_set_response!
- @controller.set_response!(@request)
- assert_kind_of(Live::Response, @controller.response)
- assert_equal @request, @controller.response.request
- end
-
def test_write_to_stream
- @controller = TestController.new
get :basic_stream
assert_equal "helloworld", @response.body
assert_equal 'text/event-stream', @response.headers['Content-Type']
@@ -278,78 +276,65 @@ module ActionController
def test_async_stream
rubinius_skip "https://github.com/rubinius/rubinius/issues/2934"
- @controller.latch = ActiveSupport::Concurrency::Latch.new
+ @controller.latch = Concurrent::CountDownLatch.new
parts = ['hello', 'world']
- @controller.request = @request
- @controller.response = @response
+ get :blocking_stream
- t = Thread.new(@response) { |resp|
+ t = Thread.new(response) { |resp|
resp.await_commit
resp.stream.each do |part|
assert_equal parts.shift, part
ol = @controller.latch
- @controller.latch = ActiveSupport::Concurrency::Latch.new
- ol.release
+ @controller.latch = Concurrent::CountDownLatch.new
+ ol.count_down
end
}
- @controller.process :blocking_stream
-
assert t.join(3), 'timeout expired before the thread terminated'
end
def test_abort_with_full_buffer
- @controller.latch = ActiveSupport::Concurrency::Latch.new
-
- @request.parameters[:format] = 'plain'
- @controller.request = @request
- @controller.response = @response
-
- got_error = ActiveSupport::Concurrency::Latch.new
- @response.stream.on_error do
- ActionController::Base.logger.warn 'Error while streaming'
- got_error.release
- end
-
- t = Thread.new(@response) { |resp|
- resp.await_commit
- _, _, body = resp.to_a
- body.each do |part|
- @controller.latch.await
- body.close
- break
- end
- }
+ @controller.latch = Concurrent::CountDownLatch.new
+ @controller.error_latch = Concurrent::CountDownLatch.new
capture_log_output do |output|
- @controller.process :overfill_buffer_and_die
+ get :overfill_buffer_and_die, :format => 'plain'
+
+ t = Thread.new(response) { |resp|
+ resp.await_commit
+ _, _, body = resp.to_a
+ body.each do
+ @controller.latch.wait
+ body.close
+ break
+ end
+ }
+
t.join
- got_error.await
+ @controller.error_latch.wait
assert_match 'Error while streaming', output.rewind && output.read
end
end
def test_ignore_client_disconnect
- @controller.latch = ActiveSupport::Concurrency::Latch.new
+ @controller.latch = Concurrent::CountDownLatch.new
- @controller.request = @request
- @controller.response = @response
+ capture_log_output do |output|
+ get :ignore_client_disconnect
- t = Thread.new(@response) { |resp|
- resp.await_commit
- _, _, body = resp.to_a
- body.each do |part|
- body.close
- break
- end
- }
+ t = Thread.new(response) { |resp|
+ resp.await_commit
+ _, _, body = resp.to_a
+ body.each do
+ body.close
+ break
+ end
+ }
- capture_log_output do |output|
- @controller.process :ignore_client_disconnect
t.join
Timeout.timeout(3) do
- @controller.latch.await
+ @controller.latch.wait
end
assert_match 'Work complete', output.rewind && output.read
end
@@ -364,11 +349,8 @@ module ActionController
end
def test_live_stream_default_header
- @controller.request = @request
- @controller.response = @response
- @controller.process :default_header
- _, headers, _ = @response.prepare!
- assert headers['Content-Type']
+ get :default_header
+ assert response.headers['Content-Type']
end
def test_render_text
@@ -406,8 +388,14 @@ module ActionController
end
def test_exception_callback_when_committed
+ current_threads = Thread.list
+
capture_log_output do |output|
get :exception_with_callback, format: 'text/event-stream'
+
+ # Wait on the execution of all threads
+ (Thread.list - current_threads).each(&:join)
+
assert_equal %(data: "500 Internal Server Error"\n\n), response.body
assert_match 'An exception occurred...', output.rewind && output.read
assert_stream_closed
@@ -437,13 +425,13 @@ module ActionController
def test_stale_without_etag
get :with_stale
- assert_equal 200, @response.status.to_i
+ assert_equal 200, response.status.to_i
end
def test_stale_with_etag
@request.if_none_match = Digest::MD5.hexdigest("123")
get :with_stale
- assert_equal 304, @response.status.to_i
+ assert_equal 304, response.status.to_i
end
end
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index 03a4ad7823..6ae33be3c8 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -10,7 +10,7 @@ module Another
end
rescue_from SpecialException do
- head :status => 406
+ head 406
end
before_action :redirector, only: :never_executed
@@ -19,7 +19,7 @@ module Another
end
def show
- render :nothing => true
+ head :ok
end
def redirector
@@ -170,7 +170,7 @@ class ACLogSubscriberTest < ActionController::TestCase
def test_process_action_with_view_runtime
get :show
wait
- assert_match(/\(Views: [\d.]+ms\)/, logs[1])
+ assert_match(/Completed 200 OK in \d+ms/, logs[1])
end
def test_append_info_to_payload_is_called_even_with_exception
diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb
index 1f5f66dc80..c025c7fa00 100644
--- a/actionpack/test/controller/mime/respond_to_test.rb
+++ b/actionpack/test/controller/mime/respond_to_test.rb
@@ -1,45 +1,53 @@
require 'abstract_unit'
+require "active_support/log_subscriber/test_helper"
class RespondToController < ActionController::Base
layout :set_layout
+ before_action {
+ case params[:v]
+ when String then request.variant = params[:v].to_sym
+ when Array then request.variant = params[:v].map(&:to_sym)
+ end
+ }
+
def html_xml_or_rss
respond_to do |type|
- type.html { render :text => "HTML" }
- type.xml { render :text => "XML" }
- type.rss { render :text => "RSS" }
- type.all { render :text => "Nothing" }
+ type.html { render body: "HTML" }
+ type.xml { render body: "XML" }
+ type.rss { render body: "RSS" }
+ type.all { render body: "Nothing" }
end
end
def js_or_html
respond_to do |type|
- type.html { render :text => "HTML" }
- type.js { render :text => "JS" }
- type.all { render :text => "Nothing" }
+ type.html { render body: "HTML" }
+ type.js { render body: "JS" }
+ type.all { render body: "Nothing" }
end
end
def json_or_yaml
respond_to do |type|
- type.json { render :text => "JSON" }
- type.yaml { render :text => "YAML" }
+ type.json { render body: "JSON" }
+ type.yaml { render body: "YAML" }
end
end
def html_or_xml
respond_to do |type|
- type.html { render :text => "HTML" }
- type.xml { render :text => "XML" }
- type.all { render :text => "Nothing" }
+ type.html { render body: "HTML" }
+ type.xml { render body: "XML" }
+ type.all { render body: "Nothing" }
end
end
def json_xml_or_html
respond_to do |type|
- type.json { render :text => 'JSON' }
+ type.json { render body: 'JSON' }
type.xml { render :xml => 'XML' }
- type.html { render :text => 'HTML' }
+ type.html { render body: 'HTML' }
end
end
@@ -48,14 +56,14 @@ class RespondToController < ActionController::Base
request.format = :xml
respond_to do |type|
- type.html { render :text => "HTML" }
- type.xml { render :text => "XML" }
+ type.html { render body: "HTML" }
+ type.xml { render body: "XML" }
end
end
def just_xml
respond_to do |type|
- type.xml { render :text => "XML" }
+ type.xml { render body: "XML" }
end
end
@@ -73,52 +81,52 @@ class RespondToController < ActionController::Base
def using_defaults_with_all
respond_to do |type|
type.html
- type.all{ render text: "ALL" }
+ type.all { render body: "ALL" }
end
end
def made_for_content_type
respond_to do |type|
- type.rss { render :text => "RSS" }
- type.atom { render :text => "ATOM" }
- type.all { render :text => "Nothing" }
+ type.rss { render body: "RSS" }
+ type.atom { render body: "ATOM" }
+ type.all { render body: "Nothing" }
end
end
def custom_type_handling
respond_to do |type|
- type.html { render :text => "HTML" }
- type.custom("application/crazy-xml") { render :text => "Crazy XML" }
- type.all { render :text => "Nothing" }
+ type.html { render body: "HTML" }
+ type.custom("application/crazy-xml") { render body: "Crazy XML" }
+ type.all { render body: "Nothing" }
end
end
def custom_constant_handling
respond_to do |type|
- type.html { render :text => "HTML" }
- type.mobile { render :text => "Mobile" }
+ type.html { render body: "HTML" }
+ type.mobile { render body: "Mobile" }
end
end
def custom_constant_handling_without_block
respond_to do |type|
- type.html { render :text => "HTML" }
+ type.html { render body: "HTML" }
type.mobile
end
end
def handle_any
respond_to do |type|
- type.html { render :text => "HTML" }
- type.any(:js, :xml) { render :text => "Either JS or XML" }
+ type.html { render body: "HTML" }
+ type.any(:js, :xml) { render body: "Either JS or XML" }
end
end
def handle_any_any
respond_to do |type|
- type.html { render :text => 'HTML' }
- type.any { render :text => 'Whatever you ask for, I got it' }
+ type.html { render body: 'HTML' }
+ type.any { render body: 'Whatever you ask for, I got it' }
end
end
@@ -159,15 +167,15 @@ class RespondToController < ActionController::Base
request.variant = :mobile
respond_to do |type|
- type.html { render text: "mobile" }
+ type.html { render body: "mobile" }
end
end
def multiple_variants_for_format
respond_to do |type|
type.html do |html|
- html.tablet { render text: "tablet" }
- html.phone { render text: "phone" }
+ html.tablet { render body: "tablet" }
+ html.phone { render body: "phone" }
end
end
end
@@ -175,7 +183,7 @@ class RespondToController < ActionController::Base
def variant_plus_none_for_format
respond_to do |format|
format.html do |variant|
- variant.phone { render text: "phone" }
+ variant.phone { render body: "phone" }
variant.none
end
end
@@ -183,9 +191,9 @@ class RespondToController < ActionController::Base
def variant_inline_syntax
respond_to do |format|
- format.js { render text: "js" }
- format.html.none { render text: "none" }
- format.html.phone { render text: "phone" }
+ format.js { render body: "js" }
+ format.html.none { render body: "none" }
+ format.html.phone { render body: "phone" }
end
end
@@ -200,8 +208,8 @@ class RespondToController < ActionController::Base
def variant_any
respond_to do |format|
format.html do |variant|
- variant.any(:tablet, :phablet){ render text: "any" }
- variant.phone { render text: "phone" }
+ variant.any(:tablet, :phablet){ render body: "any" }
+ variant.phone { render body: "phone" }
end
end
end
@@ -209,23 +217,23 @@ class RespondToController < ActionController::Base
def variant_any_any
respond_to do |format|
format.html do |variant|
- variant.any { render text: "any" }
- variant.phone { render text: "phone" }
+ variant.any { render body: "any" }
+ variant.phone { render body: "phone" }
end
end
end
def variant_inline_any
respond_to do |format|
- format.html.any(:tablet, :phablet){ render text: "any" }
- format.html.phone { render text: "phone" }
+ format.html.any(:tablet, :phablet){ render body: "any" }
+ format.html.phone { render body: "phone" }
end
end
def variant_inline_any_any
respond_to do |format|
- format.html.phone { render text: "phone" }
- format.html.any { render text: "any" }
+ format.html.phone { render body: "phone" }
+ format.html.any { render body: "any" }
end
end
@@ -238,16 +246,16 @@ class RespondToController < ActionController::Base
def variant_any_with_none
respond_to do |format|
- format.html.any(:none, :phone){ render text: "none or phone" }
+ format.html.any(:none, :phone){ render body: "none or phone" }
end
end
def format_any_variant_any
respond_to do |format|
- format.html { render text: "HTML" }
+ format.html { render body: "HTML" }
format.any(:js, :xml) do |variant|
- variant.phone{ render text: "phone" }
- variant.any(:tablet, :phablet){ render text: "tablet" }
+ variant.phone{ render body: "phone" }
+ variant.any(:tablet, :phablet){ render body: "tablet" }
end
end
end
@@ -608,35 +616,40 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_invalid_variant
- @request.variant = :invalid
- assert_raises(ActionView::MissingTemplate) do
- get :variant_with_implicit_rendering
- end
+ logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
+ old_logger, ActionController::Base.logger = ActionController::Base.logger, logger
+
+ get :variant_with_implicit_rendering, params: { v: :invalid }
+ assert_response :no_content
+ assert_equal 1, logger.logged(:info).select{ |s| s =~ /No template found/ }.size, "Implicit head :no_content not logged"
+ ensure
+ ActionController::Base.logger = old_logger
end
def test_variant_not_set_regular_template_missing
- assert_raises(ActionView::MissingTemplate) do
- get :variant_with_implicit_rendering
- end
+ get :variant_with_implicit_rendering
+ assert_response :no_content
end
def test_variant_with_implicit_rendering
- @request.variant = :mobile
- get :variant_with_implicit_rendering
+ get :variant_with_implicit_rendering, params: { v: :implicit }
+ assert_response :no_content
+ end
+
+ def test_variant_with_implicit_template_rendering
+ get :variant_with_implicit_rendering, params: { v: :mobile }
assert_equal "text/html", @response.content_type
assert_equal "mobile", @response.body
end
def test_variant_with_format_and_custom_render
- @request.variant = :phone
- get :variant_with_format_and_custom_render
+ get :variant_with_format_and_custom_render, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "mobile", @response.body
end
def test_multiple_variants_for_format
- @request.variant = :tablet
- get :multiple_variants_for_format
+ get :multiple_variants_for_format, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "tablet", @response.body
end
@@ -656,32 +669,27 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "text/html", @response.content_type
assert_equal "none", @response.body
- @request.variant = :phone
- get :variant_inline_syntax
+ get :variant_inline_syntax, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_inline_syntax_without_block
- @request.variant = :phone
- get :variant_inline_syntax_without_block
+ get :variant_inline_syntax_without_block, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_any
- @request.variant = :phone
- get :variant_any
+ get :variant_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :tablet
- get :variant_any
+ get :variant_any, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
- @request.variant = :phablet
- get :variant_any
+ get :variant_any, params: { v: :phablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
@@ -691,54 +699,45 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
- @request.variant = :phone
- get :variant_any_any
+ get :variant_any_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :yolo
- get :variant_any_any
+ get :variant_any_any, params: { v: :yolo }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
def test_variant_inline_any
- @request.variant = :phone
- get :variant_any
+ get :variant_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :tablet
- get :variant_inline_any
+ get :variant_inline_any, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
- @request.variant = :phablet
- get :variant_inline_any
+ get :variant_inline_any, params: { v: :phablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
def test_variant_inline_any_any
- @request.variant = :phone
- get :variant_inline_any_any
+ get :variant_inline_any_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :yolo
- get :variant_inline_any_any
+ get :variant_inline_any_any, params: { v: :yolo }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
def test_variant_any_implicit_render
- @request.variant = :tablet
- get :variant_any_implicit_render
+ get :variant_any_implicit_render, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "tablet", @response.body
- @request.variant = :phablet
- get :variant_any_implicit_render
+ get :variant_any_implicit_render, params: { v: :phablet }
assert_equal "text/html", @response.content_type
assert_equal "phablet", @response.body
end
@@ -748,37 +747,53 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "text/html", @response.content_type
assert_equal "none or phone", @response.body
- @request.variant = :phone
- get :variant_any_with_none
+ get :variant_any_with_none, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "none or phone", @response.body
end
def test_format_any_variant_any
- @request.variant = :tablet
- get :format_any_variant_any, format: :js
+ get :format_any_variant_any, format: :js, params: { v: :tablet }
assert_equal "text/javascript", @response.content_type
assert_equal "tablet", @response.body
end
def test_variant_negotiation_inline_syntax
- @request.variant = [:tablet, :phone]
- get :variant_inline_syntax_without_block
+ get :variant_inline_syntax_without_block, params: { v: [:tablet, :phone] }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_negotiation_block_syntax
- @request.variant = [:tablet, :phone]
- get :variant_plus_none_for_format
+ get :variant_plus_none_for_format, params: { v: [:tablet, :phone] }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_negotiation_without_block
- @request.variant = [:tablet, :phone]
- get :variant_inline_syntax_without_block
+ get :variant_inline_syntax_without_block, params: { v: [:tablet, :phone] }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
end
+
+class RespondToWithBlockOnDefaultRenderController < ActionController::Base
+ def show
+ default_render do
+ render body: 'default_render yielded'
+ end
+ end
+end
+
+class RespondToWithBlockOnDefaultRenderControllerTest < ActionController::TestCase
+ def setup
+ super
+ @request.host = "www.example.com"
+ end
+
+ def test_default_render_uses_block_when_no_template_exists
+ get :show
+ assert_equal "default_render yielded", @response.body
+ assert_equal "text/plain", @response.content_type
+ end
+end
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 710c428dcc..e61f4d241b 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -2,8 +2,6 @@ require "abstract_unit"
module BareMetalTest
class BareController < ActionController::Metal
- include ActionController::RackDelegation
-
def index
self.response_body = "Hello world"
end
@@ -28,6 +26,8 @@ module BareMetalTest
test "response_body value is wrapped in an array when the value is a String" do
controller = BareController.new
+ controller.set_request!(ActionDispatch::Request.new({}))
+ controller.set_response!(BareController.make_response!(controller.request))
controller.index
assert_equal ["Hello world"], controller.response_body
end
@@ -37,8 +37,6 @@ module BareMetalTest
controller = BareController.new
controller.set_request! ActionDispatch::Request.new(env)
assert controller.request
- assert controller.response
- assert env['action_controller.instance']
end
end
@@ -123,34 +121,40 @@ module BareMetalTest
end
test "head :no_content (204) does not return any content" do
- content = HeadController.action(:no_content).call(Rack::MockRequest.env_for("/")).third.first
+ content = body(HeadController.action(:no_content).call(Rack::MockRequest.env_for("/")))
assert_empty content
end
test "head :reset_content (205) does not return any content" do
- content = HeadController.action(:reset_content).call(Rack::MockRequest.env_for("/")).third.first
+ content = body(HeadController.action(:reset_content).call(Rack::MockRequest.env_for("/")))
assert_empty content
end
test "head :not_modified (304) does not return any content" do
- content = HeadController.action(:not_modified).call(Rack::MockRequest.env_for("/")).third.first
+ content = body(HeadController.action(:not_modified).call(Rack::MockRequest.env_for("/")))
assert_empty content
end
test "head :continue (100) does not return any content" do
- content = HeadController.action(:continue).call(Rack::MockRequest.env_for("/")).third.first
+ content = body(HeadController.action(:continue).call(Rack::MockRequest.env_for("/")))
assert_empty content
end
test "head :switching_protocols (101) does not return any content" do
- content = HeadController.action(:switching_protocols).call(Rack::MockRequest.env_for("/")).third.first
+ content = body(HeadController.action(:switching_protocols).call(Rack::MockRequest.env_for("/")))
assert_empty content
end
test "head :processing (102) does not return any content" do
- content = HeadController.action(:processing).call(Rack::MockRequest.env_for("/")).third.first
+ content = body(HeadController.action(:processing).call(Rack::MockRequest.env_for("/")))
assert_empty content
end
+
+ def body(rack_response)
+ buf = []
+ rack_response[2].each { |x| buf << x }
+ buf.join
+ end
end
class BareControllerTest < ActionController::TestCase
diff --git a/actionpack/test/controller/new_base/base_test.rb b/actionpack/test/controller/new_base/base_test.rb
index 964f22eb03..0755dafe93 100644
--- a/actionpack/test/controller/new_base/base_test.rb
+++ b/actionpack/test/controller/new_base/base_test.rb
@@ -6,7 +6,7 @@ module Dispatching
before_action :authenticate
def index
- render :text => "success"
+ render body: "success"
end
def modify_response_body
@@ -22,7 +22,7 @@ module Dispatching
end
def show_actions
- render :text => "actions: #{action_methods.to_a.sort.join(', ')}"
+ render body: "actions: #{action_methods.to_a.sort.join(', ')}"
end
protected
@@ -51,7 +51,7 @@ module Dispatching
assert_body "success"
assert_status 200
- assert_content_type "text/html; charset=utf-8"
+ assert_content_type "text/plain; charset=utf-8"
end
# :api: plugin
diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb
index c8166280fc..c0e92b3b05 100644
--- a/actionpack/test/controller/new_base/content_negotiation_test.rb
+++ b/actionpack/test/controller/new_base/content_negotiation_test.rb
@@ -9,7 +9,7 @@ module ContentNegotiation
)]
def all
- render :text => self.formats.inspect
+ render plain: self.formats.inspect
end
end
diff --git a/actionpack/test/controller/new_base/content_type_test.rb b/actionpack/test/controller/new_base/content_type_test.rb
index 88453988dd..a9dcdde4b8 100644
--- a/actionpack/test/controller/new_base/content_type_test.rb
+++ b/actionpack/test/controller/new_base/content_type_test.rb
@@ -3,16 +3,16 @@ require 'abstract_unit'
module ContentType
class BaseController < ActionController::Base
def index
- render :text => "Hello world!"
+ render body: "Hello world!"
end
def set_on_response_obj
- response.content_type = Mime::RSS
- render :text => "Hello world!"
+ response.content_type = Mime[:rss]
+ render body: "Hello world!"
end
def set_on_render
- render :text => "Hello world!", :content_type => Mime::RSS
+ render body: "Hello world!", content_type: Mime[:rss]
end
end
@@ -30,17 +30,17 @@ module ContentType
class CharsetController < ActionController::Base
def set_on_response_obj
response.charset = "utf-16"
- render :text => "Hello world!"
+ render body: "Hello world!"
end
def set_as_nil_on_response_obj
response.charset = nil
- render :text => "Hello world!"
+ render body: "Hello world!"
end
end
class ExplicitContentTypeTest < Rack::TestCase
- test "default response is HTML and UTF8" do
+ test "default response is text/plain and UTF8" do
with_routing do |set|
set.draw do
get ':controller', :action => 'index'
@@ -49,7 +49,7 @@ module ContentType
get "/content_type/base"
assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-8"
+ assert_header "Content-Type", "text/plain; charset=utf-8"
end
end
@@ -99,14 +99,14 @@ module ContentType
get "/content_type/charset/set_on_response_obj"
assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-16"
+ assert_header "Content-Type", "text/plain; charset=utf-16"
end
test "setting the charset of the response as nil directly on the response object" do
get "/content_type/charset/set_as_nil_on_response_obj"
assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-8"
+ assert_header "Content-Type", "text/plain; charset=utf-8"
end
end
end
diff --git a/actionpack/test/controller/new_base/metal_test.rb b/actionpack/test/controller/new_base/metal_test.rb
deleted file mode 100644
index 537b93387a..0000000000
--- a/actionpack/test/controller/new_base/metal_test.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-require 'abstract_unit'
-
-module MetalTest
- class MetalMiddleware < ActionController::Middleware
- def call(env)
- if env["PATH_INFO"] =~ /authed/
- app.call(env)
- else
- [401, headers, "Not authed!"]
- end
- end
- end
-
- class Endpoint
- def call(env)
- [200, {}, "Hello World"]
- end
- end
-
- class TestMiddleware < ActiveSupport::TestCase
- def setup
- @app = Rack::Builder.new do
- use MetalTest::MetalMiddleware
- run MetalTest::Endpoint.new
- end.to_app
- end
-
- test "it can call the next app by using @app" do
- env = Rack::MockRequest.env_for("/authed")
- response = @app.call(env)
-
- assert_equal ["Hello World"], response[2]
- end
-
- test "it can return a response using the normal AC::Metal techniques" do
- env = Rack::MockRequest.env_for("/")
- response = @app.call(env)
-
- assert_equal ["Not authed!"], response[2]
- assert_equal 401, response[0]
- end
- end
-end
diff --git a/actionpack/test/controller/new_base/middleware_test.rb b/actionpack/test/controller/new_base/middleware_test.rb
index a30e937bb3..85a1f351f0 100644
--- a/actionpack/test/controller/new_base/middleware_test.rb
+++ b/actionpack/test/controller/new_base/middleware_test.rb
@@ -75,7 +75,7 @@ module MiddlewareTest
test "middleware that is 'use'd is called as part of the Rack application" do
result = @app.call(env_for("/"))
- assert_equal ["Hello World"], result[2]
+ assert_equal ["Hello World"], [].tap { |a| result[2].each { |x| a << x } }
assert_equal "Success", result[1]["Middleware-Test"]
end
diff --git a/actionpack/test/controller/new_base/render_html_test.rb b/actionpack/test/controller/new_base/render_html_test.rb
index fe11501eeb..e9ea57e329 100644
--- a/actionpack/test/controller/new_base/render_html_test.rb
+++ b/actionpack/test/controller/new_base/render_html_test.rb
@@ -179,7 +179,7 @@ module RenderHtml
test "rendering from minimal controller returns response with text/html content type" do
get "/render_html/minimal/index"
- assert_content_type "text/html"
+ assert_content_type "text/html; charset=utf-8"
end
test "rendering from normal controller returns response with text/html content type" do
diff --git a/actionpack/test/controller/new_base/render_plain_test.rb b/actionpack/test/controller/new_base/render_plain_test.rb
index 0e36d36b50..0881442bd0 100644
--- a/actionpack/test/controller/new_base/render_plain_test.rb
+++ b/actionpack/test/controller/new_base/render_plain_test.rb
@@ -157,7 +157,7 @@ module RenderPlain
test "rendering from minimal controller returns response with text/plain content type" do
get "/render_plain/minimal/index"
- assert_content_type "text/plain"
+ assert_content_type "text/plain; charset=utf-8"
end
test "rendering from normal controller returns response with text/plain content type" do
diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb
index 11a19ab783..963f2c2f5c 100644
--- a/actionpack/test/controller/new_base/render_test.rb
+++ b/actionpack/test/controller/new_base/render_test.rb
@@ -37,14 +37,14 @@ module Render
private
def secretz
- render :text => "FAIL WHALE!"
+ render plain: "FAIL WHALE!"
end
end
class DoubleRenderController < ActionController::Base
def index
- render :text => "hello"
- render :text => "world"
+ render plain: "hello"
+ render plain: "world"
end
end
diff --git a/actionpack/test/controller/new_base/render_text_test.rb b/actionpack/test/controller/new_base/render_text_test.rb
index 10bad57cd6..048458178c 100644
--- a/actionpack/test/controller/new_base/render_text_test.rb
+++ b/actionpack/test/controller/new_base/render_text_test.rb
@@ -73,7 +73,10 @@ module RenderText
class RenderTextTest < Rack::TestCase
test "rendering text from a minimal controller" do
- get "/render_text/minimal/index"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/minimal/index"
+ end
+
assert_body "Hello World!"
assert_status 200
end
@@ -82,7 +85,10 @@ module RenderText
with_routing do |set|
set.draw { get ':controller', action: 'index' }
- get "/render_text/simple"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/simple"
+ end
+
assert_body "hello david"
assert_status 200
end
@@ -92,7 +98,9 @@ module RenderText
with_routing do |set|
set.draw { get ':controller', action: 'index' }
- get "/render_text/with_layout"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout"
+ end
assert_body "hello david"
assert_status 200
@@ -100,59 +108,81 @@ module RenderText
end
test "rendering text, while also providing a custom status code" do
- get "/render_text/with_layout/custom_code"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/custom_code"
+ end
assert_body "hello world"
assert_status 404
end
test "rendering text with nil returns an empty body" do
- get "/render_text/with_layout/with_nil"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_nil"
+ end
assert_body ""
assert_status 200
end
test "Rendering text with nil and custom status code returns an empty body and the status" do
- get "/render_text/with_layout/with_nil_and_status"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_nil_and_status"
+ end
assert_body ""
assert_status 403
end
test "rendering text with false returns the string 'false'" do
- get "/render_text/with_layout/with_false"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_false"
+ end
assert_body "false"
assert_status 200
end
test "rendering text with layout: true" do
- get "/render_text/with_layout/with_layout_true"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_layout_true"
+ end
assert_body "hello world, I'm here!"
assert_status 200
end
test "rendering text with layout: 'greetings'" do
- get "/render_text/with_layout/with_custom_layout"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_custom_layout"
+ end
assert_body "hello world, I wish thee well."
assert_status 200
end
test "rendering text with layout: false" do
- get "/render_text/with_layout/with_layout_false"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_layout_false"
+ end
assert_body "hello world"
assert_status 200
end
test "rendering text with layout: nil" do
- get "/render_text/with_layout/with_layout_nil"
+ ActiveSupport::Deprecation.silence do
+ get "/render_text/with_layout/with_layout_nil"
+ end
assert_body "hello world"
assert_status 200
end
+
+ test "rendering text displays deprecation warning" do
+ assert_deprecated do
+ get "/render_text/with_layout/with_layout_nil"
+ end
+ end
end
end
diff --git a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
index 59be08db54..efaf8a96c3 100644
--- a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
+++ b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
require 'action_controller/metal/strong_parameters'
-require 'minitest/mock'
class AlwaysPermittedParametersTest < ActiveSupport::TestCase
def setup
diff --git a/actionpack/test/controller/parameters/nested_parameters_test.rb b/actionpack/test/controller/parameters/nested_parameters_test.rb
index 3b1257e8d5..7151a8567c 100644
--- a/actionpack/test/controller/parameters/nested_parameters_test.rb
+++ b/actionpack/test/controller/parameters/nested_parameters_test.rb
@@ -136,7 +136,7 @@ class NestedParametersTest < ActiveSupport::TestCase
authors_attributes: {
:'0' => { name: 'William Shakespeare', age_of_death: '52' },
:'1' => { name: 'Unattributed Assistant' },
- :'2' => { name: %w(injected names)}
+ :'2' => { name: %w(injected names) }
}
}
})
diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
index 2ed486516d..9f7d14e85d 100644
--- a/actionpack/test/controller/parameters/parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -194,6 +194,19 @@ class ParametersPermitTest < ActiveSupport::TestCase
assert_equal "monkey", @params.fetch(:foo) { "monkey" }
end
+ test "fetch doesnt raise ParameterMissing exception if there is a default that is nil" do
+ assert_equal nil, @params.fetch(:foo, nil)
+ assert_equal nil, @params.fetch(:foo) { nil }
+ end
+
+ test 'KeyError in fetch block should not be covered up' do
+ params = ActionController::Parameters.new
+ e = assert_raises(KeyError) do
+ params.fetch(:missing_key) { {}.fetch(:also_missing) }
+ end
+ assert_match(/:also_missing$/, e.message)
+ end
+
test "not permitted is sticky beyond merges" do
assert !@params.merge(a: "b").permitted?
end
@@ -253,7 +266,6 @@ class ParametersPermitTest < ActiveSupport::TestCase
assert @params.to_h.is_a? Hash
assert_not @params.to_h.is_a? ActionController::Parameters
- assert_equal @params.to_hash, @params.to_h
end
test "to_h returns converted hash when .permit_all_parameters is set" do
@@ -284,6 +296,5 @@ class ParametersPermitTest < ActiveSupport::TestCase
test "to_unsafe_h returns unfiltered params" do
assert @params.to_h.is_a? Hash
assert_not @params.to_h.is_a? ActionController::Parameters
- assert_equal @params.to_hash, @params.to_unsafe_h
end
end
diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb
index 8bf016d060..7226beed26 100644
--- a/actionpack/test/controller/params_wrapper_test.rb
+++ b/actionpack/test/controller/params_wrapper_test.rb
@@ -28,8 +28,17 @@ class ParamsWrapperTest < ActionController::TestCase
end
end
- class User; end
- class Person; end
+ class User
+ def self.attribute_names
+ []
+ end
+ end
+
+ class Person
+ def self.attribute_names
+ []
+ end
+ end
tests UsersController
@@ -155,33 +164,28 @@ class ParamsWrapperTest < ActionController::TestCase
end
def test_derived_wrapped_keys_from_matching_model
- User.expects(:respond_to?).with(:attribute_names).returns(true)
- User.expects(:attribute_names).twice.returns(["username"])
-
- with_default_wrapper_options do
- @request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
- assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
+ assert_called(User, :attribute_names, times: 2, returns: ["username"]) do
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
+ end
end
end
def test_derived_wrapped_keys_from_specified_model
with_default_wrapper_options do
- Person.expects(:respond_to?).with(:attribute_names).returns(true)
- Person.expects(:attribute_names).twice.returns(["username"])
+ assert_called(Person, :attribute_names, times: 2, returns: ["username"]) do
+ UsersController.wrap_parameters Person
- UsersController.wrap_parameters Person
-
- @request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
- assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }})
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }})
+ end
end
end
def test_not_wrapping_abstract_model
- User.expects(:respond_to?).with(:attribute_names).returns(true)
- User.expects(:attribute_names).returns([])
-
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
diff --git a/actionpack/test/controller/permitted_params_test.rb b/actionpack/test/controller/permitted_params_test.rb
index 7136fafae5..7c753a45a5 100644
--- a/actionpack/test/controller/permitted_params_test.rb
+++ b/actionpack/test/controller/permitted_params_test.rb
@@ -2,11 +2,11 @@ require 'abstract_unit'
class PeopleController < ActionController::Base
def create
- render text: params[:person].permitted? ? "permitted" : "forbidden"
+ render plain: params[:person].permitted? ? "permitted" : "forbidden"
end
def create_with_permit
- render text: params[:person].permit(:name).permitted? ? "permitted" : "forbidden"
+ render plain: params[:person].permit(:name).permitted? ? "permitted" : "forbidden"
end
end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index efd790de63..631ff7d02a 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -1,13 +1,10 @@
require 'abstract_unit'
-class WorkshopsController < ActionController::Base
-end
-
class RedirectController < ActionController::Base
# empty method not used anywhere to ensure methods like
# `status` and `location` aren't called on `redirect_to` calls
- def status; render :text => 'called status'; end
- def location; render :text => 'called location'; end
+ def status; render plain: 'called status'; end
+ def location; render plain: 'called location'; end
def simple_redirect
redirect_to :action => "hello_world"
@@ -53,11 +50,6 @@ class RedirectController < ActionController::Base
redirect_to :controller => 'module_test/module_redirect', :action => "hello_world"
end
- def redirect_with_assigns
- @hello = "world"
- redirect_to :action => "hello_world"
- end
-
def redirect_to_url
redirect_to "http://www.rubyonrails.org/"
end
@@ -218,12 +210,6 @@ class RedirectTest < ActionController::TestCase
assert_redirected_to :controller => 'module_test/module_redirect', :action => 'hello_world'
end
- def test_redirect_with_assigns
- get :redirect_with_assigns
- assert_response :redirect
- assert_equal "world", assigns["hello"]
- end
-
def test_redirect_to_url
get :redirect_to_url
assert_response :redirect
@@ -280,15 +266,17 @@ class RedirectTest < ActionController::TestCase
end
def test_redirect_to_nil
- assert_raise(ActionController::ActionControllerError) do
+ error = assert_raise(ActionController::ActionControllerError) do
get :redirect_to_nil
end
+ assert_equal "Cannot redirect to nil!", error.message
end
def test_redirect_to_params
- assert_raise(ActionController::ActionControllerError) do
+ error = assert_raise(ActionController::ActionControllerError) do
get :redirect_to_params
end
+ assert_equal "Cannot redirect to a parameter hash!", error.message
end
def test_redirect_to_with_block
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
index b1ad16bc55..3773900cc4 100644
--- a/actionpack/test/controller/render_json_test.rb
+++ b/actionpack/test/controller/render_json_test.rb
@@ -28,7 +28,7 @@ class RenderJsonTest < ActionController::TestCase
end
def render_json_render_to_string
- render :text => render_to_string(:json => '[]')
+ render plain: render_to_string(json: '[]')
end
def render_json_hello_world
diff --git a/actionpack/test/controller/render_other_test.rb b/actionpack/test/controller/render_other_test.rb
index af50e11261..1f5215ac55 100644
--- a/actionpack/test/controller/render_other_test.rb
+++ b/actionpack/test/controller/render_other_test.rb
@@ -12,7 +12,7 @@ class RenderOtherTest < ActionController::TestCase
def test_using_custom_render_option
ActionController.add_renderer :simon do |says, options|
- self.content_type = Mime::TEXT
+ self.content_type = Mime[:text]
self.response_body = "Simon says: #{says}"
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 79e2104789..256ebf6a07 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
require 'controller/fake_models'
-require 'pathname'
class TestControllerWithExtraEtags < ActionController::Base
etag { nil }
@@ -10,20 +9,25 @@ class TestControllerWithExtraEtags < ActionController::Base
etag { nil }
def fresh
- render text: "stale" if stale?(etag: '123', template: false)
+ render plain: "stale" if stale?(etag: '123', template: false)
end
def array
- render text: "stale" if stale?(etag: %w(1 2 3), template: false)
+ render plain: "stale" if stale?(etag: %w(1 2 3), template: false)
end
def with_template
if stale? template: 'test/hello_world'
- render text: 'stale'
+ render plain: 'stale'
end
end
end
+class ImplicitRenderTestController < ActionController::Base
+ def empty_action
+ end
+end
+
class TestController < ActionController::Base
protect_from_forgery
@@ -120,6 +124,10 @@ class TestController < ActionController::Base
render :action => 'hello_world'
end
+ def respond_with_empty_body
+ render nothing: true
+ end
+
def conditional_hello_with_bangs
render :action => 'hello_world'
end
@@ -129,6 +137,14 @@ class TestController < ActionController::Base
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
end
+ def head_with_status_hash
+ head status: :created
+ end
+
+ def head_with_hash_does_not_include_status
+ head warning: :deprecated
+ end
+
def head_created
head :created
end
@@ -142,31 +158,31 @@ class TestController < ActionController::Base
end
def head_with_location_header
- head :location => "/foo"
+ head :ok, :location => "/foo"
end
def head_with_location_object
- head :location => Customer.new("david", 1)
+ head :ok, :location => Customer.new("david", 1)
end
def head_with_symbolic_status
- head :status => params[:status].intern
+ head params[:status].intern
end
def head_with_integer_status
- head :status => params[:status].to_i
+ head params[:status].to_i
end
def head_with_string_status
- head :status => params[:status]
+ head params[:status]
end
def head_with_custom_header
- head :x_custom_header => "something"
+ head :ok, :x_custom_header => "something"
end
def head_with_www_authenticate_header
- head 'WWW-Authenticate' => 'something'
+ head :ok, 'WWW-Authenticate' => 'something'
end
def head_with_status_code_first
@@ -218,8 +234,6 @@ class MetalTestController < ActionController::Metal
include AbstractController::Rendering
include ActionView::Rendering
include ActionController::Rendering
- include ActionController::RackDelegation
-
def accessing_logger_in_template
render :inline => "<%= logger.class %>"
@@ -270,11 +284,18 @@ class ExpiresInRenderTest < ActionController::TestCase
assert_match(/no-transform/, @response.headers["Cache-Control"])
end
+ def test_render_nothing_deprecated
+ assert_deprecated do
+ get :respond_with_empty_body
+ end
+ end
+
def test_date_header_when_expires_in
time = Time.mktime(2011,10,30)
- Time.stubs(:now).returns(time)
- get :conditional_hello_with_expires_in
- assert_equal Time.now.httpdate, @response.headers["Date"]
+ Time.stub :now, time do
+ get :conditional_hello_with_expires_in
+ assert_equal Time.now.httpdate, @response.headers["Date"]
+ end
end
end
@@ -453,6 +474,15 @@ class MetalRenderTest < ActionController::TestCase
end
end
+class ImplicitRenderTest < ActionController::TestCase
+ tests ImplicitRenderTestController
+
+ def test_implicit_no_content_response
+ get :empty_action
+ assert_response :no_content
+ end
+end
+
class HeadRenderTest < ActionController::TestCase
tests TestController
@@ -466,6 +496,19 @@ class HeadRenderTest < ActionController::TestCase
assert_response :created
end
+ def test_passing_hash_to_head_as_first_parameter_deprecated
+ assert_deprecated do
+ get :head_with_status_hash
+ end
+ end
+
+ def test_head_with_default_value_is_deprecated
+ assert_deprecated do
+ get :head_with_hash_does_not_include_status
+ assert_response :ok
+ end
+ end
+
def test_head_created_with_application_json_content_type
post :head_created_with_application_json_content_type
assert @response.body.blank?
@@ -577,7 +620,7 @@ class HttpCacheForeverTest < ActionController::TestCase
class HttpCacheForeverController < ActionController::Base
def cache_me_forever
http_cache_forever(public: params[:public], version: params[:version] || 'v1') do
- render text: 'hello'
+ render plain: 'hello'
end
end
end
@@ -586,13 +629,13 @@ class HttpCacheForeverTest < ActionController::TestCase
def test_cache_with_public
get :cache_me_forever, params: {public: true}
- assert_equal "max-age=#{100.years.to_i}, public", @response.headers["Cache-Control"]
+ assert_equal "max-age=#{100.years}, public", @response.headers["Cache-Control"]
assert_not_nil @response.etag
end
def test_cache_with_private
get :cache_me_forever
- assert_equal "max-age=#{100.years.to_i}, private", @response.headers["Cache-Control"]
+ assert_equal "max-age=#{100.years}, private", @response.headers["Cache-Control"]
assert_not_nil @response.etag
assert_response :success
end
diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb
index 7a91577b17..f0fd7ddc5e 100644
--- a/actionpack/test/controller/render_xml_test.rb
+++ b/actionpack/test/controller/render_xml_test.rb
@@ -92,6 +92,6 @@ class RenderXmlTest < ActionController::TestCase
def test_should_use_implicit_content_type
get :implicit_content_type, format: 'atom'
- assert_equal Mime::ATOM, @response.content_type
+ assert_equal Mime[:atom], @response.content_type
end
end
diff --git a/actionpack/test/controller/renderer_test.rb b/actionpack/test/controller/renderer_test.rb
index b55a25430b..16d24fa82a 100644
--- a/actionpack/test/controller/renderer_test.rb
+++ b/actionpack/test/controller/renderer_test.rb
@@ -1,6 +1,10 @@
require 'abstract_unit'
class RendererTest < ActiveSupport::TestCase
+ test 'action controller base has a renderer' do
+ assert ActionController::Base.renderer
+ end
+
test 'creating with a controller' do
controller = CommentsController
renderer = ActionController::Renderer.for controller
@@ -57,8 +61,7 @@ class RendererTest < ActiveSupport::TestCase
end
test 'rendering with defaults' do
- renderer = ApplicationController.renderer
- renderer.defaults[:https] = true
+ renderer = ApplicationController.renderer.new https: true
content = renderer.render inline: '<%= request.ssl? %>'
assert_equal 'true', content
@@ -67,8 +70,8 @@ class RendererTest < ActiveSupport::TestCase
test 'same defaults from the same controller' do
renderer_defaults = ->(controller) { controller.renderer.defaults }
- assert renderer_defaults[AccountsController].equal? renderer_defaults[AccountsController]
- assert_not renderer_defaults[AccountsController].equal? renderer_defaults[CommentsController]
+ assert_equal renderer_defaults[AccountsController], renderer_defaults[AccountsController]
+ assert_equal renderer_defaults[AccountsController], renderer_defaults[CommentsController]
end
test 'rendering with different formats' do
@@ -83,18 +86,6 @@ class RendererTest < ActiveSupport::TestCase
test 'rendering with helpers' do
assert_equal "<p>1\n<br />2</p>", render[inline: '<%= simple_format "1\n2" %>']
end
-
- test 'rendering from inherited renderer' do
- inherited = Class.new ApplicationController.renderer do
- defaults[:script_name] = 'script'
- def render(options)
- super options.merge(locals: { param: :value })
- end
- end
-
- template = '<%= url_for controller: :foo, action: :bar, param: param %>'
- assert_equal 'script/foo/bar?param=value', inherited.render(inline: template)
- end
private
def render
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
index 77a2f68b1c..e5d698d5c2 100644
--- a/actionpack/test/controller/request/test_request_test.rb
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -1,11 +1,7 @@
require 'abstract_unit'
require 'stringio'
-class ActionController::TestRequestTest < ActiveSupport::TestCase
-
- def setup
- @request = ActionController::TestRequest.new
- end
+class ActionController::TestRequestTest < ActionController::TestCase
def test_test_request_has_session_options_initialized
assert @request.session_options
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 8887f291cf..94ffbe3cd0 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'digest/sha1'
require "active_support/log_subscriber/test_helper"
# common controller actions
@@ -12,30 +11,14 @@ module RequestForgeryProtectionActions
render :inline => "<%= button_to('New', '/') %>"
end
- def external_form
- render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>"
- end
-
- def external_form_without_protection
- render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>"
- end
-
def unsafe
- render :text => 'pwn'
+ render plain: 'pwn'
end
def meta
render :inline => "<%= csrf_meta_tags %>"
end
- def external_form_for
- render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>"
- end
-
- def form_for_without_protection
- render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>"
- end
-
def form_for_remote
render :inline => "<%= form_for(:some_resource, :remote => true ) {} %>"
end
@@ -70,7 +53,6 @@ module RequestForgeryProtectionActions
negotiate_same_origin
end
- def rescue_action(e) raise e end
end
# sample controllers
@@ -89,17 +71,17 @@ class RequestForgeryProtectionControllerUsingNullSession < ActionController::Bas
def signed
cookies.signed[:foo] = 'bar'
- render :nothing => true
+ head :ok
end
def encrypted
cookies.encrypted[:foo] = 'bar'
- render :nothing => true
+ head :ok
end
def try_to_reset_session
reset_session
- render :nothing => true
+ head :ok
end
end
@@ -149,10 +131,7 @@ end
# common test methods
module RequestForgeryProtectionTests
def setup
- @token = "cf50faa3fe97702ca1ae"
- @controller.stubs(:form_authenticity_token).returns(@token)
- @controller.stubs(:valid_authenticity_token?).with{ |_, t| t == @token }.returns(true)
- @controller.stubs(:valid_authenticity_token?).with{ |_, t| t != @token }.returns(false)
+ @token = Base64.strict_encode64('railstestrailstestrailstestrails')
@old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token
ActionController::Base.request_forgery_protection_token = :custom_authenticity_token
end
@@ -162,17 +141,21 @@ module RequestForgeryProtectionTests
end
def test_should_render_form_with_token_tag
- assert_not_blocked do
- get :index
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked do
+ get :index
+ end
+ assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
- assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
def test_should_render_button_to_with_token_tag
- assert_not_blocked do
- get :show_button
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked do
+ get :show_button
+ end
+ assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
- assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
def test_should_render_form_without_token_tag_if_remote
@@ -216,17 +199,21 @@ module RequestForgeryProtectionTests
end
def test_should_render_form_with_token_tag_if_remote_and_authenticity_token_requested
- assert_not_blocked do
- get :form_for_remote_with_token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked do
+ get :form_for_remote_with_token
+ end
+ assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
- assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
def test_should_render_form_with_token_tag_with_authenticity_token_requested
- assert_not_blocked do
- get :form_for_with_token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked do
+ get :form_for_with_token
+ end
+ assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
- assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
def test_should_allow_get
@@ -266,37 +253,53 @@ module RequestForgeryProtectionTests
end
def test_should_allow_post_with_token
- assert_not_blocked { post :index, params: { custom_authenticity_token: @token } }
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked { post :index, params: { custom_authenticity_token: @token } }
+ end
end
def test_should_allow_patch_with_token
- assert_not_blocked { patch :index, params: { custom_authenticity_token: @token } }
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked { patch :index, params: { custom_authenticity_token: @token } }
+ end
end
def test_should_allow_put_with_token
- assert_not_blocked { put :index, params: { custom_authenticity_token: @token } }
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked { put :index, params: { custom_authenticity_token: @token } }
+ end
end
def test_should_allow_delete_with_token
- assert_not_blocked { delete :index, params: { custom_authenticity_token: @token } }
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked { delete :index, params: { custom_authenticity_token: @token } }
+ end
end
def test_should_allow_post_with_token_in_header
+ session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { post :index }
end
def test_should_allow_delete_with_token_in_header
+ session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { delete :index }
end
def test_should_allow_patch_with_token_in_header
+ session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { patch :index }
end
def test_should_allow_put_with_token_in_header
+ session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { put :index }
end
@@ -350,6 +353,7 @@ module RequestForgeryProtectionTests
# Allow non-GET requests since GET is all a remote <script> tag can muster.
def test_should_allow_non_get_js_without_xhr_header
+ session[:_csrf_token] = @token
assert_cross_origin_not_blocked { post :same_origin_js, params: { custom_authenticity_token: @token } }
assert_cross_origin_not_blocked { post :same_origin_js, params: { format: 'js', custom_authenticity_token: @token } }
assert_cross_origin_not_blocked do
@@ -375,7 +379,6 @@ module RequestForgeryProtectionTests
end
def test_should_not_raise_error_if_token_is_not_a_string
- @controller.unstub(:valid_authenticity_token?)
assert_blocked do
patch :index, params: { custom_authenticity_token: { foo: 'bar' } }
end
@@ -419,11 +422,13 @@ class RequestForgeryProtectionControllerUsingResetSessionTest < ActionController
end
test 'should emit a csrf-param meta tag and a csrf-token meta tag' do
- @controller.stubs(:form_authenticity_token).returns(@token + '<=?')
- get :meta
- assert_select 'meta[name=?][content=?]', 'csrf-param', 'custom_authenticity_token'
- assert_select 'meta[name=?]', 'csrf-token'
- assert_match(/cf50faa3fe97702ca1ae&lt;=\?/, @response.body)
+ @controller.stub :form_authenticity_token, @token + '<=?' do
+ get :meta
+ assert_select 'meta[name=?][content=?]', 'csrf-param', 'custom_authenticity_token'
+ assert_select 'meta[name=?]', 'csrf-token'
+ regexp = "#{@token}&lt;=\?"
+ assert_match(/#{regexp}/, @response.body)
+ end
end
end
@@ -501,32 +506,37 @@ end
class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@token = "cf50faa3fe97702ca1ae"
-
- SecureRandom.stubs(:base64).returns(@token)
+ super
end
def test_should_not_render_form_with_token_tag
- get :index
- assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
+ SecureRandom.stub :base64, @token do
+ get :index
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
+ end
end
def test_should_not_render_button_to_with_token_tag
- get :show_button
- assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
+ SecureRandom.stub :base64, @token do
+ get :show_button
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
+ end
end
def test_should_allow_all_methods_without_token
- [:post, :patch, :put, :delete].each do |method|
- assert_nothing_raised { send(method, :index)}
+ SecureRandom.stub :base64, @token do
+ [:post, :patch, :put, :delete].each do |method|
+ assert_nothing_raised { send(method, :index)}
+ end
end
end
test 'should not emit a csrf-token meta tag' do
- get :meta
- assert @response.body.blank?
+ SecureRandom.stub :base64, @token do
+ get :meta
+ assert @response.body.blank?
+ end
end
end
@@ -547,11 +557,11 @@ class CustomAuthenticityParamControllerTest < ActionController::TestCase
def test_should_not_warn_if_form_authenticity_param_matches_form_authenticity_token
ActionController::Base.logger = @logger
- @controller.stubs(:valid_authenticity_token?).returns(:true)
-
begin
- post :index, params: { custom_token_name: 'foobar' }
- assert_equal 0, @logger.logged(:warn).size
+ @controller.stub :valid_authenticity_token?, :true do
+ post :index, params: { custom_token_name: 'foobar' }
+ assert_equal 0, @logger.logged(:warn).size
+ end
ensure
ActionController::Base.logger = @old_logger
end
diff --git a/actionpack/test/controller/required_params_test.rb b/actionpack/test/controller/required_params_test.rb
index a901e56332..168f64ce41 100644
--- a/actionpack/test/controller/required_params_test.rb
+++ b/actionpack/test/controller/required_params_test.rb
@@ -48,4 +48,21 @@ class ParametersRequireTest < ActiveSupport::TestCase
ActionController::Parameters.new(person: {}).require(:person)
end
end
+
+ test "require array when all required params are present" do
+ safe_params = ActionController::Parameters.new(person: {first_name: 'Gaurish', title: 'Mjallo', city: 'Barcelona'})
+ .require(:person)
+ .require([:first_name, :title])
+
+ assert_kind_of Array, safe_params
+ assert_equal ['Gaurish', 'Mjallo'], safe_params
+ end
+
+ test "require array when a required param is missing" do
+ assert_raises(ActionController::ParameterMissing) do
+ ActionController::Parameters.new(person: {first_name: 'Gaurish', title: nil})
+ .require(:person)
+ .require([:first_name, :title])
+ end
+ end
end
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index 4898b0c57f..f42bef883f 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -43,29 +43,29 @@ class RescueController < ActionController::Base
rescue_from NotAllowed, :with => proc { head :forbidden }
rescue_from 'RescueController::NotAllowedToRescueAsString', :with => proc { head :forbidden }
- rescue_from InvalidRequest, :with => proc { |exception| render :text => exception.message }
- rescue_from 'InvalidRequestToRescueAsString', :with => proc { |exception| render :text => exception.message }
+ rescue_from InvalidRequest, with: proc { |exception| render plain: exception.message }
+ rescue_from 'InvalidRequestToRescueAsString', with: proc { |exception| render plain: exception.message }
rescue_from BadGateway do
- head :status => 502
+ head 502
end
rescue_from 'BadGatewayToRescueAsString' do
- head :status => 502
+ head 502
end
rescue_from ResourceUnavailable do |exception|
- render :text => exception.message
+ render plain: exception.message
end
rescue_from 'ResourceUnavailableToRescueAsString' do |exception|
- render :text => exception.message
+ render plain: exception.message
end
rescue_from ActionView::TemplateError do
- render :text => 'action_view templater error'
+ render plain: 'action_view templater error'
end
rescue_from IOError do
- render :text => 'io error'
+ render plain: 'io error'
end
before_action(only: :before_action_raises) { raise 'umm nice' }
@@ -74,7 +74,7 @@ class RescueController < ActionController::Base
end
def raises
- render :text => 'already rendered'
+ render plain: 'already rendered'
raise "don't panic!"
end
@@ -132,11 +132,19 @@ class RescueController < ActionController::Base
end
def io_error_in_view
- raise ActionView::TemplateError.new(nil, IOError.new('this is io error'))
+ begin
+ raise IOError.new('this is io error')
+ rescue
+ raise ActionView::TemplateError.new(nil)
+ end
end
def zero_division_error_in_view
- raise ActionView::TemplateError.new(nil, ZeroDivisionError.new('this is zero division error'))
+ begin
+ raise ZeroDivisionError.new('this is zero division error')
+ rescue
+ raise ActionView::TemplateError.new(nil)
+ end
end
protected
@@ -246,12 +254,15 @@ class RescueControllerTest < ActionController::TestCase
end
def test_rescue_handler_with_argument
- @controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) }
- get :record_invalid
+ assert_called_with @controller, :show_errors, [Exception] do
+ get :record_invalid
+ end
end
+
def test_rescue_handler_with_argument_as_string
- @controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) }
- get :record_invalid_raise_as_string
+ assert_called_with @controller, :show_errors, [Exception] do
+ get :record_invalid_raise_as_string
+ end
end
def test_proc_rescue_handler
@@ -302,7 +313,7 @@ class RescueTest < ActionDispatch::IntegrationTest
rescue_from RecordInvalid, :with => :show_errors
def foo
- render :text => "foo"
+ render plain: "foo"
end
def invalid
@@ -315,7 +326,7 @@ class RescueTest < ActionDispatch::IntegrationTest
protected
def show_errors(exception)
- render :text => exception.message
+ render plain: exception.message
end
end
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index f3da2df3ef..4490abf7b2 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -149,7 +149,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_restful_named_routes_for :messages do |options|
+ assert_restful_named_routes_for :messages do
actions.each_key do |action|
assert_named_route "/messages/#{action}", "#{action}_messages_path", :action => action
end
@@ -179,7 +179,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do
actions.each_key do |action|
assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action
end
@@ -206,7 +206,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do
actions.each_key do |action|
assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action
end
@@ -236,7 +236,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do
actions.each_key do |action|
assert_named_route "/threads/1/messages/#{action}.xml", "#{action}_thread_messages_path", :action => action, :format => 'xml'
end
@@ -253,7 +253,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method)
end
- assert_restful_named_routes_for :messages do |options|
+ assert_restful_named_routes_for :messages do
assert_named_route mark_path, :mark_message_path, mark_options
end
end
@@ -278,7 +278,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method)
end
- assert_restful_named_routes_for :messages, :path_names => {:new => 'nuevo'} do |options|
+ assert_restful_named_routes_for :messages, :path_names => {:new => 'nuevo'} do
assert_named_route mark_path, :mark_message_path, mark_options
end
end
@@ -304,7 +304,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(action_options), :path => action_path, :method => method)
end
- assert_restful_named_routes_for :messages do |options|
+ assert_restful_named_routes_for :messages do
assert_named_route action_path, "#{action}_message_path".to_sym, action_options
end
end
@@ -351,7 +351,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post)
end
- assert_restful_named_routes_for :messages do |options|
+ assert_restful_named_routes_for :messages do
assert_named_route preview_path, :preview_new_message_path, preview_options
end
end
@@ -373,7 +373,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post)
end
- assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do
assert_named_route preview_path, :preview_new_thread_message_path, preview_options
end
end
@@ -395,7 +395,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post)
end
- assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do
assert_named_route preview_path, :preview_new_thread_message_path, preview_options
end
end
@@ -505,8 +505,8 @@ class ResourcesTest < ActionController::TestCase
routes = @routes.routes
routes.each do |route|
routes.each do |r|
- next if route === r # skip the comparison instance
- assert_not_equal [route.conditions, route.path.spec.to_s], [r.conditions, r.path.spec.to_s]
+ next if route == r # skip the comparison instance
+ assert_not_equal [route.conditions, route.path.spec.to_s, route.verb], [r.conditions, r.path.spec.to_s, r.verb]
end
end
end
@@ -519,9 +519,9 @@ class ResourcesTest < ActionController::TestCase
end
def test_should_create_multiple_singleton_resource_routes
- with_singleton_resources :account, :logo do
+ with_singleton_resources :account, :product do
assert_singleton_restful_for :account
- assert_singleton_restful_for :logo
+ assert_singleton_restful_for :product
end
end
@@ -553,7 +553,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(reset_options), :path => reset_path, :method => method)
end
- assert_singleton_named_routes_for :account do |options|
+ assert_singleton_named_routes_for :account do
assert_named_route reset_path, :reset_account_path, reset_options
end
end
@@ -577,7 +577,7 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(options.merge(action_options), :path => action_path, :method => method)
end
- assert_singleton_named_routes_for :account do |options|
+ assert_singleton_named_routes_for :account do
assert_named_route action_path, "#{action}_account_path".to_sym, action_options
end
end
@@ -1070,8 +1070,8 @@ class ResourcesTest < ActionController::TestCase
end
def test_singleton_resource_name_is_not_singularized
- with_singleton_resources(:preferences) do
- assert_singleton_restful_for :preferences
+ with_singleton_resources(:products) do
+ assert_singleton_restful_for :products
end
end
@@ -1128,14 +1128,14 @@ class ResourcesTest < ActionController::TestCase
end
def assert_restful_routes_for(controller_name, options = {})
- options[:options] ||= {}
- options[:options][:controller] = options[:controller] || controller_name.to_s
+ route_options = (options[:options] ||= {}).dup
+ route_options[:controller] = options[:controller] || controller_name.to_s
if options[:shallow]
options[:shallow_options] ||= {}
- options[:shallow_options][:controller] = options[:options][:controller]
+ options[:shallow_options][:controller] = route_options[:controller]
else
- options[:shallow_options] = options[:options]
+ options[:shallow_options] = route_options
end
new_action = @routes.resources_path_names[:new] || "new"
@@ -1154,7 +1154,7 @@ class ResourcesTest < ActionController::TestCase
edit_member_path = "#{member_path}/#{edit_action}"
formatted_edit_member_path = "#{member_path}/#{edit_action}.xml"
- with_options(options[:options]) do |controller|
+ with_options(route_options) do |controller|
controller.assert_routing collection_path, :action => 'index'
controller.assert_routing new_path, :action => 'new'
controller.assert_routing "#{collection_path}.xml", :action => 'index', :format => 'xml'
@@ -1168,23 +1168,23 @@ class ResourcesTest < ActionController::TestCase
controller.assert_routing formatted_edit_member_path, :action => 'edit', :id => '1', :format => 'xml'
end
- assert_recognizes(options[:options].merge(:action => 'index'), :path => collection_path, :method => :get)
- assert_recognizes(options[:options].merge(:action => 'new'), :path => new_path, :method => :get)
- assert_recognizes(options[:options].merge(:action => 'create'), :path => collection_path, :method => :post)
+ assert_recognizes(route_options.merge(:action => 'index'), :path => collection_path, :method => :get)
+ assert_recognizes(route_options.merge(:action => 'new'), :path => new_path, :method => :get)
+ assert_recognizes(route_options.merge(:action => 'create'), :path => collection_path, :method => :post)
assert_recognizes(options[:shallow_options].merge(:action => 'show', :id => '1'), :path => member_path, :method => :get)
assert_recognizes(options[:shallow_options].merge(:action => 'edit', :id => '1'), :path => edit_member_path, :method => :get)
assert_recognizes(options[:shallow_options].merge(:action => 'update', :id => '1'), :path => member_path, :method => :put)
assert_recognizes(options[:shallow_options].merge(:action => 'destroy', :id => '1'), :path => member_path, :method => :delete)
- assert_recognizes(options[:options].merge(:action => 'index', :format => 'xml'), :path => "#{collection_path}.xml", :method => :get)
- assert_recognizes(options[:options].merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get)
- assert_recognizes(options[:options].merge(:action => 'create', :format => 'xml'), :path => "#{collection_path}.xml", :method => :post)
+ assert_recognizes(route_options.merge(:action => 'index', :format => 'xml'), :path => "#{collection_path}.xml", :method => :get)
+ assert_recognizes(route_options.merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get)
+ assert_recognizes(route_options.merge(:action => 'create', :format => 'xml'), :path => "#{collection_path}.xml", :method => :post)
assert_recognizes(options[:shallow_options].merge(:action => 'show', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :get)
assert_recognizes(options[:shallow_options].merge(:action => 'edit', :id => '1', :format => 'xml'), :path => formatted_edit_member_path, :method => :get)
assert_recognizes(options[:shallow_options].merge(:action => 'update', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :put)
assert_recognizes(options[:shallow_options].merge(:action => 'destroy', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :delete)
- yield options[:options] if block_given?
+ yield route_options if block_given?
end
# test named routes like foo_path and foos_path map to the correct options.
@@ -1195,22 +1195,20 @@ class ResourcesTest < ActionController::TestCase
end
singular_name ||= controller_name.to_s.singularize
- options[:options] ||= {}
- options[:options][:controller] = options[:controller] || controller_name.to_s
+ route_options = (options[:options] ||= {}).dup
+ route_options[:controller] = options[:controller] || controller_name.to_s
if options[:shallow]
options[:shallow_options] ||= {}
- options[:shallow_options][:controller] = options[:options][:controller]
+ options[:shallow_options][:controller] = route_options[:controller]
else
- options[:shallow_options] = options[:options]
+ options[:shallow_options] = route_options
end
- @controller = "#{options[:options][:controller].camelize}Controller".constantize.new
+ @controller = "#{route_options[:controller].camelize}Controller".constantize.new
@controller.singleton_class.include(@routes.url_helpers)
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- get :index, params: options[:options]
- options[:options].delete :action
+ get :index, params: route_options
+ route_options.delete :action
path = "#{options[:as] || controller_name}"
shallow_path = "/#{options[:shallow] ? options[:namespace] : options[:path_prefix]}#{path}"
@@ -1225,29 +1223,29 @@ class ResourcesTest < ActionController::TestCase
edit_action = options[:path_names][:edit] || "edit"
end
- assert_named_route "#{full_path}", "#{name_prefix}#{controller_name}_path", options[:options]
- assert_named_route "#{full_path}.xml", "#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}", "#{name_prefix}#{controller_name}_path", route_options
+ assert_named_route "#{full_path}.xml", "#{name_prefix}#{controller_name}_path", route_options.merge(:format => 'xml')
assert_named_route "#{shallow_path}/1", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1')
assert_named_route "#{shallow_path}/1.xml", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
- assert_named_route "#{full_path}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options]
- assert_named_route "#{full_path}/#{new_action}.xml", "new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", route_options
+ assert_named_route "#{full_path}/#{new_action}.xml", "new_#{name_prefix}#{singular_name}_path", route_options.merge(:format => 'xml')
assert_named_route "#{shallow_path}/1/#{edit_action}", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1')
assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
- yield options[:options] if block_given?
+ yield route_options if block_given?
end
def assert_singleton_routes_for(singleton_name, options = {})
- options[:options] ||= {}
- options[:options][:controller] = options[:controller] || singleton_name.to_s.pluralize
+ route_options = (options[:options] ||= {}).dup
+ route_options[:controller] = options[:controller] || singleton_name.to_s.pluralize
full_path = "/#{options[:path_prefix]}#{options[:as] || singleton_name}"
new_path = "#{full_path}/new"
edit_path = "#{full_path}/edit"
formatted_edit_path = "#{full_path}/edit.xml"
- with_options options[:options] do |controller|
+ with_options route_options do |controller|
controller.assert_routing full_path, :action => 'show'
controller.assert_routing new_path, :action => 'new'
controller.assert_routing edit_path, :action => 'edit'
@@ -1256,42 +1254,41 @@ class ResourcesTest < ActionController::TestCase
controller.assert_routing formatted_edit_path, :action => 'edit', :format => 'xml'
end
- assert_recognizes(options[:options].merge(:action => 'show'), :path => full_path, :method => :get)
- assert_recognizes(options[:options].merge(:action => 'new'), :path => new_path, :method => :get)
- assert_recognizes(options[:options].merge(:action => 'edit'), :path => edit_path, :method => :get)
- assert_recognizes(options[:options].merge(:action => 'create'), :path => full_path, :method => :post)
- assert_recognizes(options[:options].merge(:action => 'update'), :path => full_path, :method => :put)
- assert_recognizes(options[:options].merge(:action => 'destroy'), :path => full_path, :method => :delete)
+ assert_recognizes(route_options.merge(:action => 'show'), :path => full_path, :method => :get)
+ assert_recognizes(route_options.merge(:action => 'new'), :path => new_path, :method => :get)
+ assert_recognizes(route_options.merge(:action => 'edit'), :path => edit_path, :method => :get)
+ assert_recognizes(route_options.merge(:action => 'create'), :path => full_path, :method => :post)
+ assert_recognizes(route_options.merge(:action => 'update'), :path => full_path, :method => :put)
+ assert_recognizes(route_options.merge(:action => 'destroy'), :path => full_path, :method => :delete)
- assert_recognizes(options[:options].merge(:action => 'show', :format => 'xml'), :path => "#{full_path}.xml", :method => :get)
- assert_recognizes(options[:options].merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get)
- assert_recognizes(options[:options].merge(:action => 'edit', :format => 'xml'), :path => formatted_edit_path, :method => :get)
- assert_recognizes(options[:options].merge(:action => 'create', :format => 'xml'), :path => "#{full_path}.xml", :method => :post)
- assert_recognizes(options[:options].merge(:action => 'update', :format => 'xml'), :path => "#{full_path}.xml", :method => :put)
- assert_recognizes(options[:options].merge(:action => 'destroy', :format => 'xml'), :path => "#{full_path}.xml", :method => :delete)
+ assert_recognizes(route_options.merge(:action => 'show', :format => 'xml'), :path => "#{full_path}.xml", :method => :get)
+ assert_recognizes(route_options.merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get)
+ assert_recognizes(route_options.merge(:action => 'edit', :format => 'xml'), :path => formatted_edit_path, :method => :get)
+ assert_recognizes(route_options.merge(:action => 'create', :format => 'xml'), :path => "#{full_path}.xml", :method => :post)
+ assert_recognizes(route_options.merge(:action => 'update', :format => 'xml'), :path => "#{full_path}.xml", :method => :put)
+ assert_recognizes(route_options.merge(:action => 'destroy', :format => 'xml'), :path => "#{full_path}.xml", :method => :delete)
- yield options[:options] if block_given?
+ yield route_options if block_given?
end
def assert_singleton_named_routes_for(singleton_name, options = {})
- (options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize
- @controller = "#{options[:options][:controller].camelize}Controller".constantize.new
+ route_options = (options[:options] ||= {}).dup
+ controller_name = route_options[:controller] || options[:controller] || singleton_name.to_s.pluralize
+ @controller = "#{controller_name.camelize}Controller".constantize.new
@controller.singleton_class.include(@routes.url_helpers)
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- get :show, params: options[:options]
- options[:options].delete :action
+ get :show, params: route_options
+ route_options.delete :action
full_path = "/#{options[:path_prefix]}#{options[:as] || singleton_name}"
name_prefix = options[:name_prefix]
- assert_named_route "#{full_path}", "#{name_prefix}#{singleton_name}_path", options[:options]
- assert_named_route "#{full_path}.xml", "#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}", "#{name_prefix}#{singleton_name}_path", route_options
+ assert_named_route "#{full_path}.xml", "#{name_prefix}#{singleton_name}_path", route_options.merge(:format => 'xml')
- assert_named_route "#{full_path}/new", "new_#{name_prefix}#{singleton_name}_path", options[:options]
- assert_named_route "#{full_path}/new.xml", "new_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
- assert_named_route "#{full_path}/edit", "edit_#{name_prefix}#{singleton_name}_path", options[:options]
- assert_named_route "#{full_path}/edit.xml", "edit_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}/new", "new_#{name_prefix}#{singleton_name}_path", route_options
+ assert_named_route "#{full_path}/new.xml", "new_#{name_prefix}#{singleton_name}_path", route_options.merge(:format => 'xml')
+ assert_named_route "#{full_path}/edit", "edit_#{name_prefix}#{singleton_name}_path", route_options
+ assert_named_route "#{full_path}/edit.xml", "edit_#{name_prefix}#{singleton_name}_path", route_options.merge(:format => 'xml')
end
def assert_named_route(expected, route, options)
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 2d08987ca6..a39fede5b9 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -8,8 +8,6 @@ class MilestonesController < ActionController::Base
alias_method :show, :index
end
-ROUTING = ActionDispatch::Routing
-
# See RFC 3986, section 3.3 for allowed path characters.
class UriReservedCharactersRoutingTest < ActiveSupport::TestCase
include RoutingTestHelpers
@@ -291,12 +289,6 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
assert_equal({:id=>"1", :filters=>"foo", :format=>"js"}, params)
end
- def test_draw_with_block_arity_one_raises
- assert_raise(RuntimeError) do
- rs.draw { |map| map.match '/:controller(/:action(/:id))' }
- end
- end
-
def test_specific_controller_action_failure
rs.draw do
mount lambda {} => "/foo"
@@ -329,17 +321,23 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
assert_equal '/stuff', controller.url_for({ :controller => '/stuff', :only_path => true })
end
- def test_ignores_leading_slash
- rs.clear!
- rs.draw { get '/:controller(/:action(/:id))'}
- test_default_setup
- end
-
def test_route_with_colon_first
rs.draw do
- get '/:controller/:action/:id', :action => 'index', :id => nil
- get ':url', :controller => 'tiny_url', :action => 'translate'
+ get '/:controller/:action/:id', action: 'index', id: nil
+ get ':url', controller: 'content', action: 'translate'
end
+
+ assert_equal({controller: 'content', action: 'translate', url: 'example'}, rs.recognize_path('/example'))
+ end
+
+ def test_route_with_regexp_for_action
+ rs.draw { get '/:controller/:action', action: /auth[-|_].+/ }
+
+ assert_equal({ action: 'auth_google', controller: 'content' }, rs.recognize_path('/content/auth_google'))
+ assert_equal({ action: 'auth-facebook', controller: 'content' }, rs.recognize_path('/content/auth-facebook'))
+
+ assert_equal '/content/auth_google', url_for(rs, { controller: "content", action: "auth_google" })
+ assert_equal '/content/auth-facebook', url_for(rs, { controller: "content", action: "auth-facebook" })
end
def test_route_with_regexp_for_controller
@@ -871,7 +869,7 @@ class RouteSetTest < ActiveSupport::TestCase
def default_route_set
@default_route_set ||= begin
- set = ROUTING::RouteSet.new
+ set = ActionDispatch::Routing::RouteSet.new
set.draw do
get '/:controller(/:action(/:id))'
end
@@ -1748,40 +1746,10 @@ class RouteSetTest < ActiveSupport::TestCase
include ActionDispatch::RoutingVerbs
- class TestSet < ROUTING::RouteSet
- def initialize(block)
- @block = block
- super()
- end
-
- class Dispatcher < ROUTING::RouteSet::Dispatcher
- def initialize(defaults, set, block)
- super(defaults)
- @block = block
- @set = set
- end
-
- def controller_reference(controller_param)
- block = @block
- set = @set
- Class.new(ActionController::Base) {
- include set.url_helpers
- define_method(:process) { |name| block.call(self) }
- def to_a; [200, {}, []]; end
- }
- end
- end
-
- def dispatcher defaults
- TestSet::Dispatcher.new defaults, self, @block
- end
- end
-
alias :routes :set
def test_generate_with_optional_params_recalls_last_request
- controller = nil
- @set = TestSet.new ->(c) { controller = c }
+ @set = make_set false
set.draw do
get "blog/", :controller => "blog", :action => "index"
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index 36c57ec9b2..2820425c31 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -20,6 +20,47 @@ class SendFileController < ActionController::Base
send_file(file_path, options)
end
+ def test_send_file_headers_bang
+ options = {
+ :type => Mime[:png],
+ :disposition => 'disposition',
+ :filename => 'filename'
+ }
+
+ send_data "foo", options
+ end
+
+ def test_send_file_headers_with_disposition_as_a_symbol
+ options = {
+ :type => Mime[:png],
+ :disposition => :disposition,
+ :filename => 'filename'
+ }
+
+ send_data "foo", options
+ end
+
+ def test_send_file_headers_with_mime_lookup_with_symbol
+ options = { :type => :png }
+
+ send_data "foo", options
+ end
+
+ def test_send_file_headers_with_bad_symbol
+ options = { :type => :this_type_is_not_registered }
+ send_data "foo", options
+ end
+
+ def test_send_file_headers_with_nil_content_type
+ options = { :type => nil }
+ send_data "foo", options
+ end
+
+ def test_send_file_headers_guess_type_from_extension
+ options = { :filename => params[:filename] }
+ send_data "foo", options
+ end
+
def data
send_data(file_data, options)
end
@@ -34,8 +75,6 @@ class SendFileTest < ActionController::TestCase
def setup
@controller = SendFileController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
end
def test_file_nostream
@@ -90,62 +129,39 @@ class SendFileTest < ActionController::TestCase
# Test that send_file_headers! is setting the correct HTTP headers.
def test_send_file_headers_bang
- options = {
- :type => Mime::PNG,
- :disposition => 'disposition',
- :filename => 'filename'
- }
-
# Do it a few times: the resulting headers should be identical
# no matter how many times you send with the same options.
# Test resolving Ticket #458.
- @controller.headers = {}
- @controller.send(:send_file_headers!, options)
- @controller.send(:send_file_headers!, options)
- @controller.send(:send_file_headers!, options)
+ 5.times do
+ get :test_send_file_headers_bang
- h = @controller.headers
- assert_equal 'image/png', @controller.content_type
- assert_equal 'disposition; filename="filename"', h['Content-Disposition']
- assert_equal 'binary', h['Content-Transfer-Encoding']
-
- # test overriding Cache-Control: no-cache header to fix IE open/save dialog
- @controller.send(:send_file_headers!, options)
- @controller.response.prepare!
- assert_equal 'private', h['Cache-Control']
+ assert_equal 'image/png', response.content_type
+ assert_equal 'disposition; filename="filename"', response.get_header('Content-Disposition')
+ assert_equal 'binary', response.get_header('Content-Transfer-Encoding')
+ assert_equal 'private', response.get_header('Cache-Control')
+ end
end
def test_send_file_headers_with_disposition_as_a_symbol
- options = {
- :type => Mime::PNG,
- :disposition => :disposition,
- :filename => 'filename'
- }
+ get :test_send_file_headers_with_disposition_as_a_symbol
- @controller.headers = {}
- @controller.send(:send_file_headers!, options)
- assert_equal 'disposition; filename="filename"', @controller.headers['Content-Disposition']
+ assert_equal 'disposition; filename="filename"', response.get_header('Content-Disposition')
end
def test_send_file_headers_with_mime_lookup_with_symbol
- options = {
- :type => :png
- }
-
- @controller.headers = {}
- @controller.send(:send_file_headers!, options)
-
- assert_equal 'image/png', @controller.content_type
+ get __method__
+ assert_equal 'image/png', response.content_type
end
def test_send_file_headers_with_bad_symbol
- options = {
- :type => :this_type_is_not_registered
- }
+ error = assert_raise(ArgumentError) { get __method__ }
+ assert_equal "Unknown MIME type this_type_is_not_registered", error.message
+ end
- @controller.headers = {}
- assert_raise(ArgumentError) { @controller.send(:send_file_headers!, options) }
+ def test_send_file_headers_with_nil_content_type
+ error = assert_raise(ArgumentError) { get __method__ }
+ assert_equal ":type option required", error.message
end
def test_send_file_headers_guess_type_from_extension
@@ -160,10 +176,8 @@ class SendFileTest < ActionController::TestCase
'file.unk' => 'application/octet-stream',
'zip' => 'application/octet-stream'
}.each do |filename,expected_type|
- options = { :filename => filename }
- @controller.headers = {}
- @controller.send(:send_file_headers!, options)
- assert_equal expected_type, @controller.content_type
+ get __method__, params: { filename: filename }
+ assert_equal expected_type, response.content_type
end
end
@@ -181,7 +195,7 @@ class SendFileTest < ActionController::TestCase
%w(file data).each do |method|
define_method "test_send_#{method}_status" do
@controller.options = { :stream => false, :status => 500 }
- assert_nothing_raised { assert_not_nil process(method) }
+ assert_not_nil process(method)
assert_equal 500, @response.status
end
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index e348749f78..e50373a0cc 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -4,72 +4,82 @@ require 'active_support/json/decoding'
require 'rails/engine'
class TestCaseTest < ActionController::TestCase
+ def self.fixture_path; end;
+
class TestController < ActionController::Base
def no_op
- render text: 'dummy'
+ render plain: 'dummy'
end
def set_flash
flash["test"] = ">#{flash["test"]}<"
- render text: 'ignore me'
+ render plain: 'ignore me'
end
def delete_flash
flash.delete("test")
- render :text => 'ignore me'
+ render plain: 'ignore me'
end
def set_flash_now
flash.now["test_now"] = ">#{flash["test_now"]}<"
- render text: 'ignore me'
+ render plain: 'ignore me'
end
def set_session
session['string'] = 'A wonder'
session[:symbol] = 'it works'
- render text: 'Success'
+ render plain: 'Success'
end
def reset_the_session
reset_session
- render text: 'ignore me'
+ render plain: 'ignore me'
end
def render_raw_post
raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
- render text: request.raw_post
+ render plain: request.raw_post
end
def render_body
- render text: request.body.read
+ render plain: request.body.read
end
def test_params
- render text: params.inspect
+ render plain: ::JSON.dump(params.to_unsafe_h)
+ end
+
+ def test_query_parameters
+ render plain: ::JSON.dump(request.query_parameters)
+ end
+
+ def test_request_parameters
+ render plain: request.request_parameters.inspect
end
def test_uri
- render text: request.fullpath
+ render plain: request.fullpath
end
def test_format
- render text: request.format
+ render plain: request.format
end
def test_query_string
- render text: request.query_string
+ render plain: request.query_string
end
def test_protocol
- render text: request.protocol
+ render plain: request.protocol
end
def test_headers
- render text: request.headers.env.to_json
+ render plain: ::JSON.dump(request.headers.env)
end
def test_html_output
- render text: <<HTML
+ render plain: <<HTML
<html>
<body>
<a href="/"><img src="/images/button.png" /></a>
@@ -91,7 +101,7 @@ HTML
def test_xml_output
response.content_type = "application/xml"
- render text: <<XML
+ render plain: <<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<area>area is an empty tag in HTML, raising an error if not in xml mode</area>
@@ -100,15 +110,15 @@ XML
end
def test_only_one_param
- render text: (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
+ render plain: (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
end
def test_remote_addr
- render text: (request.remote_addr || "not specified")
+ render plain: (request.remote_addr || "not specified")
end
def test_file_upload
- render text: params[:file].size
+ render plain: params[:file].size
end
def test_send_file
@@ -129,13 +139,7 @@ XML
def delete_cookie
cookies.delete("foo")
- render nothing: true
- end
-
- def test_assigns
- @foo = "foo"
- @foo_hash = { foo: :bar }
- render nothing: true
+ render plain: 'ok'
end
def test_without_body
@@ -156,9 +160,7 @@ XML
def setup
super
@controller = TestController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @request.env['PATH_INFO'] = nil
+ @request.delete_header 'PATH_INFO'
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
r.draw do
get ':controller(/:action(/:id))'
@@ -166,22 +168,11 @@ XML
end
end
- class ViewAssignsController < ActionController::Base
- def test_assigns
- @foo = "foo"
- render nothing: true
- end
-
- def view_assigns
- { "bar" => "bar" }
- end
- end
-
class DefaultUrlOptionsCachingController < ActionController::Base
before_action { @dynamic_opt = 'opt' }
def test_url_options_reset
- render text: url_for(params)
+ render plain: url_for(params)
end
def default_url_options
@@ -238,7 +229,7 @@ XML
def test_document_body_and_params_with_post
post :test_params, params: { id: 1 }
- assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
end
def test_document_body_with_post
@@ -438,30 +429,6 @@ XML
assert_equal "OK", @response.body
end
- def test_assigns
- process :test_assigns
- # assigns can be accessed using assigns(key)
- # or assigns[key], where key is a string or
- # a symbol
- assert_equal "foo", assigns(:foo)
- assert_equal "foo", assigns("foo")
- assert_equal "foo", assigns[:foo]
- assert_equal "foo", assigns["foo"]
-
- # but the assigned variable should not have its own keys stringified
- expected_hash = { foo: :bar }
- assert_equal expected_hash, assigns(:foo_hash)
- end
-
- def test_view_assigns
- @controller = ViewAssignsController.new
- process :test_assigns
- assert_equal nil, assigns(:foo)
- assert_equal nil, assigns[:foo]
- assert_equal "bar", assigns(:bar)
- assert_equal "bar", assigns[:bar]
- end
-
def test_should_not_impose_childless_html_tags_in_xml
process :test_xml_output
@@ -518,7 +485,7 @@ XML
assert_deprecated {
get :test_params, page: { name: "Page name", month: '4', year: '2004', day: '6' }
}
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{
'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -537,7 +504,7 @@ XML
day: '6'
}
}
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{
'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -547,6 +514,18 @@ XML
)
end
+ def test_query_param_named_action
+ get :test_query_parameters, params: {action: 'foobar'}
+ parsed_params = JSON.parse(@response.body)
+ assert_equal({'action' => 'foobar'}, parsed_params)
+ end
+
+ def test_request_param_named_action
+ post :test_request_parameters, params: {action: 'foobar'}
+ parsed_params = eval(@response.body)
+ assert_equal({'action' => 'foobar'}, parsed_params)
+ end
+
def test_kwarg_params_passing_with_session_and_flash
get :test_params, params: {
page: {
@@ -557,7 +536,7 @@ XML
}
}, session: { 'foo' => 'bar' }, flash: { notice: 'created' }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
@@ -572,7 +551,7 @@ XML
get :test_params, params: {
page: { name: "Page name", month: 4, year: 2004, day: 6 }
}
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
@@ -582,17 +561,17 @@ XML
def test_params_passing_with_fixnums_when_not_html_request
get :test_params, params: { format: 'json', count: 999 }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
- 'format' => 'json', 'count' => 999 },
+ 'format' => 'json', 'count' => '999' },
parsed_params
)
end
def test_params_passing_path_parameter_is_string_when_not_html_request
get :test_params, params: { format: 'json', id: 1 }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'format' => 'json', 'id' => '1' },
@@ -602,7 +581,7 @@ XML
def test_deprecated_params_passing_path_parameter_is_string_when_not_html_request
assert_deprecated { get :test_params, format: 'json', id: 1 }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'format' => 'json', 'id' => '1' },
@@ -616,7 +595,7 @@ XML
frozen: 'icy'.freeze, frozens: ['icy'.freeze].freeze, deepfreeze: { frozen: 'icy'.freeze }.freeze
}
end
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'frozen' => 'icy', 'frozens' => ['icy'], 'deepfreeze' => { 'frozen' => 'icy' }},
@@ -648,6 +627,31 @@ XML
assert_equal "application/json", parsed_env["CONTENT_TYPE"]
end
+ def test_mutating_content_type_headers_for_plain_text_files_sets_the_header
+ @request.headers['Content-Type'] = 'text/plain'
+ post :render_body, params: { name: 'foo.txt' }
+
+ assert_equal 'text/plain', @request.headers['Content-type']
+ assert_equal 'foo.txt', @request.request_parameters[:name]
+ assert_equal 'render_body', @request.path_parameters[:action]
+ end
+
+ def test_mutating_content_type_headers_for_html_files_sets_the_header
+ @request.headers['Content-Type'] = 'text/html'
+ post :render_body, params: { name: 'foo.html' }
+
+ assert_equal 'text/html', @request.headers['Content-type']
+ assert_equal 'foo.html', @request.request_parameters[:name]
+ assert_equal 'render_body', @request.path_parameters[:action]
+ end
+
+ def test_mutating_content_type_headers_for_non_registered_mime_type_raises_an_error
+ assert_raises(RuntimeError) do
+ @request.headers['Content-Type'] = 'type/fake'
+ post :render_body, params: { name: 'foo.fake' }
+ end
+ end
+
def test_id_converted_to_string
get :test_params, params: {
id: 20, foo: Object.new
@@ -714,13 +718,13 @@ XML
def test_deprecated_xhr_with_params
assert_deprecated { xhr :get, :test_params, params: { id: 1 } }
- assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
end
def test_xhr_with_params
get :test_params, params: { id: 1 }, xhr: true
- assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
end
def test_xhr_with_session
@@ -741,12 +745,6 @@ XML
assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
end
- def test_header_properly_reset_after_get_request
- get :test_params
- @request.recycle!
- assert_nil @request.instance_variable_get("@request_method")
- end
-
def test_deprecated_params_reset_between_post_requests
assert_deprecated { post :no_op, foo: "bar" }
assert_equal "bar", @request.params[:foo]
@@ -878,10 +876,10 @@ XML
end
def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
- TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
-
- uploaded_file = fixture_file_upload('/mona_lisa.jpg', 'image/png')
- assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ TestCaseTest.stub :fixture_path, FILES_DIR do
+ uploaded_file = fixture_file_upload('/mona_lisa.jpg', 'image/png')
+ assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ end
end
def test_test_uploaded_file_with_binary
@@ -908,6 +906,11 @@ XML
assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
end
+ def test_fixture_file_upload_should_be_able_access_to_tempfile
+ file = fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
+ assert file.respond_to?(:tempfile), "expected tempfile should respond on fixture file object, got nothing"
+ end
+
def test_fixture_file_upload
post :test_file_upload,
params: {
@@ -917,13 +920,13 @@ XML
end
def test_fixture_file_upload_relative_to_fixture_path
- TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
- uploaded_file = fixture_file_upload("mona_lisa.jpg", "image/jpg")
- assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ TestCaseTest.stub :fixture_path, FILES_DIR do
+ uploaded_file = fixture_file_upload("mona_lisa.jpg", "image/jpg")
+ assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ end
end
def test_fixture_file_upload_ignores_nil_fixture_path
- TestCaseTest.stubs(:fixture_path).returns(nil)
uploaded_file = fixture_file_upload("#{FILES_DIR}/mona_lisa.jpg", "image/jpg")
assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
end
@@ -932,7 +935,7 @@ XML
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
assert_deprecated {
- post :test_file_upload, file: ActionDispatch::Http::UploadedFile.new(filename: path, type: "image/jpg", tempfile: File.open(path))
+ post :test_file_upload, file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
}
assert_equal '159528', @response.body
end
@@ -941,7 +944,7 @@ XML
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
post :test_file_upload, params: {
- file: ActionDispatch::Http::UploadedFile.new(filename: path, type: "image/jpg", tempfile: File.open(path))
+ file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
}
assert_equal '159528', @response.body
end
@@ -971,12 +974,18 @@ class ResponseDefaultHeadersTest < ActionController::TestCase
headers.delete params[:header]
head :ok, 'C' => '3'
end
+
+ # Render a head response, but don't touch default headers
+ def leave_alone
+ head :ok
+ end
end
- setup do
+ def before_setup
@original = ActionDispatch::Response.default_headers
@defaults = { 'A' => '1', 'B' => '2' }
ActionDispatch::Response.default_headers = @defaults
+ super
end
teardown do
@@ -986,8 +995,6 @@ class ResponseDefaultHeadersTest < ActionController::TestCase
def setup
super
@controller = TestController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@request.env['PATH_INFO'] = nil
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
r.draw do
@@ -997,9 +1004,13 @@ class ResponseDefaultHeadersTest < ActionController::TestCase
end
test "response contains default headers" do
+ get :leave_alone
+
# Response headers start out with the defaults
- assert_equal @defaults, response.headers
+ assert_equal @defaults.merge('Content-Type' => 'text/html'), response.headers
+ end
+ test "response deletes a default header" do
get :remove_header, params: { header: 'A' }
assert_response :ok
@@ -1022,7 +1033,7 @@ module EngineControllerTests
class BarController < ActionController::Base
def index
- render text: 'bar'
+ render plain: 'bar'
end
end
@@ -1108,7 +1119,7 @@ class AnonymousControllerTest < ActionController::TestCase
def setup
@controller = Class.new(ActionController::Base) do
def index
- render text: params[:controller]
+ render plain: params[:controller]
end
end.new
@@ -1129,11 +1140,11 @@ class RoutingDefaultsTest < ActionController::TestCase
def setup
@controller = Class.new(ActionController::Base) do
def post
- render text: request.fullpath
+ render plain: request.fullpath
end
def project
- render text: request.fullpath
+ render plain: request.fullpath
end
end.new
diff --git a/actionpack/test/controller/url_for_integration_test.rb b/actionpack/test/controller/url_for_integration_test.rb
index 0e4c2b7c32..dfc2712e3e 100644
--- a/actionpack/test/controller/url_for_integration_test.rb
+++ b/actionpack/test/controller/url_for_integration_test.rb
@@ -158,6 +158,7 @@ module ActionPack
['/posts/ping',[ { :controller => 'posts', :action => 'ping' }]],
['/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1' }]],
+ ['/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1', :format => '' }]],
['/posts',[ { :controller => 'posts' }]],
['/posts',[ { :controller => 'posts', :action => 'index' }]],
['/posts/create',[ { :action => 'create' }, {:day=>nil, :month=>nil, :controller=>"posts", :action=>"show_date"}, '/blog']],
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 31677f202d..78e883f134 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -451,6 +451,26 @@ module AbstractController
end
end
+ def test_url_for_with_array_is_unmodified
+ with_routing do |set|
+ set.draw do
+ namespace :admin do
+ resources :posts
+ end
+ end
+
+ kls = Class.new { include set.url_helpers }
+ kls.default_url_options[:host] = 'www.basecamphq.com'
+
+ original_components = [:new, :admin, :post, { param: 'value' }]
+ components = original_components.dup
+
+ kls.new.url_for(components)
+
+ assert_equal(original_components, components)
+ end
+ end
+
private
def extract_params(url)
url.split('?', 2).last.split('&').sort
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index d9a1ae7d4f..5f2abc9606 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-class UrlRewriterTests < ActiveSupport::TestCase
+class UrlRewriterTests < ActionController::TestCase
class Rewriter
def initialize(request)
@options = {
@@ -16,7 +16,6 @@ class UrlRewriterTests < ActiveSupport::TestCase
end
def setup
- @request = ActionController::TestRequest.new
@params = {}
@rewriter = Rewriter.new(@request) #.new(@request, @params)
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index 21fa670bb6..6d377c4691 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -5,16 +5,22 @@ class WebServiceTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def assign_parameters
if params[:full]
- render :text => dump_params_keys
+ render plain: dump_params_keys
else
- render :text => (params.keys - ['controller', 'action']).sort.join(", ")
+ render plain: (params.keys - ['controller', 'action']).sort.join(", ")
end
end
def dump_params_keys(hash = params)
hash.keys.sort.inject("") do |s, k|
value = hash[k]
- value = Hash === value ? "(#{dump_params_keys(value)})" : ""
+
+ if value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
+ value = "(#{dump_params_keys(value)})"
+ else
+ value = ""
+ end
+
s << ", " unless s.empty?
s << "#{k}#{value}"
end
@@ -59,7 +65,7 @@ class WebServiceTest < ActionDispatch::IntegrationTest
def test_register_and_use_json_simple
with_test_route_set do
- with_params_parsers Mime::JSON => Proc.new { |data| ActiveSupport::JSON.decode(data)['request'].with_indifferent_access } do
+ with_params_parsers Mime[:json] => Proc.new { |data| ActiveSupport::JSON.decode(data)['request'].with_indifferent_access } do
post "/",
params: '{"request":{"summary":"content...","title":"JSON"}}',
headers: { 'CONTENT_TYPE' => 'application/json' }
@@ -91,24 +97,28 @@ class WebServiceTest < ActionDispatch::IntegrationTest
end
def test_parsing_json_doesnot_rescue_exception
- with_test_route_set do
- with_params_parsers Mime::JSON => Proc.new { |data| raise Interrupt } do
- assert_raises(Interrupt) do
- post "/",
- params: '{"title":"JSON"}}',
- headers: { 'CONTENT_TYPE' => 'application/json' }
- end
+ req = Class.new(ActionDispatch::Request) do
+ def params_parsers
+ { Mime[:json] => Proc.new { |data| raise Interrupt } }
end
+
+ def content_length; get_header('rack.input').length; end
+ end.new({ 'rack.input' => StringIO.new('{"title":"JSON"}}'), 'CONTENT_TYPE' => 'application/json' })
+
+ assert_raises(Interrupt) do
+ req.request_parameters
end
end
private
def with_params_parsers(parsers = {})
old_session = @integration_session
- @app = ActionDispatch::ParamsParser.new(app.routes, parsers)
+ original_parsers = ActionDispatch::Request.parameter_parsers
+ ActionDispatch::Request.parameter_parsers = original_parsers.merge parsers
reset!
yield
ensure
+ ActionDispatch::Request.parameter_parsers = original_parsers
@integration_session = old_session
end
diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb
index f767b07e75..5ba76d9ab9 100644
--- a/actionpack/test/dispatch/callbacks_test.rb
+++ b/actionpack/test/dispatch/callbacks_test.rb
@@ -28,7 +28,7 @@ class DispatcherTest < ActiveSupport::TestCase
assert_equal 4, Foo.a
assert_equal 4, Foo.b
- dispatch do |env|
+ dispatch do
raise "error"
end rescue nil
assert_equal 6, Foo.a
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 6223a52a76..84c244c72a 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -3,6 +3,75 @@ require 'openssl'
require 'active_support/key_generator'
require 'active_support/message_verifier'
+class CookieJarTest < ActiveSupport::TestCase
+ attr_reader :request
+
+ def setup
+ @request = ActionDispatch::Request.new({})
+ end
+
+ def test_fetch
+ x = Object.new
+ assert_not request.cookie_jar.key?('zzzzzz')
+ assert_equal x, request.cookie_jar.fetch('zzzzzz', x)
+ assert_not request.cookie_jar.key?('zzzzzz')
+ end
+
+ def test_fetch_exists
+ x = Object.new
+ request.cookie_jar['foo'] = 'bar'
+ assert_equal 'bar', request.cookie_jar.fetch('foo', x)
+ end
+
+ def test_fetch_block
+ x = Object.new
+ assert_not request.cookie_jar.key?('zzzzzz')
+ assert_equal x, request.cookie_jar.fetch('zzzzzz') { x }
+ end
+
+ def test_key_is_to_s
+ request.cookie_jar['foo'] = 'bar'
+ assert_equal 'bar', request.cookie_jar.fetch(:foo)
+ end
+
+ def test_fetch_type_error
+ assert_raises(KeyError) do
+ request.cookie_jar.fetch(:omglolwut)
+ end
+ end
+
+ def test_each
+ request.cookie_jar['foo'] = :bar
+ list = []
+ request.cookie_jar.each do |k,v|
+ list << [k, v]
+ end
+
+ assert_equal [['foo', :bar]], list
+ end
+
+ def test_enumerable
+ request.cookie_jar['foo'] = :bar
+ actual = request.cookie_jar.map { |k,v| [k.to_s, v.to_s] }
+ assert_equal [['foo', 'bar']], actual
+ end
+
+ def test_key_methods
+ assert !request.cookie_jar.key?(:foo)
+ assert !request.cookie_jar.has_key?("foo")
+
+ request.cookie_jar[:foo] = :bar
+ assert request.cookie_jar.key?(:foo)
+ assert request.cookie_jar.has_key?("foo")
+ end
+
+ def test_write_doesnt_set_a_nil_header
+ headers = {}
+ request.cookie_jar.write(headers)
+ assert !headers.include?('Set-Cookie')
+ end
+end
+
class CookiesTest < ActionController::TestCase
class CustomSerializer
def self.load(value)
@@ -14,16 +83,6 @@ class CookiesTest < ActionController::TestCase
end
end
- class JSONWrapper
- def initialize(obj)
- @obj = obj
- end
-
- def as_json(options = nil)
- "wrapped: #{@obj.as_json(options)}"
- end
- end
-
class TestController < ActionController::Base
def authenticate
cookies["user_name"] = "david"
@@ -88,11 +147,6 @@ class CookiesTest < ActionController::TestCase
head :ok
end
- def set_wrapped_signed_cookie
- cookies.signed[:user_id] = JSONWrapper.new(45)
- head :ok
- end
-
def get_signed_cookie
cookies.signed[:user_id]
head :ok
@@ -103,6 +157,21 @@ class CookiesTest < ActionController::TestCase
head :ok
end
+ class JSONWrapper
+ def initialize(obj)
+ @obj = obj
+ end
+
+ def as_json(options = nil)
+ "wrapped: #{@obj.as_json(options)}"
+ end
+ end
+
+ def set_wrapped_signed_cookie
+ cookies.signed[:user_id] = JSONWrapper.new(45)
+ head :ok
+ end
+
def set_wrapped_encrypted_cookie
cookies.encrypted[:foo] = JSONWrapper.new('bar')
head :ok
@@ -207,68 +276,18 @@ class CookiesTest < ActionController::TestCase
tests TestController
+ SALT = 'b3c631c314c0bbca50c1b2843150fe33'
+
def setup
super
- @request.env["action_dispatch.key_generator"] = ActiveSupport::KeyGenerator.new("b3c631c314c0bbca50c1b2843150fe33", iterations: 2)
- @request.env["action_dispatch.signed_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
- @request.env["action_dispatch.encrypted_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
- @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
- @request.host = "www.nextangle.com"
- end
-
- def test_fetch
- x = Object.new
- assert_not request.cookie_jar.key?('zzzzzz')
- assert_equal x, request.cookie_jar.fetch('zzzzzz', x)
- assert_not request.cookie_jar.key?('zzzzzz')
- end
-
- def test_fetch_exists
- x = Object.new
- request.cookie_jar['foo'] = 'bar'
- assert_equal 'bar', request.cookie_jar.fetch('foo', x)
- end
-
- def test_fetch_block
- x = Object.new
- assert_not request.cookie_jar.key?('zzzzzz')
- assert_equal x, request.cookie_jar.fetch('zzzzzz') { x }
- end
-
- def test_key_is_to_s
- request.cookie_jar['foo'] = 'bar'
- assert_equal 'bar', request.cookie_jar.fetch(:foo)
- end
-
- def test_fetch_type_error
- assert_raises(KeyError) do
- request.cookie_jar.fetch(:omglolwut)
- end
- end
- def test_each
- request.cookie_jar['foo'] = :bar
- list = []
- request.cookie_jar.each do |k,v|
- list << [k, v]
- end
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::KeyGenerator.new(SALT, iterations: 2)
- assert_equal [['foo', :bar]], list
- end
+ @request.env["action_dispatch.signed_cookie_salt"] =
+ @request.env["action_dispatch.encrypted_cookie_salt"] =
+ @request.env["action_dispatch.encrypted_signed_cookie_salt"] = SALT
- def test_enumerable
- request.cookie_jar['foo'] = :bar
- actual = request.cookie_jar.map { |k,v| [k.to_s, v.to_s] }
- assert_equal [['foo', 'bar']], actual
- end
-
- def test_key_methods
- assert !request.cookie_jar.key?(:foo)
- assert !request.cookie_jar.has_key?("foo")
-
- request.cookie_jar[:foo] = :bar
- assert request.cookie_jar.key?(:foo)
- assert request.cookie_jar.has_key?("foo")
+ @request.host = "www.nextangle.com"
end
def test_setting_cookie
@@ -280,7 +299,7 @@ class CookiesTest < ActionController::TestCase
def test_setting_the_same_value_to_cookie
request.cookies[:user_name] = 'david'
get :authenticate
- assert response.cookies.empty?
+ assert_predicate response.cookies, :empty?
end
def test_setting_the_same_value_to_permanent_cookie
@@ -321,10 +340,12 @@ class CookiesTest < ActionController::TestCase
end
def test_setting_cookie_with_secure_when_always_write_cookie_is_true
- ActionDispatch::Cookies::CookieJar.any_instance.stubs(:always_write_cookie).returns(true)
+ old_cookie, @request.cookie_jar.always_write_cookie = @request.cookie_jar.always_write_cookie, true
get :authenticate_with_secure
assert_cookie_header "user_name=david; path=/; secure"
assert_equal({"user_name" => "david"}, @response.cookies)
+ ensure
+ @request.cookie_jar.always_write_cookie = old_cookie
end
def test_not_setting_cookie_with_secure
@@ -360,7 +381,7 @@ class CookiesTest < ActionController::TestCase
def test_delete_unexisting_cookie
request.cookies.clear
get :delete_cookie
- assert @response.cookies.empty?
+ assert_predicate @response.cookies, :empty?
end
def test_deleted_cookie_predicate
@@ -378,7 +399,7 @@ class CookiesTest < ActionController::TestCase
def test_cookies_persist_throughout_request
response = get :authenticate
- assert response.headers["Set-Cookie"] =~ /user_name=david/
+ assert_match(/user_name=david/, response.headers["Set-Cookie"])
end
def test_set_permanent_cookie
@@ -651,6 +672,15 @@ class CookiesTest < ActionController::TestCase
end
end
+ def test_cookie_jar_mutated_by_request_persists_on_future_requests
+ get :authenticate
+ cookie_jar = @request.cookie_jar
+ cookie_jar.signed[:user_id] = 123
+ assert_equal ["user_name", "user_id"], @request.cookie_jar.instance_variable_get(:@cookies).keys
+ get :get_signed_cookie
+ assert_equal ["user_name", "user_id"], @request.cookie_jar.instance_variable_get(:@cookies).keys
+ end
+
def test_raises_argument_error_if_missing_secret
assert_raise(ArgumentError, nil.inspect) {
@request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new(nil)
@@ -1072,11 +1102,11 @@ class CookiesTest < ActionController::TestCase
assert_equal "david", cookies[:user_name]
get :noop
- assert_nil @response.headers["Set-Cookie"]
+ assert !@response.headers.include?("Set-Cookie")
assert_equal "david", cookies[:user_name]
get :noop
- assert_nil @response.headers["Set-Cookie"]
+ assert !@response.headers.include?("Set-Cookie")
assert_equal "david", cookies[:user_name]
end
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
index a867aee7ec..8960156d00 100644
--- a/actionpack/test/dispatch/debug_exceptions_test.rb
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -42,7 +42,11 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
when "/unprocessable_entity"
raise ActionController::InvalidAuthenticityToken
when "/not_found_original_exception"
- raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new)
+ begin
+ raise AbstractController::ActionNotFound.new
+ rescue
+ raise ActionView::Template::Error.new('template')
+ end
when "/missing_template"
raise ActionView::MissingTemplate.new(%w(foo), 'foo/index', %w(foo), false, 'mailer')
when "/bad_request"
@@ -56,12 +60,12 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
when "/syntax_error_into_view"
begin
eval 'broke_syntax ='
- rescue Exception => e
+ rescue Exception
template = ActionView::Template.new(File.read(__FILE__),
__FILE__,
ActionView::Template::Handlers::Raw.new,
{})
- raise ActionView::Template::Error.new(template, e)
+ raise ActionView::Template::Error.new(template)
end
when "/framework_raises"
method_that_raises
@@ -71,14 +75,6 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
end
end
- def setup
- app = ActiveSupport::OrderedOptions.new
- app.config = ActiveSupport::OrderedOptions.new
- app.config.assets = ActiveSupport::OrderedOptions.new
- app.config.assets.prefix = '/sprockets'
- Rails.stubs(:application).returns(app)
- end
-
RoutesApp = Struct.new(:routes).new(SharedTestRoutes)
ProductionApp = ActionDispatch::DebugExceptions.new(Boomer.new(false), RoutesApp)
DevelopmentApp = ActionDispatch::DebugExceptions.new(Boomer.new(true), RoutesApp)
@@ -280,9 +276,12 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test 'uses backtrace cleaner from env' do
@app = DevelopmentApp
- cleaner = stub(:clean => ['passed backtrace cleaner'])
- get "/", headers: { 'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner }
- assert_match(/passed backtrace cleaner/, body)
+ backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
+
+ backtrace_cleaner.stub :clean, ['passed backtrace cleaner'] do
+ get "/", headers: { 'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => backtrace_cleaner }
+ assert_match(/passed backtrace cleaner/, body)
+ end
end
test 'logs exception backtrace when all lines silenced' do
@@ -338,36 +337,37 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test 'debug exceptions app shows user code that caused the error in source view' do
@app = DevelopmentApp
- Rails.stubs(:root).returns(Pathname.new('.'))
- cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc|
- bc.add_silencer { |line| line =~ /method_that_raises/ }
- bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} }
- end
+ Rails.stub :root, Pathname.new('.') do
+ cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc|
+ bc.add_silencer { |line| line =~ /method_that_raises/ }
+ bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} }
+ end
- get '/framework_raises', headers: { 'action_dispatch.backtrace_cleaner' => cleaner }
+ get '/framework_raises', headers: { 'action_dispatch.backtrace_cleaner' => cleaner }
- # Assert correct error
- assert_response 500
- assert_select 'h2', /error in framework/
+ # Assert correct error
+ assert_response 500
+ assert_select 'h2', /error in framework/
- # assert source view line is the call to method_that_raises
- assert_select 'div.source:not(.hidden)' do
- assert_select 'pre .line.active', /method_that_raises/
- end
+ # assert source view line is the call to method_that_raises
+ assert_select 'div.source:not(.hidden)' do
+ assert_select 'pre .line.active', /method_that_raises/
+ end
- # assert first source view (hidden) that throws the error
- assert_select 'div.source:first' do
- assert_select 'pre .line.active', /raise StandardError\.new/
- end
+ # assert first source view (hidden) that throws the error
+ assert_select 'div.source:first' do
+ assert_select 'pre .line.active', /raise StandardError\.new/
+ end
- # assert application trace refers to line that calls method_that_raises is first
- assert_select '#Application-Trace' do
- assert_select 'pre code a:first', %r{test/dispatch/debug_exceptions_test\.rb:\d+:in `call}
- end
+ # assert application trace refers to line that calls method_that_raises is first
+ assert_select '#Application-Trace' do
+ assert_select 'pre code a:first', %r{test/dispatch/debug_exceptions_test\.rb:\d+:in `call}
+ end
- # assert framework trace that that threw the error is first
- assert_select '#Framework-Trace' do
- assert_select 'pre code a:first', /method_that_raises/
+ # assert framework trace that threw the error is first
+ assert_select '#Framework-Trace' do
+ assert_select 'pre code a:first', /method_that_raises/
+ end
end
end
end
diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb
index 7a29a7ff97..dfbb91c0ca 100644
--- a/actionpack/test/dispatch/exception_wrapper_test.rb
+++ b/actionpack/test/dispatch/exception_wrapper_test.rb
@@ -17,51 +17,49 @@ module ActionDispatch
end
setup do
- Rails.stubs(:root).returns(Pathname.new('.'))
-
- cleaner = ActiveSupport::BacktraceCleaner.new
- cleaner.add_silencer { |line| line !~ /^lib/ }
-
- @environment = { 'action_dispatch.backtrace_cleaner' => cleaner }
+ @cleaner = ActiveSupport::BacktraceCleaner.new
+ @cleaner.add_silencer { |line| line !~ /^lib/ }
end
test '#source_extracts fetches source fragments for every backtrace entry' do
exception = TestError.new("lib/file.rb:42:in `index'")
- wrapper = ExceptionWrapper.new({}, exception)
-
- wrapper.expects(:source_fragment).with('lib/file.rb', 42).returns('foo')
+ wrapper = ExceptionWrapper.new(nil, exception)
- assert_equal [ code: 'foo', line_number: 42 ], wrapper.source_extracts
+ assert_called_with(wrapper, :source_fragment, ['lib/file.rb', 42], returns: 'foo') do
+ assert_equal [ code: 'foo', line_number: 42 ], wrapper.source_extracts
+ end
end
test '#source_extracts works with Windows paths' do
exc = TestError.new("c:/path/to/rails/app/controller.rb:27:in 'index':")
- wrapper = ExceptionWrapper.new({}, exc)
- wrapper.expects(:source_fragment).with('c:/path/to/rails/app/controller.rb', 27).returns('nothing')
+ wrapper = ExceptionWrapper.new(nil, exc)
- assert_equal [ code: 'nothing', line_number: 27 ], wrapper.source_extracts
+ assert_called_with(wrapper, :source_fragment, ['c:/path/to/rails/app/controller.rb', 27], returns: 'nothing') do
+ assert_equal [ code: 'nothing', line_number: 27 ], wrapper.source_extracts
+ end
end
test '#source_extracts works with non standard backtrace' do
exc = TestError.new('invalid')
- wrapper = ExceptionWrapper.new({}, exc)
- wrapper.expects(:source_fragment).with('invalid', 0).returns('nothing')
+ wrapper = ExceptionWrapper.new(nil, exc)
- assert_equal [ code: 'nothing', line_number: 0 ], wrapper.source_extracts
+ assert_called_with(wrapper, :source_fragment, ['invalid', 0], returns: 'nothing') do
+ assert_equal [ code: 'nothing', line_number: 0 ], wrapper.source_extracts
+ end
end
test '#application_trace returns traces only from the application' do
exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
- wrapper = ExceptionWrapper.new(@environment, exception)
+ wrapper = ExceptionWrapper.new(@cleaner, exception)
assert_equal [ "lib/file.rb:42:in `index'" ], wrapper.application_trace
end
test '#application_trace cannot be nil' do
- nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
- nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+ nil_backtrace_wrapper = ExceptionWrapper.new(@cleaner, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new(nil, BadlyDefinedError.new)
assert_equal [], nil_backtrace_wrapper.application_trace
assert_equal [], nil_cleaner_wrapper.application_trace
@@ -69,14 +67,14 @@ module ActionDispatch
test '#framework_trace returns traces outside the application' do
exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
- wrapper = ExceptionWrapper.new(@environment, exception)
+ wrapper = ExceptionWrapper.new(@cleaner, exception)
assert_equal caller, wrapper.framework_trace
end
test '#framework_trace cannot be nil' do
- nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
- nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+ nil_backtrace_wrapper = ExceptionWrapper.new(@cleaner, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new(nil, BadlyDefinedError.new)
assert_equal [], nil_backtrace_wrapper.framework_trace
assert_equal [], nil_cleaner_wrapper.framework_trace
@@ -84,14 +82,14 @@ module ActionDispatch
test '#full_trace returns application and framework traces' do
exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
- wrapper = ExceptionWrapper.new(@environment, exception)
+ wrapper = ExceptionWrapper.new(@cleaner, exception)
assert_equal exception.backtrace, wrapper.full_trace
end
test '#full_trace cannot be nil' do
- nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
- nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+ nil_backtrace_wrapper = ExceptionWrapper.new(@cleaner, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new(nil, BadlyDefinedError.new)
assert_equal [], nil_backtrace_wrapper.full_trace
assert_equal [], nil_cleaner_wrapper.full_trace
@@ -99,7 +97,7 @@ module ActionDispatch
test '#traces returns every trace by category enumerated with an index' do
exception = TestError.new("lib/file.rb:42:in `index'", "/gems/rack.rb:43:in `index'")
- wrapper = ExceptionWrapper.new(@environment, exception)
+ wrapper = ExceptionWrapper.new(@cleaner, exception)
assert_equal({
'Application Trace' => [ id: 0, trace: "lib/file.rb:42:in `index'" ],
diff --git a/actionpack/test/dispatch/header_test.rb b/actionpack/test/dispatch/header_test.rb
index e2b38c23bc..7f1ef121b7 100644
--- a/actionpack/test/dispatch/header_test.rb
+++ b/actionpack/test/dispatch/header_test.rb
@@ -1,15 +1,19 @@
require "abstract_unit"
class HeaderTest < ActiveSupport::TestCase
+ def make_headers(hash)
+ ActionDispatch::Http::Headers.new ActionDispatch::Request.new hash
+ end
+
setup do
- @headers = ActionDispatch::Http::Headers.new(
+ @headers = make_headers(
"CONTENT_TYPE" => "text/plain",
"HTTP_REFERER" => "/some/page"
)
end
test "#new does not normalize the data" do
- headers = ActionDispatch::Http::Headers.new(
+ headers = make_headers(
"Content-Type" => "application/json",
"HTTP_REFERER" => "/some/page",
"Host" => "http://test.com")
@@ -38,6 +42,24 @@ class HeaderTest < ActiveSupport::TestCase
assert_equal "127.0.0.1", @headers["HTTP_HOST"]
end
+ test "add to multivalued headers" do
+ # Sets header when not present
+ @headers.add 'Foo', '1'
+ assert_equal '1', @headers['Foo']
+
+ # Ignores nil values
+ @headers.add 'Foo', nil
+ assert_equal '1', @headers['Foo']
+
+ # Converts value to string
+ @headers.add 'Foo', 1
+ assert_equal '1,1', @headers['Foo']
+
+ # Case-insensitive
+ @headers.add 'fOo', 2
+ assert_equal '1,1,2', @headers['foO']
+ end
+
test "headers can contain numbers" do
@headers["Content-MD5"] = "Q2hlY2sgSW50ZWdyaXR5IQ=="
@@ -108,7 +130,7 @@ class HeaderTest < ActiveSupport::TestCase
end
test "env variables with . are not modified" do
- headers = ActionDispatch::Http::Headers.new
+ headers = make_headers({})
headers.merge! "rack.input" => "",
"rack.request.cookie_hash" => "",
"action_dispatch.logger" => ""
@@ -119,7 +141,7 @@ class HeaderTest < ActiveSupport::TestCase
end
test "symbols are treated as strings" do
- headers = ActionDispatch::Http::Headers.new
+ headers = make_headers({})
headers.merge!(:SERVER_NAME => "example.com",
"HTTP_REFERER" => "/",
:Host => "test.com")
@@ -130,7 +152,7 @@ class HeaderTest < ActiveSupport::TestCase
test "headers directly modifies the passed environment" do
env = {"HTTP_REFERER" => "/"}
- headers = ActionDispatch::Http::Headers.new(env)
+ headers = make_headers(env)
headers['Referer'] = "http://example.com/"
headers.merge! "CONTENT_TYPE" => "text/plain"
assert_equal({"HTTP_REFERER"=>"http://example.com/",
diff --git a/actionpack/test/dispatch/live_response_test.rb b/actionpack/test/dispatch/live_response_test.rb
index 512f3a8a7a..160cdc1582 100644
--- a/actionpack/test/dispatch/live_response_test.rb
+++ b/actionpack/test/dispatch/live_response_test.rb
@@ -1,5 +1,5 @@
require 'abstract_unit'
-require 'active_support/concurrency/latch'
+require 'concurrent/atomic/count_down_latch'
module ActionController
module Live
@@ -27,18 +27,18 @@ module ActionController
end
def test_parallel
- latch = ActiveSupport::Concurrency::Latch.new
+ latch = Concurrent::CountDownLatch.new
t = Thread.new {
@response.stream.write 'foo'
- latch.await
+ latch.wait
@response.stream.close
}
@response.await_commit
@response.each do |part|
assert_equal 'foo', part
- latch.release
+ latch.count_down
end
assert t.join
end
@@ -62,15 +62,15 @@ module ActionController
def test_headers_cannot_be_written_after_webserver_reads
@response.stream.write 'omg'
- latch = ActiveSupport::Concurrency::Latch.new
+ latch = Concurrent::CountDownLatch.new
t = Thread.new {
- @response.stream.each do |chunk|
- latch.release
+ @response.stream.each do
+ latch.count_down
end
}
- latch.await
+ latch.wait
assert @response.headers.frozen?
e = assert_raises(ActionDispatch::IllegalStateError) do
@response.headers['Content-Length'] = "zomg"
@@ -83,6 +83,8 @@ module ActionController
def test_headers_cannot_be_written_after_close
@response.stream.close
+ # we can add data until it's actually written, which happens on `each`
+ @response.each { |x| }
e = assert_raises(ActionDispatch::IllegalStateError) do
@response.headers['Content-Length'] = "zomg"
diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb
index 889f9a4736..e783df855e 100644
--- a/actionpack/test/dispatch/mapper_test.rb
+++ b/actionpack/test/dispatch/mapper_test.rb
@@ -4,13 +4,6 @@ module ActionDispatch
module Routing
class MapperTest < ActiveSupport::TestCase
class FakeSet < ActionDispatch::Routing::RouteSet
- attr_reader :routes
- alias :set :routes
-
- def initialize
- @routes = []
- end
-
def resources_path_names
{}
end
@@ -19,16 +12,24 @@ module ActionDispatch
ActionDispatch::Request
end
- def add_route(*args)
- routes << args
+ def dispatcher_class
+ RouteSet::Dispatcher
+ end
+
+ def defaults
+ routes.map(&:defaults)
end
def conditions
- routes.map { |x| x[1] }
+ routes.map(&:constraints)
end
def requirements
- routes.map { |x| x[2] }
+ routes.map(&:path).map(&:requirements)
+ end
+
+ def asts
+ routes.map(&:path).map(&:spec)
end
end
@@ -36,18 +37,76 @@ module ActionDispatch
Mapper.new FakeSet.new
end
+ def test_scope_raises_on_anchor
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ assert_raises(ArgumentError) do
+ mapper.scope(anchor: false) do
+ end
+ end
+ end
+
+ def test_blows_up_without_via
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ assert_raises(ArgumentError) do
+ mapper.match '/', :to => 'posts#index', :as => :main
+ end
+ end
+
+ def test_unscoped_formatted
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/foo', :to => 'posts#index', :as => :main, :format => true
+ assert_equal({:controller=>"posts", :action=>"index"},
+ fakeset.defaults.first)
+ assert_equal "/foo.:format", fakeset.asts.first.to_s
+ end
+
+ def test_scoped_formatted
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.scope(format: true) do
+ mapper.get '/foo', :to => 'posts#index', :as => :main
+ end
+ assert_equal({:controller=>"posts", :action=>"index"},
+ fakeset.defaults.first)
+ assert_equal "/foo.:format", fakeset.asts.first.to_s
+ end
+
+ def test_random_keys
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.scope(omg: :awesome) do
+ mapper.get '/', :to => 'posts#index', :as => :main
+ end
+ assert_equal({:omg=>:awesome, :controller=>"posts", :action=>"index"},
+ fakeset.defaults.first)
+ assert_equal("GET", fakeset.routes.first.verb)
+ end
+
def test_mapping_requirements
- options = { :controller => 'foo', :action => 'bar', :via => :get }
- m = Mapper::Mapping.build({}, FakeSet.new, '/store/:name(*rest)', nil, options)
- _, _, requirements, _ = m.to_route
- assert_equal(/.+?/, requirements[:rest])
+ options = { }
+ scope = Mapper::Scope.new({})
+ ast = Journey::Parser.parse '/store/:name(*rest)'
+ m = Mapper::Mapping.build(scope, FakeSet.new, ast, 'foo', 'bar', nil, [:get], nil, {}, true, options)
+ assert_equal(/.+?/, m.requirements[:rest])
+ end
+
+ def test_via_scope
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.scope(via: :put) do
+ mapper.match '/', :to => 'posts#index', :as => :main
+ end
+ assert_equal("PUT", fakeset.routes.first.verb)
end
def test_map_slash
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get '/', :to => 'posts#index', :as => :main
- assert_equal '/', fakeset.conditions.first[:path_info]
+ assert_equal '/', fakeset.asts.first.to_s
end
def test_map_more_slashes
@@ -56,14 +115,14 @@ module ActionDispatch
# FIXME: is this a desired behavior?
mapper.get '/one/two/', :to => 'posts#index', :as => :main
- assert_equal '/one/two(.:format)', fakeset.conditions.first[:path_info]
+ assert_equal '/one/two(.:format)', fakeset.asts.first.to_s
end
def test_map_wildcard
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get '/*path', :to => 'pages#show'
- assert_equal '/*path(.:format)', fakeset.conditions.first[:path_info]
+ assert_equal '/*path(.:format)', fakeset.asts.first.to_s
assert_equal(/.+?/, fakeset.requirements.first[:path])
end
@@ -71,7 +130,7 @@ module ActionDispatch
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get '/*path/foo/:bar', :to => 'pages#show'
- assert_equal '/*path/foo/:bar(.:format)', fakeset.conditions.first[:path_info]
+ assert_equal '/*path/foo/:bar(.:format)', fakeset.asts.first.to_s
assert_equal(/.+?/, fakeset.requirements.first[:path])
end
@@ -79,7 +138,7 @@ module ActionDispatch
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get '/*foo/*bar', :to => 'pages#show'
- assert_equal '/*foo/*bar(.:format)', fakeset.conditions.first[:path_info]
+ assert_equal '/*foo/*bar(.:format)', fakeset.asts.first.to_s
assert_equal(/.+?/, fakeset.requirements.first[:foo])
assert_equal(/.+?/, fakeset.requirements.first[:bar])
end
@@ -88,7 +147,7 @@ module ActionDispatch
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get '/*path', :to => 'pages#show', :format => false
- assert_equal '/*path', fakeset.conditions.first[:path_info]
+ assert_equal '/*path', fakeset.asts.first.to_s
assert_nil fakeset.requirements.first[:path]
end
@@ -96,7 +155,7 @@ module ActionDispatch
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get '/*path', :to => 'pages#show', :format => true
- assert_equal '/*path.:format', fakeset.conditions.first[:path_info]
+ assert_equal '/*path.:format', fakeset.asts.first.to_s
end
def test_raising_helpful_error_on_invalid_arguments
diff --git a/actionpack/test/dispatch/middleware_stack/middleware_test.rb b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
deleted file mode 100644
index 9607f026db..0000000000
--- a/actionpack/test/dispatch/middleware_stack/middleware_test.rb
+++ /dev/null
@@ -1,77 +0,0 @@
-require 'abstract_unit'
-require 'action_dispatch/middleware/stack'
-
-module ActionDispatch
- class MiddlewareStack
- class MiddlewareTest < ActiveSupport::TestCase
- class Omg; end
-
- {
- 'concrete' => Omg,
- 'anonymous' => Class.new
- }.each do |name, klass|
-
- define_method("test_#{name}_klass") do
- mw = Middleware.new klass
- assert_equal klass, mw.klass
- end
-
- define_method("test_#{name}_==") do
- mw1 = Middleware.new klass
- mw2 = Middleware.new klass
- assert_equal mw1, mw2
- end
-
- end
-
- def test_string_class
- mw = Middleware.new Omg.name
- assert_equal Omg, mw.klass
- end
-
- def test_double_equal_works_with_classes
- k = Class.new
- mw = Middleware.new k
- assert_operator mw, :==, k
-
- result = mw != Class.new
- assert result, 'middleware should not equal other anon class'
- end
-
- def test_double_equal_works_with_strings
- mw = Middleware.new Omg
- assert_operator mw, :==, Omg.name
- end
-
- def test_double_equal_normalizes_strings
- mw = Middleware.new Omg
- assert_operator mw, :==, "::#{Omg.name}"
- end
-
- def test_middleware_loads_classnames_from_cache
- mw = Class.new(Middleware) {
- attr_accessor :classcache
- }.new(Omg.name)
-
- fake_cache = { mw.name => Omg }
- mw.classcache = fake_cache
-
- assert_equal Omg, mw.klass
-
- fake_cache[mw.name] = Middleware
- assert_equal Middleware, mw.klass
- end
-
- def test_middleware_always_returns_class
- mw = Class.new(Middleware) {
- attr_accessor :classcache
- }.new(Omg)
-
- fake_cache = { mw.name => Middleware }
- mw.classcache = fake_cache
-
- assert_equal Omg, mw.klass
- end
- end
- end
-end
diff --git a/actionpack/test/dispatch/middleware_stack_test.rb b/actionpack/test/dispatch/middleware_stack_test.rb
index 948a690979..33aa616474 100644
--- a/actionpack/test/dispatch/middleware_stack_test.rb
+++ b/actionpack/test/dispatch/middleware_stack_test.rb
@@ -4,6 +4,7 @@ class MiddlewareStackTest < ActiveSupport::TestCase
class FooMiddleware; end
class BarMiddleware; end
class BazMiddleware; end
+ class HiyaMiddleware; end
class BlockMiddleware
attr_reader :block
def initialize(&block)
@@ -17,6 +18,20 @@ class MiddlewareStackTest < ActiveSupport::TestCase
@stack.use BarMiddleware
end
+ def test_delete_with_string_is_deprecated
+ assert_deprecated do
+ assert_difference "@stack.size", -1 do
+ @stack.delete FooMiddleware.name
+ end
+ end
+ end
+
+ def test_delete_works
+ assert_difference "@stack.size", -1 do
+ @stack.delete FooMiddleware
+ end
+ end
+
test "use should push middleware as class onto the stack" do
assert_difference "@stack.size" do
@stack.use BazMiddleware
@@ -25,17 +40,21 @@ class MiddlewareStackTest < ActiveSupport::TestCase
end
test "use should push middleware as a string onto the stack" do
- assert_difference "@stack.size" do
- @stack.use "MiddlewareStackTest::BazMiddleware"
+ assert_deprecated do
+ assert_difference "@stack.size" do
+ @stack.use "MiddlewareStackTest::BazMiddleware"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
end
- assert_equal BazMiddleware, @stack.last.klass
end
test "use should push middleware as a symbol onto the stack" do
- assert_difference "@stack.size" do
- @stack.use :"MiddlewareStackTest::BazMiddleware"
+ assert_deprecated do
+ assert_difference "@stack.size" do
+ @stack.use :"MiddlewareStackTest::BazMiddleware"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
end
- assert_equal BazMiddleware, @stack.last.klass
end
test "use should push middleware class with arguments onto the stack" do
@@ -88,30 +107,28 @@ class MiddlewareStackTest < ActiveSupport::TestCase
end
test "unshift adds a new middleware at the beginning of the stack" do
- @stack.unshift :"MiddlewareStackTest::BazMiddleware"
- assert_equal BazMiddleware, @stack.first.klass
+ assert_deprecated do
+ @stack.unshift :"MiddlewareStackTest::BazMiddleware"
+ assert_equal BazMiddleware, @stack.first.klass
+ end
end
test "raise an error on invalid index" do
assert_raise RuntimeError do
- @stack.insert("HiyaMiddleware", BazMiddleware)
+ @stack.insert(HiyaMiddleware, BazMiddleware)
end
assert_raise RuntimeError do
- @stack.insert_after("HiyaMiddleware", BazMiddleware)
+ @stack.insert_after(HiyaMiddleware, BazMiddleware)
end
end
test "lazy evaluates middleware class" do
- assert_difference "@stack.size" do
- @stack.use "MiddlewareStackTest::BazMiddleware"
+ assert_deprecated do
+ assert_difference "@stack.size" do
+ @stack.use "MiddlewareStackTest::BazMiddleware"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
end
- assert_equal BazMiddleware, @stack.last.klass
- end
-
- test "lazy compares so unloaded constants are not loaded" do
- @stack.use "UnknownMiddleware"
- @stack.use :"MiddlewareStackTest::BazMiddleware"
- assert @stack.include?("::MiddlewareStackTest::BazMiddleware")
end
end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index 3017a9c2d6..149e37bf3d 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
class MimeTypeTest < ActiveSupport::TestCase
-
test "parse single" do
Mime::LOOKUP.each_key do |mime_type|
unless mime_type == 'image/*'
@@ -11,97 +10,95 @@ class MimeTypeTest < ActiveSupport::TestCase
end
test "unregister" do
+ assert_nil Mime[:mobile]
+
begin
- Mime::Type.register("text/x-mobile", :mobile)
- assert defined?(Mime::MOBILE)
- assert_equal Mime::MOBILE, Mime::LOOKUP['text/x-mobile']
- assert_equal Mime::MOBILE, Mime::EXTENSION_LOOKUP['mobile']
+ mime = Mime::Type.register("text/x-mobile", :mobile)
+ assert_equal mime, Mime[:mobile]
+ assert_equal mime, Mime::Type.lookup('text/x-mobile')
+ assert_equal mime, Mime::Type.lookup_by_extension(:mobile)
Mime::Type.unregister(:mobile)
- assert !defined?(Mime::MOBILE), "Mime::MOBILE should not be defined"
- assert !Mime::LOOKUP.has_key?('text/x-mobile'), "Mime::LOOKUP should not have key ['text/x-mobile]"
- assert !Mime::EXTENSION_LOOKUP.has_key?('mobile'), "Mime::EXTENSION_LOOKUP should not have key ['mobile]"
+ assert_nil Mime[:mobile], "Mime[:mobile] should be nil after unregistering :mobile"
+ assert_nil Mime::Type.lookup_by_extension(:mobile), "Should be missing MIME extension lookup for :mobile"
ensure
- Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) }
- Mime::LOOKUP.reject!{|key,_| key == 'text/x-mobile'}
+ Mime::Type.unregister :mobile
end
end
test "parse text with trailing star at the beginning" do
accept = "text/*, text/html, application/json, multipart/form-data"
- expect = [Mime::HTML, Mime::TEXT, Mime::JS, Mime::CSS, Mime::ICS, Mime::CSV, Mime::VCF, Mime::XML, Mime::YAML, Mime::JSON, Mime::MULTIPART_FORM]
+ expect = [Mime[:html], Mime[:text], Mime[:js], Mime[:css], Mime[:ics], Mime[:csv], Mime[:vcf], Mime[:xml], Mime[:yaml], Mime[:json], Mime[:multipart_form]]
parsed = Mime::Type.parse(accept)
assert_equal expect, parsed
end
test "parse text with trailing star in the end" do
accept = "text/html, application/json, multipart/form-data, text/*"
- expect = [Mime::HTML, Mime::JSON, Mime::MULTIPART_FORM, Mime::TEXT, Mime::JS, Mime::CSS, Mime::ICS, Mime::CSV, Mime::VCF, Mime::XML, Mime::YAML]
+ expect = [Mime[:html], Mime[:json], Mime[:multipart_form], Mime[:text], Mime[:js], Mime[:css], Mime[:ics], Mime[:csv], Mime[:vcf], Mime[:xml], Mime[:yaml]]
parsed = Mime::Type.parse(accept)
assert_equal expect, parsed
end
test "parse text with trailing star" do
accept = "text/*"
- expect = [Mime::HTML, Mime::TEXT, Mime::JS, Mime::CSS, Mime::ICS, Mime::CSV, Mime::VCF, Mime::XML, Mime::YAML, Mime::JSON]
+ expect = [Mime[:html], Mime[:text], Mime[:js], Mime[:css], Mime[:ics], Mime[:csv], Mime[:vcf], Mime[:xml], Mime[:yaml], Mime[:json]]
parsed = Mime::Type.parse(accept)
assert_equal expect, parsed
end
test "parse application with trailing star" do
accept = "application/*"
- expect = [Mime::HTML, Mime::JS, Mime::XML, Mime::RSS, Mime::ATOM, Mime::YAML, Mime::URL_ENCODED_FORM, Mime::JSON, Mime::PDF, Mime::ZIP]
+ expect = [Mime[:html], Mime[:js], Mime[:xml], Mime[:rss], Mime[:atom], Mime[:yaml], Mime[:url_encoded_form], Mime[:json], Mime[:pdf], Mime[:zip]]
parsed = Mime::Type.parse(accept)
assert_equal expect, parsed
end
test "parse without q" do
accept = "text/xml,application/xhtml+xml,text/yaml,application/xml,text/html,image/png,text/plain,application/pdf,*/*"
- expect = [Mime::HTML, Mime::XML, Mime::YAML, Mime::PNG, Mime::TEXT, Mime::PDF, Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept)
+ expect = [Mime[:html], Mime[:xml], Mime[:yaml], Mime[:png], Mime[:text], Mime[:pdf], '*/*']
+ assert_equal expect.map(&:to_s), Mime::Type.parse(accept).map(&:to_s)
end
test "parse with q" do
accept = "text/xml,application/xhtml+xml,text/yaml; q=0.3,application/xml,text/html; q=0.8,image/png,text/plain; q=0.5,application/pdf,*/*; q=0.2"
- expect = [Mime::HTML, Mime::XML, Mime::PNG, Mime::PDF, Mime::TEXT, Mime::YAML, Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept)
+ expect = [Mime[:html], Mime[:xml], Mime[:png], Mime[:pdf], Mime[:text], Mime[:yaml], '*/*']
+ assert_equal expect.map(&:to_s), Mime::Type.parse(accept).map(&:to_s)
end
test "parse single media range with q" do
accept = "text/html;q=0.9"
- expect = [Mime::HTML]
+ expect = [Mime[:html]]
assert_equal expect, Mime::Type.parse(accept)
end
test "parse arbitrary media type parameters" do
accept = 'multipart/form-data; boundary="simple boundary"'
- expect = [Mime::MULTIPART_FORM]
+ expect = [Mime[:multipart_form]]
assert_equal expect, Mime::Type.parse(accept)
end
# Accept header send with user HTTP_USER_AGENT: Sunrise/0.42j (Windows XP)
test "parse broken acceptlines" do
accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5"
- expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept).collect(&:to_s)
+ expect = [Mime[:html], Mime[:xml], "image/*", Mime[:text], '*/*']
+ assert_equal expect.map(&:to_s), Mime::Type.parse(accept).map(&:to_s)
end
# Accept header send with user HTTP_USER_AGENT: Mozilla/4.0
# (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1)
test "parse other broken acceptlines" do
accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*"
- expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept).collect(&:to_s)
+ expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', '*/*']
+ assert_equal expect.map(&:to_s), Mime::Type.parse(accept).map(&:to_s)
end
test "custom type" do
begin
- Mime::Type.register("image/foo", :foo)
- assert_nothing_raised do
- assert_equal Mime::FOO, Mime::SET.last
- end
+ type = Mime::Type.register("image/foo", :foo)
+ assert_equal type, Mime[:foo]
ensure
- Mime::Type.unregister(:FOO)
+ Mime::Type.unregister(:foo)
end
end
@@ -109,10 +106,10 @@ class MimeTypeTest < ActiveSupport::TestCase
begin
Mime::Type.register "text/foobar", :foobar, ["text/foo", "text/bar"]
%w[text/foobar text/foo text/bar].each do |type|
- assert_equal Mime::FOOBAR, type
+ assert_equal Mime[:foobar], type
end
ensure
- Mime::Type.unregister(:FOOBAR)
+ Mime::Type.unregister(:foobar)
end
end
@@ -123,10 +120,10 @@ class MimeTypeTest < ActiveSupport::TestCase
registered_mimes << mime
end
- Mime::Type.register("text/foo", :foo)
- assert_equal [Mime::FOO], registered_mimes
+ mime = Mime::Type.register("text/foo", :foo)
+ assert_equal [mime], registered_mimes
ensure
- Mime::Type.unregister(:FOO)
+ Mime::Type.unregister(:foo)
end
end
@@ -134,70 +131,67 @@ class MimeTypeTest < ActiveSupport::TestCase
begin
Mime::Type.register "text/foobar", :foobar, [], [:foo, "bar"]
%w[foobar foo bar].each do |extension|
- assert_equal Mime::FOOBAR, Mime::EXTENSION_LOOKUP[extension]
+ assert_equal Mime[:foobar], Mime::EXTENSION_LOOKUP[extension]
end
ensure
- Mime::Type.unregister(:FOOBAR)
+ Mime::Type.unregister(:foobar)
end
end
test "register alias" do
begin
Mime::Type.register_alias "application/xhtml+xml", :foobar
- assert_equal Mime::HTML, Mime::EXTENSION_LOOKUP['foobar']
+ assert_equal Mime[:html], Mime::EXTENSION_LOOKUP['foobar']
ensure
- Mime::Type.unregister(:FOOBAR)
+ Mime::Type.unregister(:foobar)
end
end
test "type should be equal to symbol" do
- assert_equal Mime::HTML, 'application/xhtml+xml'
- assert_equal Mime::HTML, :html
+ assert_equal Mime[:html], 'application/xhtml+xml'
+ assert_equal Mime[:html], :html
end
test "type convenience methods" do
- # Don't test Mime::ALL, since it Mime::ALL#html? == true
- types = Mime::SET.symbols.uniq - [:all, :iphone]
-
- # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
- types.delete_if { |type| !Mime.const_defined?(type.upcase) }
-
+ types = Mime::SET.symbols.uniq - [:iphone]
types.each do |type|
- mime = Mime.const_get(type.upcase)
+ mime = Mime[type]
assert mime.respond_to?("#{type}?"), "#{mime.inspect} does not respond to #{type}?"
- assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?"
+ assert_equal type, mime.symbol, "#{mime.inspect} is not #{type}?"
invalid_types = types - [type]
- invalid_types.delete(:html) if Mime::Type.html_types.include?(type)
- invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
+ invalid_types.delete(:html)
+ invalid_types.each { |other_type|
+ assert_not_equal mime.symbol, other_type, "#{mime.inspect} is #{other_type}?"
+ }
end
end
- test "mime all is html" do
- assert Mime::ALL.all?, "Mime::ALL is not all?"
- assert Mime::ALL.html?, "Mime::ALL is not html?"
+ test "deprecated lookup" do
+ assert_deprecated do
+ Mime::HTML
+ end
end
- test "verifiable mime types" do
- all_types = Mime::SET.symbols
- all_types.uniq!
- # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
- all_types.delete_if { |type| !Mime.const_defined?(type.upcase) }
+ test "deprecated const_defined?" do
+ assert_deprecated do
+ Mime.const_defined? :HTML
+ end
end
test "references gives preference to symbols before strings" do
- assert_equal :html, Mime::HTML.ref
+ assert_equal :html, Mime[:html].ref
another = Mime::Type.lookup("foo/bar")
assert_nil another.to_sym
assert_equal "foo/bar", another.ref
end
test "regexp matcher" do
- assert Mime::JS =~ "text/javascript"
- assert Mime::JS =~ "application/javascript"
- assert Mime::JS !~ "text/html"
- assert !(Mime::JS !~ "text/javascript")
- assert !(Mime::JS !~ "application/javascript")
- assert Mime::HTML =~ 'application/xhtml+xml'
+ assert Mime[:js] =~ "text/javascript"
+ assert Mime[:js] =~ "application/javascript"
+ assert Mime[:js] !~ "text/html"
+ assert !(Mime[:js] !~ "text/javascript")
+ assert !(Mime[:js] !~ "application/javascript")
+ assert Mime[:html] =~ 'application/xhtml+xml'
end
end
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
index 6a439be2b5..d027f09762 100644
--- a/actionpack/test/dispatch/mount_test.rb
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -49,7 +49,7 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
def test_app_name_is_properly_generated_when_engine_is_mounted_in_resources
assert Router.mounted_helpers.method_defined?(:user_fake_mounted_at_resource),
"A mounted helper should be defined with a parent's prefix"
- assert Router.named_routes.routes[:user_fake_mounted_at_resource],
+ assert Router.named_routes.key?(:user_fake_mounted_at_resource),
"A named route should be defined with a parent's prefix"
end
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
index f90d5499d7..d75e31db62 100644
--- a/actionpack/test/dispatch/prefix_generation_test.rb
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -73,26 +73,26 @@ module TestGenerationPrefix
include RailsApplication.routes.mounted_helpers
def index
- render :text => posts_path
+ render plain: posts_path
end
def show
- render :text => post_path(:id => params[:id])
+ render plain: post_path(id: params[:id])
end
def url_to_application
path = main_app.url_for(:controller => "outside_engine_generating",
:action => "index",
:only_path => true)
- render :text => path
+ render plain: path
end
def polymorphic_path_for_engine
- render :text => polymorphic_path(Post.new)
+ render plain: polymorphic_path(Post.new)
end
def conflicting
- render :text => "engine"
+ render plain: "engine"
end
end
@@ -101,28 +101,28 @@ module TestGenerationPrefix
include RailsApplication.routes.url_helpers
def index
- render :text => blog_engine.post_path(:id => 1)
+ render plain: blog_engine.post_path(id: 1)
end
def polymorphic_path_for_engine
- render :text => blog_engine.polymorphic_path(Post.new)
+ render plain: blog_engine.polymorphic_path(Post.new)
end
def polymorphic_path_for_app
- render :text => polymorphic_path(Post.new)
+ render plain: polymorphic_path(Post.new)
end
def polymorphic_with_url_for
- render :text => blog_engine.url_for(Post.new)
+ render plain: blog_engine.url_for(Post.new)
end
def conflicting
- render :text => "application"
+ render plain: "application"
end
def ivar_usage
@blog_engine = "Not the engine route helper"
- render :text => blog_engine.post_path(:id => 1)
+ render plain: blog_engine.post_path(id: 1)
end
end
@@ -378,7 +378,7 @@ module TestGenerationPrefix
include RailsApplication.routes.mounted_helpers
def show
- render :text => post_path(:id => params[:id])
+ render plain: post_path(id: params[:id])
end
end
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index d77341bc64..a3992ad008 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -37,6 +37,13 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
)
end
+ test "parses json params for application/vnd.api+json" do
+ assert_parses(
+ {"person" => {"name" => "David"}},
+ "{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/vnd.api+json' }
+ )
+ end
+
test "nils are stripped from collections" do
assert_parses(
{"person" => []},
@@ -69,8 +76,8 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
$stderr = StringIO.new # suppress the log
json = "[\"person]\": {\"name\": \"David\"}}"
exception = assert_raise(ActionDispatch::ParamsParser::ParseError) { post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => false} }
- assert_equal JSON::ParserError, exception.original_exception.class
- assert_equal exception.original_exception.message, exception.message
+ assert_equal JSON::ParserError, exception.cause.class
+ assert_equal exception.cause.message, exception.message
ensure
$stderr = STDERR
end
@@ -113,7 +120,7 @@ class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
def parse
self.class.last_request_parameters = request.request_parameters
- self.class.last_parameters = params
+ self.class.last_parameters = params.to_unsafe_h
head :ok
end
end
@@ -136,6 +143,13 @@ class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
)
end
+ test "parses json params for application/vnd.api+json" do
+ assert_parses(
+ {"user" => {"username" => "sikachu"}, "username" => "sikachu"},
+ "{\"username\": \"sikachu\"}", { 'CONTENT_TYPE' => 'application/vnd.api+json' }
+ )
+ end
+
test "parses json with non-object JSON content" do
assert_parses(
{"user" => {"_json" => "string content" }, "_json" => "string content" },
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 50f69c53cb..b36fbd3c76 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -17,7 +17,7 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
end
def read
- render :text => "File: #{params[:uploaded_data].read}"
+ render plain: "File: #{params[:uploaded_data].read}"
end
end
@@ -63,6 +63,17 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
assert_equal 'contents', file.read
end
+ test "parses utf8 filename with percent character" do
+ params = parse_multipart('utf8_filename')
+ assert_equal %w(file foo), params.keys.sort
+ assert_equal 'bar', params['foo']
+
+ file = params['file']
+ assert_equal 'ファイル%名.txt', file.original_filename
+ assert_equal "text/plain", file.content_type
+ assert_equal 'contents', file.read
+ end
+
test "parses boundary problem file" do
params = parse_multipart('boundary_problem_file')
assert_equal %w(file foo), params.keys.sort
diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb
index 10fb04e230..ae0e7e93ed 100644
--- a/actionpack/test/dispatch/request/session_test.rb
+++ b/actionpack/test/dispatch/request/session_test.rb
@@ -4,40 +4,42 @@ require 'action_dispatch/middleware/session/abstract_store'
module ActionDispatch
class Request
class SessionTest < ActiveSupport::TestCase
+ attr_reader :req
+
+ def setup
+ @req = ActionDispatch::Request.new({})
+ end
+
def test_create_adds_itself_to_env
- env = {}
- s = Session.create(store, env, {})
- assert_equal s, env[Rack::Session::Abstract::ENV_SESSION_KEY]
+ s = Session.create(store, req, {})
+ assert_equal s, req.env[Rack::RACK_SESSION]
end
def test_to_hash
- env = {}
- s = Session.create(store, env, {})
+ s = Session.create(store, req, {})
s['foo'] = 'bar'
assert_equal 'bar', s['foo']
assert_equal({'foo' => 'bar'}, s.to_hash)
end
def test_create_merges_old
- env = {}
- s = Session.create(store, env, {})
+ s = Session.create(store, req, {})
s['foo'] = 'bar'
- s1 = Session.create(store, env, {})
+ s1 = Session.create(store, req, {})
assert_not_equal s, s1
assert_equal 'bar', s1['foo']
end
def test_find
- env = {}
- assert_nil Session.find(env)
+ assert_nil Session.find(req)
- s = Session.create(store, env, {})
- assert_equal s, Session.find(env)
+ s = Session.create(store, req, {})
+ assert_equal s, Session.find(req)
end
def test_destroy
- s = Session.create(store, {}, {})
+ s = Session.create(store, req, {})
s['rails'] = 'ftw'
s.destroy
@@ -46,21 +48,21 @@ module ActionDispatch
end
def test_keys
- s = Session.create(store, {}, {})
+ s = Session.create(store, req, {})
s['rails'] = 'ftw'
s['adequate'] = 'awesome'
assert_equal %w[rails adequate], s.keys
end
def test_values
- s = Session.create(store, {}, {})
+ s = Session.create(store, req, {})
s['rails'] = 'ftw'
s['adequate'] = 'awesome'
assert_equal %w[ftw awesome], s.values
end
def test_clear
- s = Session.create(store, {}, {})
+ s = Session.create(store, req, {})
s['rails'] = 'ftw'
s['adequate'] = 'awesome'
@@ -69,7 +71,7 @@ module ActionDispatch
end
def test_update
- s = Session.create(store, {}, {})
+ s = Session.create(store, req, {})
s['rails'] = 'ftw'
s.update(:rails => 'awesome')
@@ -79,7 +81,7 @@ module ActionDispatch
end
def test_delete
- s = Session.create(store, {}, {})
+ s = Session.create(store, req, {})
s['rails'] = 'ftw'
s.delete('rails')
@@ -88,7 +90,7 @@ module ActionDispatch
end
def test_fetch
- session = Session.create(store, {}, {})
+ session = Session.create(store, req, {})
session['one'] = '1'
assert_equal '1', session.fetch(:one)
@@ -108,7 +110,7 @@ module ActionDispatch
Class.new {
def load_session(env); [1, {}]; end
def session_exists?(env); true; end
- def destroy_session(env, id, options); 123; end
+ def delete_session(env, id, options); 123; end
}.new
end
end
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 672dbd636c..08c4554721 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -663,6 +663,7 @@ class RequestMethod < BaseRequestTest
assert_equal 'GET', request.request_method
assert_equal 'GET', request.env["REQUEST_METHOD"]
+ assert request.get?
end
test "invalid http method raises exception" do
@@ -748,84 +749,94 @@ end
class RequestFormat < BaseRequestTest
test "xml format" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => 'xml' })
- assert_equal Mime::XML, request.format
+ assert_called(request, :parameters, times: 2, returns: {format: :xml}) do
+ assert_equal Mime[:xml], request.format
+ end
end
test "xhtml format" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => 'xhtml' })
- assert_equal Mime::HTML, request.format
+ assert_called(request, :parameters, times: 2, returns: {format: :xhtml}) do
+ assert_equal Mime[:html], request.format
+ end
end
test "txt format" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => 'txt' })
- assert_equal Mime::TEXT, request.format
+ assert_called(request, :parameters, times: 2, returns: {format: :txt}) do
+ assert_equal Mime[:text], request.format
+ end
end
test "XMLHttpRequest" do
request = stub_request(
'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest',
- 'HTTP_ACCEPT' => [Mime::JS, Mime::HTML, Mime::XML, "text/xml", Mime::ALL].join(",")
+ 'HTTP_ACCEPT' => [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(",")
)
- request.expects(:parameters).at_least_once.returns({})
- assert request.xhr?
- assert_equal Mime::JS, request.format
+
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert request.xhr?
+ assert_equal Mime[:js], request.format
+ end
end
test "can override format with parameter negative" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => :txt })
- assert !request.format.xml?
+ assert_called(request, :parameters, times: 2, returns: {format: :txt}) do
+ assert !request.format.xml?
+ end
end
test "can override format with parameter positive" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => :xml })
- assert request.format.xml?
+ assert_called(request, :parameters, times: 2, returns: {format: :xml}) do
+ assert request.format.xml?
+ end
end
test "formats text/html with accept header" do
request = stub_request 'HTTP_ACCEPT' => 'text/html'
- assert_equal [Mime::HTML], request.formats
+ assert_equal [Mime[:html]], request.formats
end
test "formats blank with accept header" do
request = stub_request 'HTTP_ACCEPT' => ''
- assert_equal [Mime::HTML], request.formats
+ assert_equal [Mime[:html]], request.formats
end
test "formats XMLHttpRequest with accept header" do
request = stub_request 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
- assert_equal [Mime::JS], request.formats
+ assert_equal [Mime[:js]], request.formats
end
test "formats application/xml with accept header" do
request = stub_request('CONTENT_TYPE' => 'application/xml; charset=UTF-8',
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest")
- assert_equal [Mime::XML], request.formats
+ assert_equal [Mime[:xml]], request.formats
end
test "formats format:text with accept header" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => :txt })
- assert_equal [Mime::TEXT], request.formats
+ assert_called(request, :parameters, times: 2, returns: {format: :txt}) do
+ assert_equal [Mime[:text]], request.formats
+ end
end
test "formats format:unknown with accept header" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ :format => :unknown })
- assert_instance_of Mime::NullType, request.format
+ assert_called(request, :parameters, times: 2, returns: {format: :unknown}) do
+ assert_instance_of Mime::NullType, request.format
+ end
end
test "format is not nil with unknown format" do
request = stub_request
- request.expects(:parameters).at_least_once.returns({ format: :hello })
- assert request.format.nil?
- assert_not request.format.html?
- assert_not request.format.xml?
- assert_not request.format.json?
+ assert_called(request, :parameters, times: 2, returns: {format: :hello}) do
+ assert request.format.nil?
+ assert_not request.format.html?
+ assert_not request.format.xml?
+ assert_not request.format.json?
+ end
end
test "format does not throw exceptions when malformed parameters" do
@@ -836,8 +847,9 @@ class RequestFormat < BaseRequestTest
test "formats with xhr request" do
request = stub_request 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
- request.expects(:parameters).at_least_once.returns({})
- assert_equal [Mime::JS], request.formats
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert_equal [Mime[:js]], request.formats
+ end
end
test "ignore_accept_header" do
@@ -846,30 +858,37 @@ class RequestFormat < BaseRequestTest
begin
request = stub_request 'HTTP_ACCEPT' => 'application/xml'
- request.expects(:parameters).at_least_once.returns({})
- assert_equal [ Mime::HTML ], request.formats
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert_equal [ Mime[:html] ], request.formats
+ end
request = stub_request 'HTTP_ACCEPT' => 'koz-asked/something-crazy'
- request.expects(:parameters).at_least_once.returns({})
- assert_equal [ Mime::HTML ], request.formats
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert_equal [ Mime[:html] ], request.formats
+ end
request = stub_request 'HTTP_ACCEPT' => '*/*;q=0.1'
- request.expects(:parameters).at_least_once.returns({})
- assert_equal [ Mime::HTML ], request.formats
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert_equal [ Mime[:html] ], request.formats
+ end
request = stub_request 'HTTP_ACCEPT' => 'application/jxw'
- request.expects(:parameters).at_least_once.returns({})
- assert_equal [ Mime::HTML ], request.formats
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert_equal [ Mime[:html] ], request.formats
+ end
request = stub_request 'HTTP_ACCEPT' => 'application/xml',
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
- request.expects(:parameters).at_least_once.returns({})
- assert_equal [ Mime::JS ], request.formats
+
+ assert_called(request, :parameters, times: 1, returns: {}) do
+ assert_equal [ Mime[:js] ], request.formats
+ end
request = stub_request 'HTTP_ACCEPT' => 'application/xml',
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
- request.expects(:parameters).at_least_once.returns({:format => :json})
- assert_equal [ Mime::JSON ], request.formats
+ assert_called(request, :parameters, times: 2, returns: {format: :json}) do
+ assert_equal [ Mime[:json] ], request.formats
+ end
ensure
ActionDispatch::Request.ignore_accept_header = old_ignore_accept_header
end
@@ -878,7 +897,7 @@ end
class RequestMimeType < BaseRequestTest
test "content type" do
- assert_equal Mime::HTML, stub_request('CONTENT_TYPE' => 'text/html').content_mime_type
+ assert_equal Mime[:html], stub_request('CONTENT_TYPE' => 'text/html').content_mime_type
end
test "no content type" do
@@ -886,11 +905,11 @@ class RequestMimeType < BaseRequestTest
end
test "content type is XML" do
- assert_equal Mime::XML, stub_request('CONTENT_TYPE' => 'application/xml').content_mime_type
+ assert_equal Mime[:xml], stub_request('CONTENT_TYPE' => 'application/xml').content_mime_type
end
test "content type with charset" do
- assert_equal Mime::XML, stub_request('CONTENT_TYPE' => 'application/xml; charset=UTF-8').content_mime_type
+ assert_equal Mime[:xml], stub_request('CONTENT_TYPE' => 'application/xml; charset=UTF-8').content_mime_type
end
test "user agent" do
@@ -903,9 +922,9 @@ class RequestMimeType < BaseRequestTest
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
)
- assert_equal nil, request.negotiate_mime([Mime::XML, Mime::JSON])
- assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::HTML])
- assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::ALL])
+ assert_equal nil, request.negotiate_mime([Mime[:xml], Mime[:json]])
+ assert_equal Mime[:html], request.negotiate_mime([Mime[:xml], Mime[:html]])
+ assert_equal Mime[:html], request.negotiate_mime([Mime[:xml], Mime::ALL])
end
test "negotiate_mime with content_type" do
@@ -914,19 +933,21 @@ class RequestMimeType < BaseRequestTest
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
)
- assert_equal Mime::XML, request.negotiate_mime([Mime::XML, Mime::CSV])
+ assert_equal Mime[:xml], request.negotiate_mime([Mime[:xml], Mime[:csv]])
end
end
class RequestParameters < BaseRequestTest
test "parameters" do
request = stub_request
- request.expects(:request_parameters).at_least_once.returns({ "foo" => 1 })
- request.expects(:query_parameters).at_least_once.returns({ "bar" => 2 })
- assert_equal({"foo" => 1, "bar" => 2}, request.parameters)
- assert_equal({"foo" => 1}, request.request_parameters)
- assert_equal({"bar" => 2}, request.query_parameters)
+ assert_called(request, :request_parameters, times: 2, returns: {"foo" => 1}) do
+ assert_called(request, :query_parameters, times: 2, returns: {"bar" => 2}) do
+ assert_equal({"foo" => 1, "bar" => 2}, request.parameters)
+ assert_equal({"foo" => 1}, request.request_parameters)
+ assert_equal({"bar" => 2}, request.query_parameters)
+ end
+ end
end
test "parameters not accessible after rack parse error" do
@@ -940,15 +961,33 @@ class RequestParameters < BaseRequestTest
end
end
+ test "path parameters with invalid UTF8 encoding" do
+ request = stub_request(
+ "action_dispatch.request.path_parameters" => { foo: "\xBE" }
+ )
+
+ err = assert_raises(ActionController::BadRequest) do
+ request.check_path_parameters!
+ end
+
+ assert_match "Invalid parameter encoding", err.message
+ assert_match "foo", err.message
+ assert_match "\\xBE", err.message
+ end
+
test "parameters not accessible after rack parse error of invalid UTF8 character" do
request = stub_request("QUERY_STRING" => "foo%81E=1")
+ assert_raises(ActionController::BadRequest) { request.parameters }
+ end
- 2.times do
- assert_raises(ActionController::BadRequest) do
- # rack will raise a Rack::Utils::InvalidParameterError when parsing this query string
- request.parameters
- end
- end
+ test "parameters containing an invalid UTF8 character" do
+ request = stub_request("QUERY_STRING" => "foo=%81E")
+ assert_raises(ActionController::BadRequest) { request.parameters }
+ end
+
+ test "parameters containing a deeply nested invalid UTF8 character" do
+ request = stub_request("QUERY_STRING" => "foo[bar]=%81E")
+ assert_raises(ActionController::BadRequest) { request.parameters }
end
test "parameters not accessible after rack parse error 1" do
@@ -973,8 +1012,8 @@ class RequestParameters < BaseRequestTest
request.parameters
end
- assert e.original_exception
- assert_equal e.original_exception.backtrace, e.backtrace
+ assert_not_nil e.cause
+ assert_equal e.cause.backtrace, e.backtrace
end
end
@@ -988,6 +1027,7 @@ class RequestParameterFilter < BaseRequestTest
[{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'],
[{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'],
[{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'],
+ [{'deep'=>{'cc'=>{'code'=>'bar','bar'=>'foo'},'ss'=>{'code'=>'bar'}}},{'deep'=>{'cc'=>{'code'=>'[FILTERED]','bar'=>'foo'},'ss'=>{'code'=>'bar'}}},%w'deep.cc.code'],
[{'baz'=>[{'foo'=>'baz'}, "1"]}, {'baz'=>[{'foo'=>'[FILTERED]'}, "1"]}, [/foo/]]]
test_hashes.each do |before_filter, after_filter, filter_words|
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 5fbd19acdf..981d820ccf 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -4,7 +4,7 @@ require 'rack/content_length'
class ResponseTest < ActiveSupport::TestCase
def setup
- @response = ActionDispatch::Response.new
+ @response = ActionDispatch::Response.create
end
def test_can_wait_until_commit
@@ -42,6 +42,18 @@ class ResponseTest < ActiveSupport::TestCase
assert_equal Encoding::UTF_8, response.body.encoding
end
+ def test_response_charset_writer
+ @response.charset = 'utf-16'
+ assert_equal 'utf-16', @response.charset
+ @response.charset = nil
+ assert_equal 'utf-8', @response.charset
+ end
+
+ def test_setting_content_type_header_impacts_content_type_method
+ @response.headers['Content-Type'] = "application/aaron"
+ assert_equal 'application/aaron', @response.content_type
+ end
+
test "simple output" do
@response.body = "Hello, World!"
@@ -60,6 +72,13 @@ class ResponseTest < ActiveSupport::TestCase
assert_equal 200, ActionDispatch::Response.new('200 OK').status
end
+ def test_only_set_charset_still_defaults_to_text_html
+ response = ActionDispatch::Response.new
+ response.charset = "utf-16"
+ _,headers,_ = response.to_a
+ assert_equal "text/html; charset=utf-16", headers['Content-Type']
+ end
+
test "utf8 output" do
@response.body = [1090, 1077, 1089, 1090].pack("U*")
@@ -72,12 +91,14 @@ class ResponseTest < ActiveSupport::TestCase
test "content type" do
[204, 304].each do |c|
+ @response = ActionDispatch::Response.new
@response.status = c.to_s
_, headers, _ = @response.to_a
assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
end
[200, 302, 404, 500].each do |c|
+ @response = ActionDispatch::Response.new
@response.status = c.to_s
_, headers, _ = @response.to_a
assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
@@ -125,17 +146,23 @@ class ResponseTest < ActiveSupport::TestCase
test "cookies" do
@response.set_cookie("user_name", :value => "david", :path => "/")
- status, headers, body = @response.to_a
+ _status, headers, _body = @response.to_a
assert_equal "user_name=david; path=/", headers["Set-Cookie"]
assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+ test "multiple cookies" do
+ @response.set_cookie("user_name", :value => "david", :path => "/")
@response.set_cookie("login", :value => "foo&bar", :path => "/", :expires => Time.utc(2005, 10, 10,5))
- status, headers, body = @response.to_a
+ _status, headers, _body = @response.to_a
assert_equal "user_name=david; path=/\nlogin=foo%26bar; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000", headers["Set-Cookie"]
assert_equal({"login" => "foo&bar", "user_name" => "david"}, @response.cookies)
+ end
+ test "delete cookies" do
+ @response.set_cookie("user_name", :value => "david", :path => "/")
+ @response.set_cookie("login", :value => "foo&bar", :path => "/", :expires => Time.utc(2005, 10, 10,5))
@response.delete_cookie("login")
- status, headers, body = @response.to_a
assert_equal({"user_name" => "david", "login" => nil}, @response.cookies)
end
@@ -157,18 +184,28 @@ class ResponseTest < ActiveSupport::TestCase
test "read charset and content type" do
resp = ActionDispatch::Response.new.tap { |response|
response.charset = 'utf-16'
- response.content_type = Mime::XML
+ response.content_type = Mime[:xml]
response.body = 'Hello'
}
resp.to_a
assert_equal('utf-16', resp.charset)
- assert_equal(Mime::XML, resp.content_type)
+ assert_equal(Mime[:xml], resp.content_type)
assert_equal('application/xml; charset=utf-16', resp.headers['Content-Type'])
end
- test "read content type without charset" do
+ test "read content type with default charset utf-8" do
+ original = ActionDispatch::Response.default_charset
+ begin
+ resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" })
+ assert_equal('utf-8', resp.charset)
+ ensure
+ ActionDispatch::Response.default_charset = original
+ end
+ end
+
+ test "read content type with charset utf-16" do
original = ActionDispatch::Response.default_charset
begin
ActionDispatch::Response.default_charset = 'utf-16'
@@ -187,7 +224,7 @@ class ResponseTest < ActiveSupport::TestCase
'X-Content-Type-Options' => 'nosniff',
'X-XSS-Protection' => '1;'
}
- resp = ActionDispatch::Response.new.tap { |response|
+ resp = ActionDispatch::Response.create.tap { |response|
response.body = 'Hello'
}
resp.to_a
@@ -206,7 +243,7 @@ class ResponseTest < ActiveSupport::TestCase
ActionDispatch::Response.default_headers = {
'X-XX-XXXX' => 'Here is my phone number'
}
- resp = ActionDispatch::Response.new.tap { |response|
+ resp = ActionDispatch::Response.create.tap { |response|
response.body = 'Hello'
}
resp.to_a
@@ -253,6 +290,65 @@ class ResponseTest < ActiveSupport::TestCase
end
end
+class ResponseHeadersTest < ActiveSupport::TestCase
+ def setup
+ @response = ActionDispatch::Response.create
+ @response.set_header 'Foo', '1'
+ end
+
+ test 'has_header?' do
+ assert @response.has_header? 'Foo'
+ assert_not @response.has_header? 'foo'
+ assert_not @response.has_header? nil
+ end
+
+ test 'get_header' do
+ assert_equal '1', @response.get_header('Foo')
+ assert_nil @response.get_header('foo')
+ assert_nil @response.get_header(nil)
+ end
+
+ test 'set_header' do
+ assert_equal '2', @response.set_header('Foo', '2')
+ assert @response.has_header?('Foo')
+ assert_equal '2', @response.get_header('Foo')
+
+ assert_nil @response.set_header('Foo', nil)
+ assert @response.has_header?('Foo')
+ assert_nil @response.get_header('Foo')
+ end
+
+ test 'delete_header' do
+ assert_nil @response.delete_header(nil)
+
+ assert_nil @response.delete_header('foo')
+ assert @response.has_header?('Foo')
+
+ assert_equal '1', @response.delete_header('Foo')
+ assert_not @response.has_header?('Foo')
+ end
+
+ test 'add_header' do
+ # Add a value to an existing header
+ assert_equal '1,2', @response.add_header('Foo', '2')
+ assert_equal '1,2', @response.get_header('Foo')
+
+ # Add nil to an existing header
+ assert_equal '1,2', @response.add_header('Foo', nil)
+ assert_equal '1,2', @response.get_header('Foo')
+
+ # Add nil to a nonexistent header
+ assert_nil @response.add_header('Bar', nil)
+ assert_not @response.has_header?('Bar')
+ assert_nil @response.get_header('Bar')
+
+ # Add a value to a nonexistent header
+ assert_equal '1', @response.add_header('Bar', '1')
+ assert @response.has_header?('Bar')
+ assert_equal '1', @response.get_header('Bar')
+ end
+end
+
class ResponseIntegrationTest < ActionDispatch::IntegrationTest
test "response cache control from railsish app" do
@app = lambda { |env|
@@ -294,7 +390,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
@app = lambda { |env|
ActionDispatch::Response.new.tap { |resp|
resp.charset = 'utf-16'
- resp.content_type = Mime::XML
+ resp.content_type = Mime[:xml]
resp.body = 'Hello'
}.to_a
}
@@ -303,7 +399,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
assert_response :success
assert_equal('utf-16', @response.charset)
- assert_equal(Mime::XML, @response.content_type)
+ assert_equal(Mime[:xml], @response.content_type)
assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type'])
end
@@ -319,7 +415,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
assert_response :success
assert_equal('utf-16', @response.charset)
- assert_equal(Mime::XML, @response.content_type)
+ assert_equal(Mime[:xml], @response.content_type)
assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type'])
end
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
index 3df022c64b..a17d07c40b 100644
--- a/actionpack/test/dispatch/routing/inspector_test.rb
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -12,12 +12,6 @@ module ActionDispatch
class RoutesInspectorTest < ActiveSupport::TestCase
def setup
@set = ActionDispatch::Routing::RouteSet.new
- app = ActiveSupport::OrderedOptions.new
- app.config = ActiveSupport::OrderedOptions.new
- app.config.assets = ActiveSupport::OrderedOptions.new
- app.config.assets.prefix = '/sprockets'
- Rails.stubs(:application).returns(app)
- Rails.stubs(:env).returns("development")
end
def draw(options = {}, &block)
@@ -83,6 +77,17 @@ module ActionDispatch
], output
end
+ def test_articles_inspect_with_multiple_verbs
+ output = draw do
+ match 'articles/:id', to: 'articles#update', via: [:put, :patch]
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " PUT|PATCH /articles/:id(.:format) articles#update"
+ ], output
+ end
+
def test_inspect_shows_custom_assets
output = draw do
get '/custom/assets', :to => 'custom_assets#show'
@@ -313,6 +318,19 @@ module ActionDispatch
assert_equal ["Prefix Verb URI Pattern Controller#Action",
" GET /:controller(/:action) (?-mix:api\\/[^\\/]+)#:action"], output
end
+
+ def test_inspect_routes_shows_resources_route_when_assets_disabled
+ @set = ActionDispatch::Routing::RouteSet.new
+
+ output = draw do
+ get '/cart', to: 'cart#show'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " cart GET /cart(.:format) cart#show"
+ ], output
+ end
end
end
end
diff --git a/actionpack/test/dispatch/routing/ipv6_redirect_test.rb b/actionpack/test/dispatch/routing/ipv6_redirect_test.rb
new file mode 100644
index 0000000000..f1b2e8cfc7
--- /dev/null
+++ b/actionpack/test/dispatch/routing/ipv6_redirect_test.rb
@@ -0,0 +1,45 @@
+require 'abstract_unit'
+
+class IPv6IntegrationTest < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new
+ include Routes.url_helpers
+
+ class ::BadRouteRequestController < ActionController::Base
+ include Routes.url_helpers
+ def index
+ render :text => foo_path
+ end
+
+ def foo
+ redirect_to :action => :index
+ end
+ end
+
+ Routes.draw do
+ get "/", :to => 'bad_route_request#index', :as => :index
+ get "/foo", :to => "bad_route_request#foo", :as => :foo
+ end
+
+ def _routes
+ Routes
+ end
+
+ APP = build_app Routes
+ def app
+ APP
+ end
+
+ test "bad IPv6 redirection" do
+ # def test_simple_redirect
+ request_env = {
+ 'REMOTE_ADDR' => 'fd07:2fa:6cff:2112:225:90ff:fec7:22aa',
+ 'HTTP_HOST' => '[fd07:2fa:6cff:2112:225:90ff:fec7:22aa]:3000',
+ 'SERVER_NAME' => '[fd07:2fa:6cff:2112:225:90ff:fec7:22aa]',
+ 'SERVER_PORT' => 3000 }
+
+ get '/foo', env: request_env
+ assert_response :redirect
+ assert_equal 'http://[fd07:2fa:6cff:2112:225:90ff:fec7:22aa]:3000/', redirect_to_url
+ end
+
+end
diff --git a/actionpack/test/dispatch/routing/route_set_test.rb b/actionpack/test/dispatch/routing/route_set_test.rb
index fe52c50336..9327fe12c6 100644
--- a/actionpack/test/dispatch/routing/route_set_test.rb
+++ b/actionpack/test/dispatch/routing/route_set_test.rb
@@ -17,6 +17,16 @@ module ActionDispatch
@set = RouteSet.new
end
+ test "not being empty when route is added" do
+ assert empty?
+
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_not empty?
+ end
+
test "url helpers are added when route is added" do
draw do
get 'foo', to: SimpleApp.new('foo#index')
@@ -136,6 +146,10 @@ module ActionDispatch
def url_helpers
@set.url_helpers
end
+
+ def empty?
+ @set.empty?
+ end
end
end
end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 55fc160ac8..8972f3e74d 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -1,4 +1,3 @@
-# encoding: UTF-8
require 'erb'
require 'abstract_unit'
require 'controller/fake_controllers'
@@ -167,6 +166,44 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal '/session/reset', reset_session_path
end
+ def test_session_singleton_resource_for_api_app
+ config = ActionDispatch::Routing::RouteSet::Config.new
+ config.api_only = true
+
+ self.class.stub_controllers(config) do |routes|
+ routes.draw do
+ resource :session do
+ get :create
+ post :reset
+ end
+ end
+ @app = RoutedRackApp.new routes
+ end
+
+ get '/session'
+ assert_equal 'sessions#create', @response.body
+ assert_equal '/session', session_path
+
+ post '/session'
+ assert_equal 'sessions#create', @response.body
+
+ put '/session'
+ assert_equal 'sessions#update', @response.body
+
+ delete '/session'
+ assert_equal 'sessions#destroy', @response.body
+
+ post '/session/reset'
+ assert_equal 'sessions#reset', @response.body
+ assert_equal '/session/reset', reset_session_path
+
+ get '/session/new'
+ assert_equal 'Not Found', @response.body
+
+ get '/session/edit'
+ assert_equal 'Not Found', @response.body
+ end
+
def test_session_info_nested_singleton_resource
draw do
resource :session do
@@ -323,9 +360,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
def test_pagemarks
+ tc = self
draw do
scope "pagemark", :controller => "pagemarks", :as => :pagemark do
- get "new", :path => "build"
+ tc.assert_deprecated do
+ get "new", :path => "build"
+ end
post "create", :as => ""
put "update"
get "remove", :action => :destroy, :as => :remove
@@ -509,6 +549,40 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal '/projects/1/edit', edit_project_path(:id => '1')
end
+ def test_projects_for_api_app
+ config = ActionDispatch::Routing::RouteSet::Config.new
+ config.api_only = true
+
+ self.class.stub_controllers(config) do |routes|
+ routes.draw do
+ resources :projects, controller: :project
+ end
+ @app = RoutedRackApp.new routes
+ end
+
+ get '/projects'
+ assert_equal 'project#index', @response.body
+ assert_equal '/projects', projects_path
+
+ post '/projects'
+ assert_equal 'project#create', @response.body
+
+ get '/projects.xml'
+ assert_equal 'project#index', @response.body
+ assert_equal '/projects.xml', projects_path(format: 'xml')
+
+ get '/projects/1'
+ assert_equal 'project#show', @response.body
+ assert_equal '/projects/1', project_path(id: '1')
+
+ get '/projects/1.xml'
+ assert_equal 'project#show', @response.body
+ assert_equal '/projects/1.xml', project_path(id: '1', format: 'xml')
+
+ get '/projects/1/edit'
+ assert_equal 'Not Found', @response.body
+ end
+
def test_projects_with_post_action_and_new_path_on_collection
draw do
resources :projects, :controller => :project do
@@ -3492,12 +3566,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
mount lambda { |env| [200, {}, [env['REQUEST_METHOD']]] }, at: '/'
end
- # TODO: HEAD request should match `get /home` rather than the
+ # HEAD request should match `get /home` rather than the
# lower-precedence Rack app mounted at `/`.
head '/home'
assert_response :ok
- #assert_equal 'test#index', @response.body
- assert_equal 'HEAD', @response.body
+ assert_equal 'test#index', @response.body
# But the Rack app can still respond to its own HEAD requests.
head '/foobar'
@@ -3547,7 +3620,7 @@ private
end
class TestAltApp < ActionDispatch::IntegrationTest
- class AltRequest
+ class AltRequest < ActionDispatch::Request
attr_accessor :path_parameters, :path_info, :script_name
attr_reader :env
@@ -3556,6 +3629,7 @@ class TestAltApp < ActionDispatch::IntegrationTest
@env = env
@path_info = "/"
@script_name = ""
+ super
end
def request_method
@@ -3655,7 +3729,7 @@ class TestNamespaceWithControllerOption < ActionDispatch::IntegrationTest
module ::Admin
class StorageFilesController < ActionController::Base
def index
- render :text => "admin/storage_files#index"
+ render plain: "admin/storage_files#index"
end
end
end
@@ -3750,7 +3824,7 @@ class TestDefaultScope < ActionDispatch::IntegrationTest
module ::Blog
class PostsController < ActionController::Base
def index
- render :text => "blog/posts#index"
+ render plain: "blog/posts#index"
end
end
end
@@ -4090,13 +4164,13 @@ end
class TestNamedRouteUrlHelpers < ActionDispatch::IntegrationTest
class CategoriesController < ActionController::Base
def show
- render :text => "categories#show"
+ render plain: "categories#show"
end
end
class ProductsController < ActionController::Base
def show
- render :text => "products#show"
+ render plain: "products#show"
end
end
@@ -4115,11 +4189,11 @@ class TestNamedRouteUrlHelpers < ActionDispatch::IntegrationTest
include Routes.url_helpers
test "url helpers do not ignore nil parameters when using non-optimized routes" do
- Routes.stubs(:optimize_routes_generation?).returns(false)
-
- get "/categories/1"
- assert_response :success
- assert_raises(ActionController::UrlGenerationError) { product_path(nil) }
+ Routes.stub :optimize_routes_generation?, false do
+ get "/categories/1"
+ assert_response :success
+ assert_raises(ActionController::UrlGenerationError) { product_path(nil) }
+ end
end
end
@@ -4191,7 +4265,7 @@ end
class TestInvalidUrls < ActionDispatch::IntegrationTest
class FooController < ActionController::Base
def show
- render :text => "foo#show"
+ render plain: "foo#show"
end
end
@@ -4476,12 +4550,25 @@ class TestUrlGenerationErrors < ActionDispatch::IntegrationTest
error = assert_raises(ActionController::UrlGenerationError, message){ product_path(id: nil) }
assert_equal message, error.message
end
+
+ test "url helpers raise message with mixed parameters when generation fails " do
+ url, missing = { action: 'show', controller: 'products', id: nil, "id"=>"url-tested"}, [:id]
+ message = "No route matches #{url.inspect} missing required keys: #{missing.inspect}"
+
+ # Optimized url helper
+ error = assert_raises(ActionController::UrlGenerationError){ product_path(nil, 'id'=>'url-tested') }
+ assert_equal message, error.message
+
+ # Non-optimized url helper
+ error = assert_raises(ActionController::UrlGenerationError, message){ product_path(id: nil, 'id'=>'url-tested') }
+ assert_equal message, error.message
+ end
end
class TestDefaultUrlOptions < ActionDispatch::IntegrationTest
class PostsController < ActionController::Base
def archive
- render :text => "posts#archive"
+ render plain: "posts#archive"
end
end
diff --git a/actionpack/test/dispatch/session/abstract_store_test.rb b/actionpack/test/dispatch/session/abstract_store_test.rb
index fe1a7b4f86..d38d1bbce6 100644
--- a/actionpack/test/dispatch/session/abstract_store_test.rb
+++ b/actionpack/test/dispatch/session/abstract_store_test.rb
@@ -10,13 +10,13 @@ module ActionDispatch
super
end
- def get_session(env, sid)
+ def find_session(env, sid)
sid ||= 1
session = @sessions[sid] ||= {}
[sid, session]
end
- def set_session(env, sid, session, options)
+ def write_session(env, sid, session, options)
@sessions[sid] = session
end
end
@@ -27,7 +27,7 @@ module ActionDispatch
as.call(env)
assert @env
- assert Request::Session.find @env
+ assert Request::Session.find ActionDispatch::Request.new @env
end
def test_new_session_object_is_merged_with_old
@@ -36,11 +36,11 @@ module ActionDispatch
as.call(env)
assert @env
- session = Request::Session.find @env
+ session = Request::Session.find ActionDispatch::Request.new @env
session['foo'] = 'bar'
as.call(@env)
- session1 = Request::Session.find @env
+ session1 = Request::Session.find ActionDispatch::Request.new @env
assert_not_equal session, session1
assert_equal session.to_hash, session1.to_hash
diff --git a/actionpack/test/dispatch/session/cache_store_test.rb b/actionpack/test/dispatch/session/cache_store_test.rb
index 22a46b0930..dbb996973d 100644
--- a/actionpack/test/dispatch/session/cache_store_test.rb
+++ b/actionpack/test/dispatch/session/cache_store_test.rb
@@ -18,11 +18,11 @@ class CacheStoreTest < ActionDispatch::IntegrationTest
end
def get_session_value
- render :text => "foo: #{session[:foo].inspect}"
+ render plain: "foo: #{session[:foo].inspect}"
end
def get_session_id
- render :text => "#{request.session.id}"
+ render plain: "#{request.session.id}"
end
def call_reset_session
@@ -170,7 +170,7 @@ class CacheStoreTest < ActionDispatch::IntegrationTest
@app = self.class.build_app(set) do |middleware|
@cache = ActiveSupport::Cache::MemoryStore.new
middleware.use ActionDispatch::Session::CacheStore, :key => '_session_id', :cache => @cache
- middleware.delete "ActionDispatch::ShowExceptions"
+ middleware.delete ActionDispatch::ShowExceptions
end
yield
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index e7f4235de8..f07e215e3a 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -16,25 +16,25 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
end
def persistent_session_id
- render :text => session[:session_id]
+ render plain: session[:session_id]
end
def set_session_value
session[:foo] = "bar"
- render :text => Rack::Utils.escape(Verifier.generate(session.to_hash))
+ render plain: Rack::Utils.escape(Verifier.generate(session.to_hash))
end
def get_session_value
- render :text => "foo: #{session[:foo].inspect}"
+ render plain: "foo: #{session[:foo].inspect}"
end
def get_session_id
- render :text => "id: #{request.session.id}"
+ render plain: "id: #{request.session.id}"
end
def get_class_after_reset_session
reset_session
- render :text => "class: #{session.class}"
+ render plain: "class: #{session.class}"
end
def call_session_clear
@@ -274,28 +274,32 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
with_test_route_set(:expire_after => 5.hours) do
# First request accesses the session
time = Time.local(2008, 4, 24)
- Time.stubs(:now).returns(time)
- expected_expiry = (time + 5.hours).gmtime.strftime("%a, %d %b %Y %H:%M:%S -0000")
+ cookie_body = nil
- cookies[SessionKey] = SignedBar
+ Time.stub :now, time do
+ expected_expiry = (time + 5.hours).gmtime.strftime("%a, %d %b %Y %H:%M:%S -0000")
- get '/set_session_value'
- assert_response :success
+ cookies[SessionKey] = SignedBar
- cookie_body = response.body
- assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
- headers['Set-Cookie']
+ get '/set_session_value'
+ assert_response :success
+
+ cookie_body = response.body
+ assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
+ headers['Set-Cookie']
+ end
# Second request does not access the session
time = Time.local(2008, 4, 25)
- Time.stubs(:now).returns(time)
- expected_expiry = (time + 5.hours).gmtime.strftime("%a, %d %b %Y %H:%M:%S -0000")
+ Time.stub :now, time do
+ expected_expiry = (time + 5.hours).gmtime.strftime("%a, %d %b %Y %H:%M:%S -0000")
- get '/no_session_access'
- assert_response :success
+ get '/no_session_access'
+ assert_response :success
- assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
- headers['Set-Cookie']
+ assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
+ headers['Set-Cookie']
+ end
end
end
@@ -348,7 +352,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
@app = self.class.build_app(set) do |middleware|
middleware.use ActionDispatch::Session::CookieStore, options
- middleware.delete "ActionDispatch::ShowExceptions"
+ middleware.delete ActionDispatch::ShowExceptions
end
yield
diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb
index 9a5d5131c0..3fed9bad4f 100644
--- a/actionpack/test/dispatch/session/mem_cache_store_test.rb
+++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb
@@ -19,11 +19,11 @@ class MemCacheStoreTest < ActionDispatch::IntegrationTest
end
def get_session_value
- render :text => "foo: #{session[:foo].inspect}"
+ render plain: "foo: #{session[:foo].inspect}"
end
def get_session_id
- render :text => "#{request.session.id}"
+ render plain: "#{request.session.id}"
end
def call_reset_session
@@ -192,7 +192,7 @@ class MemCacheStoreTest < ActionDispatch::IntegrationTest
@app = self.class.build_app(set) do |middleware|
middleware.use ActionDispatch::Session::MemCacheStore, :key => '_session_id', :namespace => "mem_cache_store_test:#{SecureRandom.hex(10)}"
- middleware.delete "ActionDispatch::ShowExceptions"
+ middleware.delete ActionDispatch::ShowExceptions
end
yield
diff --git a/actionpack/test/dispatch/session/test_session_test.rb b/actionpack/test/dispatch/session/test_session_test.rb
index d30461a623..3e61d123e3 100644
--- a/actionpack/test/dispatch/session/test_session_test.rb
+++ b/actionpack/test/dispatch/session/test_session_test.rb
@@ -40,4 +40,24 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase
assert_equal %w(one two), session.keys
assert_equal %w(1 2), session.values
end
+
+ def test_fetch_returns_default
+ session = ActionController::TestSession.new(one: '1')
+ assert_equal('2', session.fetch(:two, '2'))
+ end
+
+ def test_fetch_on_symbol_returns_value
+ session = ActionController::TestSession.new(one: '1')
+ assert_equal('1', session.fetch(:one))
+ end
+
+ def test_fetch_on_string_returns_value
+ session = ActionController::TestSession.new(one: '1')
+ assert_equal('1', session.fetch('one'))
+ end
+
+ def test_fetch_returns_block_value
+ session = ActionController::TestSession.new(one: '1')
+ assert_equal(2, session.fetch('2') { |key| key.to_i })
+ end
end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index 72eaa916bc..ffdf775836 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -9,13 +9,21 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
when "/not_found"
raise AbstractController::ActionNotFound
when "/bad_params"
- raise ActionDispatch::ParamsParser::ParseError.new("", StandardError.new)
+ begin
+ raise StandardError.new
+ rescue
+ raise ActionDispatch::ParamsParser::ParseError
+ end
when "/method_not_allowed"
- raise ActionController::MethodNotAllowed
+ raise ActionController::MethodNotAllowed, 'PUT'
when "/unknown_http_method"
raise ActionController::UnknownHttpMethod
when "/not_found_original_exception"
- raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new)
+ begin
+ raise AbstractController::ActionNotFound.new
+ rescue
+ raise ActionView::Template::Error.new('template')
+ end
else
raise "puke!"
end
@@ -93,13 +101,13 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_kind_of AbstractController::ActionNotFound, env["action_dispatch.exception"]
assert_equal "/404", env["PATH_INFO"]
assert_equal "/not_found_original_exception", env["action_dispatch.original_path"]
- [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED"]]
end
@app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
get "/not_found_original_exception", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
- assert_equal "YOU FAILED BRO", body
+ assert_equal "YOU FAILED", body
end
test "returns an empty response if custom exceptions app returns X-Cascade pass" do
diff --git a/actionpack/test/dispatch/ssl_test.rb b/actionpack/test/dispatch/ssl_test.rb
index 7ced41bc2e..7a5b8393dc 100644
--- a/actionpack/test/dispatch/ssl_test.rb
+++ b/actionpack/test/dispatch/ssl_test.rb
@@ -1,219 +1,199 @@
require 'abstract_unit'
class SSLTest < ActionDispatch::IntegrationTest
- def default_app
- lambda { |env|
- headers = {'Content-Type' => "text/html"}
- headers['Set-Cookie'] = "id=1; path=/\ntoken=abc; path=/; secure; HttpOnly"
- [200, headers, ["OK"]]
+ HEADERS = Rack::Utils::HeaderHash.new 'Content-Type' => 'text/html'
+
+ attr_accessor :app
+
+ def build_app(headers: {}, ssl_options: {})
+ headers = HEADERS.merge(headers)
+ ActionDispatch::SSL.new lambda { |env| [200, headers, []] }, ssl_options
+ end
+end
+
+class RedirectSSLTest < SSLTest
+ def assert_not_redirected(url, headers: {})
+ self.app = build_app
+ get url, headers: headers
+ assert_response :ok
+ end
+
+ def assert_redirected(host: nil, port: nil, status: 301, body: [],
+ deprecated_host: nil, deprecated_port: nil,
+ from: 'http://a/b?c=d', to: from.sub('http', 'https'))
+
+ self.app = build_app ssl_options: {
+ redirect: { host: host, port: port, status: status, body: body },
+ host: deprecated_host, port: deprecated_port
}
+
+ get from
+ assert_response status
+ assert_redirected_to to
+ assert_equal body.join, @response.body
end
- def app
- @app ||= ActionDispatch::SSL.new(default_app)
+ test 'https is not redirected' do
+ assert_not_redirected 'https://example.org'
end
- attr_writer :app
- def test_allows_https_url
- get "https://example.org/path?key=value"
- assert_response :success
+ test 'proxied https is not redirected' do
+ assert_not_redirected 'http://example.org', headers: { 'HTTP_X_FORWARDED_PROTO' => 'https' }
end
- def test_allows_https_proxy_header_url
- get "http://example.org/", headers: { 'HTTP_X_FORWARDED_PROTO' => "https" }
- assert_response :success
+ test 'http is redirected to https' do
+ assert_redirected
end
- def test_redirects_http_to_https
- get "http://example.org/path?key=value"
- assert_response :redirect
- assert_equal "https://example.org/path?key=value",
- response.headers['Location']
+ test 'redirect with non-301 status' do
+ assert_redirected status: 307
end
- def test_hsts_header_by_default
- get "https://example.org/"
- assert_equal "max-age=31536000",
- response.headers['Strict-Transport-Security']
+ test 'redirect with custom body' do
+ assert_redirected body: ['foo']
end
- def test_no_hsts_with_insecure_connection
- get "http://example.org/"
- assert_not response.headers['Strict-Transport-Security']
+ test 'redirect to specific host' do
+ assert_redirected host: 'ssl', to: 'https://ssl/b?c=d'
end
- def test_hsts_header
- self.app = ActionDispatch::SSL.new(default_app, :hsts => true)
- get "https://example.org/"
- assert_equal "max-age=31536000",
- response.headers['Strict-Transport-Security']
+ test 'redirect to default port' do
+ assert_redirected port: 443
end
- def test_disable_hsts_header
- self.app = ActionDispatch::SSL.new(default_app, :hsts => false)
- get "https://example.org/"
- assert_not response.headers['Strict-Transport-Security']
+ test 'redirect to non-default port' do
+ assert_redirected port: 8443, to: 'https://a:8443/b?c=d'
end
- def test_hsts_expires
- self.app = ActionDispatch::SSL.new(default_app, :hsts => { :expires => 500 })
- get "https://example.org/"
- assert_equal "max-age=500",
- response.headers['Strict-Transport-Security']
+ test 'redirect to different host and non-default port' do
+ assert_redirected host: 'ssl', port: 8443, to: 'https://ssl:8443/b?c=d'
end
- def test_hsts_expires_with_duration
- self.app = ActionDispatch::SSL.new(default_app, :hsts => { :expires => 1.year })
- get "https://example.org/"
- assert_equal "max-age=31557600",
- response.headers['Strict-Transport-Security']
+ test 'redirect to different host including port' do
+ assert_redirected host: 'ssl:443', to: 'https://ssl:443/b?c=d'
end
- def test_hsts_include_subdomains
- self.app = ActionDispatch::SSL.new(default_app, :hsts => { :subdomains => true })
- get "https://example.org/"
- assert_equal "max-age=31536000; includeSubDomains",
- response.headers['Strict-Transport-Security']
+ test ':host is deprecated, moved within redirect: { host: … }' do
+ assert_deprecated do
+ assert_redirected deprecated_host: 'foo', to: 'https://foo/b?c=d'
+ end
end
- def test_flag_cookies_as_secure
- get "https://example.org/"
- assert_equal ["id=1; path=/; secure", "token=abc; path=/; secure; HttpOnly" ],
- response.headers['Set-Cookie'].split("\n")
+ test ':port is deprecated, moved within redirect: { port: … }' do
+ assert_deprecated do
+ assert_redirected deprecated_port: 1, to: 'https://a:1/b?c=d'
+ end
end
+end
- def test_flag_cookies_as_secure_at_end_of_line
- self.app = ActionDispatch::SSL.new(lambda { |env|
- headers = {
- 'Content-Type' => "text/html",
- 'Set-Cookie' => "problem=def; path=/; HttpOnly; secure"
- }
- [200, headers, ["OK"]]
- })
+class StrictTransportSecurityTest < SSLTest
+ EXPECTED = 'max-age=15552000'
- get "https://example.org/"
- assert_equal ["problem=def; path=/; HttpOnly; secure"],
- response.headers['Set-Cookie'].split("\n")
+ def assert_hsts(expected, url: 'https://example.org', hsts: {}, headers: {})
+ self.app = build_app ssl_options: { hsts: hsts }, headers: headers
+ get url
+ assert_equal expected, response.headers['Strict-Transport-Security']
end
- def test_flag_cookies_as_secure_with_more_spaces_before
- self.app = ActionDispatch::SSL.new(lambda { |env|
- headers = {
- 'Content-Type' => "text/html",
- 'Set-Cookie' => "problem=def; path=/; HttpOnly; secure"
- }
- [200, headers, ["OK"]]
- })
+ test 'enabled by default' do
+ assert_hsts EXPECTED
+ end
- get "https://example.org/"
- assert_equal ["problem=def; path=/; HttpOnly; secure"],
- response.headers['Set-Cookie'].split("\n")
+ test 'not sent with http:// responses' do
+ assert_hsts nil, url: 'http://example.org'
end
- def test_flag_cookies_as_secure_with_more_spaces_after
- self.app = ActionDispatch::SSL.new(lambda { |env|
- headers = {
- 'Content-Type' => "text/html",
- 'Set-Cookie' => "problem=def; path=/; secure; HttpOnly"
- }
- [200, headers, ["OK"]]
- })
+ test 'defers to app-provided header' do
+ assert_hsts 'app-provided', headers: { 'Strict-Transport-Security' => 'app-provided' }
+ end
- get "https://example.org/"
- assert_equal ["problem=def; path=/; secure; HttpOnly"],
- response.headers['Set-Cookie'].split("\n")
+ test 'hsts: true enables default settings' do
+ assert_hsts EXPECTED, hsts: true
end
+ test 'hsts: false sets max-age to zero, clearing browser HSTS settings' do
+ assert_hsts 'max-age=0', hsts: false
+ end
- def test_flag_cookies_as_secure_with_has_not_spaces_before
- self.app = ActionDispatch::SSL.new(lambda { |env|
- headers = {
- 'Content-Type' => "text/html",
- 'Set-Cookie' => "problem=def; path=/;secure; HttpOnly"
- }
- [200, headers, ["OK"]]
- })
+ test ':expires sets max-age' do
+ assert_hsts 'max-age=500', hsts: { expires: 500 }
+ end
- get "https://example.org/"
- assert_equal ["problem=def; path=/;secure; HttpOnly"],
- response.headers['Set-Cookie'].split("\n")
+ test ':expires supports AS::Duration arguments' do
+ assert_hsts 'max-age=31557600', hsts: { expires: 1.year }
end
- def test_flag_cookies_as_secure_with_has_not_spaces_after
- self.app = ActionDispatch::SSL.new(lambda { |env|
- headers = {
- 'Content-Type' => "text/html",
- 'Set-Cookie' => "problem=def; path=/; secure;HttpOnly"
- }
- [200, headers, ["OK"]]
- })
+ test 'include subdomains' do
+ assert_hsts "#{EXPECTED}; includeSubDomains", hsts: { subdomains: true }
+ end
- get "https://example.org/"
- assert_equal ["problem=def; path=/; secure;HttpOnly"],
- response.headers['Set-Cookie'].split("\n")
+ test 'exclude subdomains' do
+ assert_hsts EXPECTED, hsts: { subdomains: false }
end
- def test_flag_cookies_as_secure_with_ignore_case
- self.app = ActionDispatch::SSL.new(lambda { |env|
- headers = {
- 'Content-Type' => "text/html",
- 'Set-Cookie' => "problem=def; path=/; Secure; HttpOnly"
- }
- [200, headers, ["OK"]]
- })
+ test 'opt in to browser preload lists' do
+ assert_hsts "#{EXPECTED}; preload", hsts: { preload: true }
+ end
- get "https://example.org/"
- assert_equal ["problem=def; path=/; Secure; HttpOnly"],
- response.headers['Set-Cookie'].split("\n")
+ test 'opt out of browser preload lists' do
+ assert_hsts EXPECTED, hsts: { preload: false }
end
+end
- def test_no_cookies
- self.app = ActionDispatch::SSL.new(lambda { |env|
- [200, {'Content-Type' => "text/html"}, ["OK"]]
- })
- get "https://example.org/"
- assert !response.headers['Set-Cookie']
+class SecureCookiesTest < SSLTest
+ DEFAULT = %(id=1; path=/\ntoken=abc; path=/; secure; HttpOnly)
+
+ def get(**options)
+ self.app = build_app(**options)
+ super 'https://example.org'
end
- def test_redirect_to_host
- self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org")
- get "http://example.org/path?key=value"
- assert_equal "https://ssl.example.org/path?key=value",
- response.headers['Location']
+ def assert_cookies(*expected)
+ assert_equal expected, response.headers['Set-Cookie'].split("\n")
end
- def test_redirect_to_port
- self.app = ActionDispatch::SSL.new(default_app, :port => 8443)
- get "http://example.org/path?key=value"
- assert_equal "https://example.org:8443/path?key=value",
- response.headers['Location']
+ def test_flag_cookies_as_secure
+ get headers: { 'Set-Cookie' => DEFAULT }
+ assert_cookies 'id=1; path=/; secure', 'token=abc; path=/; secure; HttpOnly'
end
- def test_redirect_to_host_and_port
- self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org", :port => 8443)
- get "http://example.org/path?key=value"
- assert_equal "https://ssl.example.org:8443/path?key=value",
- response.headers['Location']
+ def test_flag_cookies_as_secure_at_end_of_line
+ get headers: { 'Set-Cookie' => 'problem=def; path=/; HttpOnly; secure' }
+ assert_cookies 'problem=def; path=/; HttpOnly; secure'
end
- def test_redirect_to_host_with_port
- self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org:443")
- get "http://example.org/path?key=value"
- assert_equal "https://ssl.example.org:443/path?key=value",
- response.headers['Location']
+ def test_flag_cookies_as_secure_with_more_spaces_before
+ get headers: { 'Set-Cookie' => 'problem=def; path=/; HttpOnly; secure' }
+ assert_cookies 'problem=def; path=/; HttpOnly; secure'
+ end
+
+ def test_flag_cookies_as_secure_with_more_spaces_after
+ get headers: { 'Set-Cookie' => 'problem=def; path=/; secure; HttpOnly' }
+ assert_cookies 'problem=def; path=/; secure; HttpOnly'
end
- def test_redirect_to_secure_host_when_on_subdomain
- self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org")
- get "http://ssl.example.org/path?key=value"
- assert_equal "https://ssl.example.org/path?key=value",
- response.headers['Location']
+ def test_flag_cookies_as_secure_with_has_not_spaces_before
+ get headers: { 'Set-Cookie' => 'problem=def; path=/;secure; HttpOnly' }
+ assert_cookies 'problem=def; path=/;secure; HttpOnly'
+ end
+
+ def test_flag_cookies_as_secure_with_has_not_spaces_after
+ get headers: { 'Set-Cookie' => 'problem=def; path=/; secure;HttpOnly' }
+ assert_cookies 'problem=def; path=/; secure;HttpOnly'
+ end
+
+ def test_flag_cookies_as_secure_with_ignore_case
+ get headers: { 'Set-Cookie' => 'problem=def; path=/; Secure; HttpOnly' }
+ assert_cookies 'problem=def; path=/; Secure; HttpOnly'
+ end
+
+ def test_no_cookies
+ get
+ assert_nil response.headers['Set-Cookie']
end
- def test_redirect_to_secure_subdomain_when_on_deep_subdomain
- self.app = ActionDispatch::SSL.new(default_app, :host => "example.co.uk")
- get "http://double.rainbow.what.does.it.mean.example.co.uk/path?key=value"
- assert_equal "https://example.co.uk/path?key=value",
- response.headers['Location']
+ def test_keeps_original_headers_behavior
+ get headers: { 'Connection' => %w[close] }
+ assert_equal 'close', response.headers['Connection']
end
end
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index 288a2084f6..1da57ab50b 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -2,6 +2,24 @@ require 'abstract_unit'
require 'zlib'
module StaticTests
+ DummyApp = lambda { |env|
+ [200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
+ }
+
+ def setup
+ silence_warnings do
+ @default_internal_encoding = Encoding.default_internal
+ @default_external_encoding = Encoding.default_external
+ end
+ end
+
+ def teardown
+ silence_warnings do
+ Encoding.default_internal = @default_internal_encoding
+ Encoding.default_external = @default_external_encoding
+ end
+ end
+
def test_serves_dynamic_content
assert_equal "Hello, World!", get("/nofile").body
end
@@ -10,8 +28,24 @@ module StaticTests
assert_equal "Hello, World!", get("/doorkeeper%E3E4").body
end
+ def test_handles_urls_with_ascii_8bit
+ assert_equal "Hello, World!", get("/doorkeeper%E3E4".force_encoding('ASCII-8BIT')).body
+ end
+
+ def test_handles_urls_with_ascii_8bit_on_win_31j
+ silence_warnings do
+ Encoding.default_internal = "Windows-31J"
+ Encoding.default_external = "Windows-31J"
+ end
+ assert_equal "Hello, World!", get("/doorkeeper%E3E4".force_encoding('ASCII-8BIT')).body
+ end
+
def test_sets_cache_control
- response = get("/index.html")
+ app = assert_deprecated do
+ ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
+ end
+ response = Rack::MockRequest.new(app).request("GET", "/index.html")
+
assert_html "/index.html", response
assert_equal "public, max-age=60", response.headers["Cache-Control"]
end
@@ -31,6 +65,7 @@ module StaticTests
def test_serves_static_index_file_in_directory
assert_html "/foo/index.html", get("/foo/index.html")
+ assert_html "/foo/index.html", get("/foo/index")
assert_html "/foo/index.html", get("/foo/")
assert_html "/foo/index.html", get("/foo")
end
@@ -40,8 +75,6 @@ module StaticTests
end
def test_served_static_file_with_non_english_filename
- jruby_skip "Stop skipping if following bug gets fixed: " \
- "http://jira.codehaus.org/browse/JRUBY-7192"
assert_html "means hello in Japanese\n", get("/foo/#{Rack::Utils.escape("こんにちは.html")}")
end
@@ -129,7 +162,7 @@ module StaticTests
def test_does_not_modify_path_info
file_name = "/gzip/application-a71b3024f80aea3181c09774ca17e712.js"
- env = {'PATH_INFO' => file_name, 'HTTP_ACCEPT_ENCODING' => 'gzip'}
+ env = {'PATH_INFO' => file_name, 'HTTP_ACCEPT_ENCODING' => 'gzip', "REQUEST_METHOD" => 'POST'}
@app.call(env)
assert_equal file_name, env['PATH_INFO']
end
@@ -153,6 +186,21 @@ module StaticTests
assert_equal nil, response.headers['Vary']
end
+ def test_serves_files_with_headers
+ headers = {
+ "Access-Control-Allow-Origin" => 'http://rubyonrails.org',
+ "Cache-Control" => 'public, max-age=60',
+ "X-Custom-Header" => "I'm a teapot"
+ }
+
+ app = ActionDispatch::Static.new(DummyApp, @root, headers: headers)
+ response = Rack::MockRequest.new(app).request("GET", "/foo/bar.html")
+
+ assert_equal 'http://rubyonrails.org', response.headers["Access-Control-Allow-Origin"]
+ assert_equal 'public, max-age=60', response.headers["Cache-Control"]
+ assert_equal "I'm a teapot", response.headers["X-Custom-Header"]
+ end
+
# Windows doesn't allow \ / : * ? " < > | in filenames
unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
def test_serves_static_file_with_colon
@@ -203,13 +251,10 @@ module StaticTests
end
class StaticTest < ActiveSupport::TestCase
- DummyApp = lambda { |env|
- [200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
- }
-
def setup
+ super
@root = "#{FIXTURE_LOAD_PATH}/public"
- @app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
+ @app = ActionDispatch::Static.new(DummyApp, @root, headers: {'Cache-Control' => "public, max-age=60"})
end
def public_path
@@ -233,12 +278,26 @@ class StaticTest < ActiveSupport::TestCase
}
assert_equal(DummyApp.call(nil), @app.call(env))
end
+
+ def test_non_default_static_index
+ @app = ActionDispatch::Static.new(DummyApp, @root, index: "other-index")
+ assert_html "/other-index.html", get("/other-index.html")
+ assert_html "/other-index.html", get("/other-index")
+ assert_html "/other-index.html", get("/")
+ assert_html "/other-index.html", get("")
+ assert_html "/foo/other-index.html", get("/foo/other-index.html")
+ assert_html "/foo/other-index.html", get("/foo/other-index")
+ assert_html "/foo/other-index.html", get("/foo/")
+ assert_html "/foo/other-index.html", get("/foo")
+ end
+
end
class StaticEncodingTest < StaticTest
def setup
+ super
@root = "#{FIXTURE_LOAD_PATH}/公共"
- @app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
+ @app = ActionDispatch::Static.new(DummyApp, @root, headers: {'Cache-Control' => "public, max-age=60"})
end
def public_path
diff --git a/actionpack/test/dispatch/template_assertions_test.rb b/actionpack/test/dispatch/template_assertions_test.rb
deleted file mode 100644
index 7278754b49..0000000000
--- a/actionpack/test/dispatch/template_assertions_test.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-require 'abstract_unit'
-
-class AssertTemplateController < ActionController::Base
- def render_with_partial
- render partial: 'test/partial'
- end
-
- def render_with_template
- render 'test/hello_world'
- end
-
- def render_with_layout
- @variable_for_layout = 'hello'
- render 'test/hello_world', layout: "layouts/standard"
- end
-
- def render_with_file
- render file: 'README.rdoc'
- end
-
- def render_nothing
- head :ok
- end
-end
-
-class AssertTemplateControllerTest < ActionDispatch::IntegrationTest
- def test_template_reset_between_requests
- get '/assert_template/render_with_template'
- assert_template 'test/hello_world'
-
- get '/assert_template/render_nothing'
- assert_template nil
- end
-
- def test_partial_reset_between_requests
- get '/assert_template/render_with_partial'
- assert_template partial: 'test/_partial'
-
- get '/assert_template/render_nothing'
- assert_template partial: nil
- end
-
- def test_layout_reset_between_requests
- get '/assert_template/render_with_layout'
- assert_template layout: 'layouts/standard'
-
- get '/assert_template/render_nothing'
- assert_template layout: nil
- end
-
- def test_file_reset_between_requests
- get '/assert_template/render_with_file'
- assert_template file: 'README.rdoc'
-
- get '/assert_template/render_nothing'
- assert_template file: nil
- end
-
- def test_template_reset_between_requests_when_opening_a_session
- open_session do |session|
- session.get '/assert_template/render_with_template'
- session.assert_template 'test/hello_world'
-
- session.get '/assert_template/render_nothing'
- session.assert_template nil
- end
- end
-
- def test_partial_reset_between_requests_when_opening_a_session
- open_session do |session|
- session.get '/assert_template/render_with_partial'
- session.assert_template partial: 'test/_partial'
-
- session.get '/assert_template/render_nothing'
- session.assert_template partial: nil
- end
- end
-
- def test_layout_reset_between_requests_when_opening_a_session
- open_session do |session|
- session.get '/assert_template/render_with_layout'
- session.assert_template layout: 'layouts/standard'
-
- session.get '/assert_template/render_nothing'
- session.assert_template layout: nil
- end
- end
-
- def test_file_reset_between_requests_when_opening_a_session
- open_session do |session|
- session.get '/assert_template/render_with_file'
- session.assert_template file: 'README.rdoc'
-
- session.get '/assert_template/render_nothing'
- session.assert_template file: nil
- end
- end
-
- def test_assigns_do_not_reset_template_assertion
- get '/assert_template/render_with_layout'
- assert_equal 'hello', assigns(:variable_for_layout)
- assert_template layout: 'layouts/standard'
- end
-
- def test_cookies_do_not_reset_template_assertion
- get '/assert_template/render_with_layout'
- cookies
- assert_template layout: 'layouts/standard'
- end
-end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index cc35d4594e..51c469a61a 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -2,7 +2,7 @@ require 'abstract_unit'
class TestRequestTest < ActiveSupport::TestCase
test "sane defaults" do
- env = ActionDispatch::TestRequest.new.env
+ env = ActionDispatch::TestRequest.create.env
assert_equal "GET", env.delete("REQUEST_METHOD")
assert_equal "off", env.delete("HTTPS")
@@ -24,12 +24,10 @@ class TestRequestTest < ActiveSupport::TestCase
assert_equal true, env.delete("rack.multithread")
assert_equal true, env.delete("rack.multiprocess")
assert_equal false, env.delete("rack.run_once")
-
- assert env.empty?, env.inspect
end
test "cookie jar" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal({}, req.cookies)
assert_equal nil, req.env["HTTP_COOKIE"]
@@ -55,40 +53,38 @@ class TestRequestTest < ActiveSupport::TestCase
assert_cookies({"user_name" => "david"}, req.cookie_jar)
end
- test "does not complain when Rails.application is nil" do
- Rails.stubs(:application).returns(nil)
- req = ActionDispatch::TestRequest.new
-
+ test "does not complain when there is no application config" do
+ req = ActionDispatch::TestRequest.create({})
assert_equal false, req.env.empty?
end
test "default remote address is 0.0.0.0" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal '0.0.0.0', req.remote_addr
end
test "allows remote address to be overridden" do
- req = ActionDispatch::TestRequest.new('REMOTE_ADDR' => '127.0.0.1')
+ req = ActionDispatch::TestRequest.create('REMOTE_ADDR' => '127.0.0.1')
assert_equal '127.0.0.1', req.remote_addr
end
test "default host is test.host" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal 'test.host', req.host
end
test "allows host to be overridden" do
- req = ActionDispatch::TestRequest.new('HTTP_HOST' => 'www.example.com')
+ req = ActionDispatch::TestRequest.create('HTTP_HOST' => 'www.example.com')
assert_equal 'www.example.com', req.host
end
test "default user agent is 'Rails Testing'" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal 'Rails Testing', req.user_agent
end
test "allows user agent to be overridden" do
- req = ActionDispatch::TestRequest.new('HTTP_USER_AGENT' => 'GoogleBot')
+ req = ActionDispatch::TestRequest.create('HTTP_USER_AGENT' => 'GoogleBot')
assert_equal 'GoogleBot', req.user_agent
end
diff --git a/actionpack/test/dispatch/test_response_test.rb b/actionpack/test/dispatch/test_response_test.rb
index dc17668def..a4f9d56a6a 100644
--- a/actionpack/test/dispatch/test_response_test.rb
+++ b/actionpack/test/dispatch/test_response_test.rb
@@ -11,10 +11,9 @@ class TestResponseTest < ActiveSupport::TestCase
end
test "helpers" do
- assert_response_code_range 200..299, :success?
- assert_response_code_range [404], :missing?
- assert_response_code_range 300..399, :redirect?
- assert_response_code_range 500..599, :error?
+ assert_response_code_range 200..299, :successful?
+ assert_response_code_range [404], :not_found?
+ assert_response_code_range 300..399, :redirection?
assert_response_code_range 500..599, :server_error?
assert_response_code_range 400..499, :client_error?
end
diff --git a/actionpack/test/dispatch/url_generation_test.rb b/actionpack/test/dispatch/url_generation_test.rb
index ce1e1d0a6a..fd4ede4d1b 100644
--- a/actionpack/test/dispatch/url_generation_test.rb
+++ b/actionpack/test/dispatch/url_generation_test.rb
@@ -8,7 +8,7 @@ module TestUrlGeneration
class ::MyRouteGeneratingController < ActionController::Base
include Routes.url_helpers
def index
- render :text => foo_path
+ render plain: foo_path
end
end
diff --git a/actionpack/test/fixtures/customers/_commented_customer.html.erb b/actionpack/test/fixtures/customers/_commented_customer.html.erb
index d5f6e3b491..8cc9c1ec13 100644
--- a/actionpack/test/fixtures/customers/_commented_customer.html.erb
+++ b/actionpack/test/fixtures/customers/_commented_customer.html.erb
@@ -1,4 +1,5 @@
<%# I'm a comment %>
<% cache customer do %>
+ <% controller.partial_rendered_times += 1 %>
<%= customer.name %>, <%= customer.id %>
<% end %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/customers/_customer.html.erb b/actionpack/test/fixtures/customers/_customer.html.erb
index 67e9f6d411..5105090d4b 100644
--- a/actionpack/test/fixtures/customers/_customer.html.erb
+++ b/actionpack/test/fixtures/customers/_customer.html.erb
@@ -1,3 +1,4 @@
<% cache customer do %>
+ <% controller.partial_rendered_times += 1 %>
<%= customer.name %>, <%= customer.id %>
<% end %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/standard.html.erb b/actionpack/test/fixtures/layouts/standard.html.erb
index 5e6c24fe39..48882dca35 100644
--- a/actionpack/test/fixtures/layouts/standard.html.erb
+++ b/actionpack/test/fixtures/layouts/standard.html.erb
@@ -1 +1 @@
-<html><%= yield %><%= @variable_for_layout %></html> \ No newline at end of file
+<html><%= yield %><%= @variable_for_layout %></html>
diff --git a/actionpack/test/fixtures/multipart/utf8_filename b/actionpack/test/fixtures/multipart/utf8_filename
new file mode 100644
index 0000000000..60738d53b0
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/utf8_filename
@@ -0,0 +1,10 @@
+--AaB03x
+Content-Disposition: form-data; name="foo"
+
+bar
+--AaB03x
+Content-Disposition: form-data; name="file"; filename="ファイル%名.txt"
+Content-Type: text/plain
+
+contents
+--AaB03x--
diff --git a/actionpack/test/fixtures/public/foo/other-index.html b/actionpack/test/fixtures/public/foo/other-index.html
new file mode 100644
index 0000000000..51c90c26ea
--- /dev/null
+++ b/actionpack/test/fixtures/public/foo/other-index.html
@@ -0,0 +1 @@
+/foo/other-index.html \ No newline at end of file
diff --git a/actionpack/test/fixtures/public/other-index.html b/actionpack/test/fixtures/public/other-index.html
new file mode 100644
index 0000000000..0820dfcb6e
--- /dev/null
+++ b/actionpack/test/fixtures/public/other-index.html
@@ -0,0 +1 @@
+/other-index.html \ No newline at end of file
diff --git a/actionpack/test/fixtures/公共/foo/other-index.html b/actionpack/test/fixtures/公共/foo/other-index.html
new file mode 100644
index 0000000000..51c90c26ea
--- /dev/null
+++ b/actionpack/test/fixtures/公共/foo/other-index.html
@@ -0,0 +1 @@
+/foo/other-index.html \ No newline at end of file
diff --git a/actionpack/test/fixtures/公共/other-index.html b/actionpack/test/fixtures/公共/other-index.html
new file mode 100644
index 0000000000..0820dfcb6e
--- /dev/null
+++ b/actionpack/test/fixtures/公共/other-index.html
@@ -0,0 +1 @@
+/other-index.html \ No newline at end of file
diff --git a/actionpack/test/journey/nodes/symbol_test.rb b/actionpack/test/journey/nodes/symbol_test.rb
index d411a5018a..adf85b860c 100644
--- a/actionpack/test/journey/nodes/symbol_test.rb
+++ b/actionpack/test/journey/nodes/symbol_test.rb
@@ -5,7 +5,7 @@ module ActionDispatch
module Nodes
class TestSymbol < ActiveSupport::TestCase
def test_default_regexp?
- sym = Symbol.new nil
+ sym = Symbol.new "foo"
assert sym.default_regexp?
sym.regexp = nil
diff --git a/actionpack/test/journey/path/pattern_test.rb b/actionpack/test/journey/path/pattern_test.rb
index 6939b426f6..72858f5eda 100644
--- a/actionpack/test/journey/path/pattern_test.rb
+++ b/actionpack/test/journey/path/pattern_test.rb
@@ -4,6 +4,8 @@ module ActionDispatch
module Journey
module Path
class TestPattern < ActiveSupport::TestCase
+ SEPARATORS = ["/", ".", "?"].join
+
x = /.+/
{
'/:controller(/:action)' => %r{\A/(#{x})(?:/([^/.?]+))?\Z},
@@ -19,12 +21,12 @@ module ActionDispatch
'/:foo|*bar' => %r{\A/(?:([^/.?]+)|(.+))\Z},
}.each do |path, expected|
define_method(:"test_to_regexp_#{path}") do
- strexp = Router::Strexp.build(
+ path = Pattern.build(
path,
{ :controller => /.+/ },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_equal(expected, path.to_regexp)
end
end
@@ -43,13 +45,12 @@ module ActionDispatch
'/:foo|*bar' => %r{\A/(?:([^/.?]+)|(.+))},
}.each do |path, expected|
define_method(:"test_to_non_anchored_regexp_#{path}") do
- strexp = Router::Strexp.build(
+ path = Pattern.build(
path,
{ :controller => /.+/ },
- ["/", ".", "?"],
+ SEPARATORS,
false
)
- path = Pattern.new strexp
assert_equal(expected, path.to_regexp)
end
end
@@ -67,27 +68,27 @@ module ActionDispatch
'/:controller/*foo/bar' => %w{ controller foo },
}.each do |path, expected|
define_method(:"test_names_#{path}") do
- strexp = Router::Strexp.build(
+ path = Pattern.build(
path,
{ :controller => /.+/ },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_equal(expected, path.names)
end
end
def test_to_regexp_with_extended_group
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/:name',
{ :name => /
#ROFL
(tender|love
#MAO
)/x },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_match(path, '/page/tender')
assert_match(path, '/page/love')
assert_no_match(path, '/page/loving')
@@ -105,23 +106,23 @@ module ActionDispatch
end
def test_to_regexp_match_non_optional
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/:name',
{ :name => /\d+/ },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_match(path, '/123')
assert_no_match(path, '/')
end
def test_to_regexp_with_group
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/:name',
{ :name => /(tender|love)/ },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_match(path, '/page/tender')
assert_match(path, '/page/love')
assert_no_match(path, '/page/loving')
@@ -129,15 +130,13 @@ module ActionDispatch
def test_ast_sets_regular_expressions
requirements = { :name => /(tender|love)/, :value => /./ }
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/:name/:value',
requirements,
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- assert_equal requirements, strexp.requirements
-
- path = Pattern.new strexp
nodes = path.ast.grep(Nodes::Symbol)
assert_equal 2, nodes.length
nodes.each do |node|
@@ -146,24 +145,24 @@ module ActionDispatch
end
def test_match_data_with_group
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/:name',
{ :name => /(tender|love)/ },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
match = path.match '/page/tender'
assert_equal 'tender', match[1]
assert_equal 2, match.length
end
def test_match_data_with_multi_group
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/:name/:id',
{ :name => /t(((ender|love)))()/ },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
match = path.match '/page/tender/10'
assert_equal 'tender', match[1]
assert_equal '10', match[2]
@@ -173,30 +172,29 @@ module ActionDispatch
def test_star_with_custom_re
z = /\d+/
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/*foo',
{ :foo => z },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_equal(%r{\A/page/(#{z})\Z}, path.to_regexp)
end
def test_insensitive_regexp_with_group
- strexp = Router::Strexp.build(
+ path = Pattern.build(
'/page/:name/aaron',
{ :name => /(tender|love)/i },
- ["/", ".", "?"]
+ SEPARATORS,
+ true
)
- path = Pattern.new strexp
assert_match(path, '/page/TENDER/aaron')
assert_match(path, '/page/loVE/aaron')
assert_no_match(path, '/page/loVE/AAron')
end
def test_to_regexp_with_strexp
- strexp = Router::Strexp.build('/:controller', { }, ["/", ".", "?"])
- path = Pattern.new strexp
+ path = Pattern.build('/:controller', { }, SEPARATORS, true)
x = %r{\A/([^/.?]+)\Z}
assert_equal(x.source, path.source)
diff --git a/actionpack/test/journey/route_test.rb b/actionpack/test/journey/route_test.rb
index 21d867aca0..22c3b8113d 100644
--- a/actionpack/test/journey/route_test.rb
+++ b/actionpack/test/journey/route_test.rb
@@ -7,7 +7,7 @@ module ActionDispatch
app = Object.new
path = Path::Pattern.from_string '/:controller(/:action(/:id(.:format)))'
defaults = {}
- route = Route.new("name", app, path, {}, defaults)
+ route = Route.build("name", app, path, {}, [], defaults)
assert_equal app, route.app
assert_equal path, route.path
@@ -18,30 +18,37 @@ module ActionDispatch
app = Object.new
path = Path::Pattern.from_string '/:controller(/:action(/:id(.:format)))'
defaults = {}
- route = Route.new("name", app, path, {}, defaults)
+ route = Route.build("name", app, path, {}, [], defaults)
route.ast.grep(Nodes::Terminal).each do |node|
assert_equal route, node.memo
end
end
+ def test_path_requirements_override_defaults
+ path = Path::Pattern.build(':name', { name: /love/ }, '/', true)
+ defaults = { name: 'tender' }
+ route = Route.build('name', nil, path, {}, [], defaults)
+ assert_equal(/love/, route.requirements[:name])
+ end
+
def test_ip_address
path = Path::Pattern.from_string '/messages/:id(.:format)'
- route = Route.new("name", nil, path, {:ip => '192.168.1.1'},
+ route = Route.build("name", nil, path, {:ip => '192.168.1.1'}, [],
{ :controller => 'foo', :action => 'bar' })
assert_equal '192.168.1.1', route.ip
end
def test_default_ip
path = Path::Pattern.from_string '/messages/:id(.:format)'
- route = Route.new("name", nil, path, {},
+ route = Route.build("name", nil, path, {}, [],
{ :controller => 'foo', :action => 'bar' })
assert_equal(//, route.ip)
end
def test_format_with_star
path = Path::Pattern.from_string '/:controller/*extra'
- route = Route.new("name", nil, path, {},
+ route = Route.build("name", nil, path, {}, [],
{ :controller => 'foo', :action => 'bar' })
assert_equal '/foo/himom', route.format({
:controller => 'foo',
@@ -51,7 +58,7 @@ module ActionDispatch
def test_connects_all_match
path = Path::Pattern.from_string '/:controller(/:action(/:id(.:format)))'
- route = Route.new("name", nil, path, {:action => 'bar'}, { :controller => 'foo' })
+ route = Route.build("name", nil, path, {:action => 'bar'}, [], { :controller => 'foo' })
assert_equal '/foo/bar/10', route.format({
:controller => 'foo',
@@ -62,34 +69,34 @@ module ActionDispatch
def test_extras_are_not_included_if_optional
path = Path::Pattern.from_string '/page/:id(/:action)'
- route = Route.new("name", nil, path, { }, { :action => 'show' })
+ route = Route.build("name", nil, path, { }, [], { :action => 'show' })
assert_equal '/page/10', route.format({ :id => 10 })
end
def test_extras_are_not_included_if_optional_with_parameter
path = Path::Pattern.from_string '(/sections/:section)/pages/:id'
- route = Route.new("name", nil, path, { }, { :action => 'show' })
+ route = Route.build("name", nil, path, { }, [], { :action => 'show' })
assert_equal '/pages/10', route.format({:id => 10})
end
def test_extras_are_not_included_if_optional_parameter_is_nil
path = Path::Pattern.from_string '(/sections/:section)/pages/:id'
- route = Route.new("name", nil, path, { }, { :action => 'show' })
+ route = Route.build("name", nil, path, { }, [], { :action => 'show' })
assert_equal '/pages/10', route.format({:id => 10, :section => nil})
end
def test_score
- constraints = {:required_defaults => [:controller, :action]}
+ constraints = {}
defaults = {:controller=>"pages", :action=>"show"}
path = Path::Pattern.from_string "/page/:id(/:action)(.:format)"
- specific = Route.new "name", nil, path, constraints, defaults
+ specific = Route.build "name", nil, path, constraints, [:controller, :action], defaults
path = Path::Pattern.from_string "/:controller(/:action(/:id))(.:format)"
- generic = Route.new "name", nil, path, constraints
+ generic = Route.build "name", nil, path, constraints, [], {}
knowledge = {:id=>20, :controller=>"pages", :action=>"show"}
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
index 19c61b5914..15d51e5d6c 100644
--- a/actionpack/test/journey/router_test.rb
+++ b/actionpack/test/journey/router_test.rb
@@ -1,141 +1,45 @@
-# encoding: UTF-8
require 'abstract_unit'
module ActionDispatch
module Journey
class TestRouter < ActiveSupport::TestCase
- attr_reader :routes
+ attr_reader :routes, :mapper
def setup
@app = Routing::RouteSet::Dispatcher.new({})
- @routes = Routes.new
- @router = Router.new(@routes)
- @formatter = Formatter.new(@routes)
- end
-
- class FakeRequestFeeler < Struct.new(:env, :called)
- def new env
- self.env = env
- self
- end
-
- def hello
- self.called = true
- 'world'
- end
-
- def path_info; env['PATH_INFO']; end
- def request_method; env['REQUEST_METHOD']; end
- def ip; env['REMOTE_ADDR']; end
+ @route_set = ActionDispatch::Routing::RouteSet.new
+ @routes = @route_set.router.routes
+ @router = @route_set.router
+ @formatter = @route_set.formatter
+ @mapper = ActionDispatch::Routing::Mapper.new @route_set
end
def test_dashes
- router = Router.new(routes)
-
- exp = Router::Strexp.build '/foo-bar-baz', {}, ['/.?']
- path = Path::Pattern.new exp
-
- routes.add_route nil, path, {}, {:id => nil}, {}
+ mapper.get '/foo-bar-baz', to: 'foo#bar'
env = rails_env 'PATH_INFO' => '/foo-bar-baz'
called = false
- router.recognize(env) do |r, params|
+ @router.recognize(env) do |r, params|
called = true
end
assert called
end
def test_unicode
- router = Router.new(routes)
+ mapper.get '/ほげ', to: 'foo#bar'
#match the escaped version of /ほげ
- exp = Router::Strexp.build '/%E3%81%BB%E3%81%92', {}, ['/.?']
- path = Path::Pattern.new exp
-
- routes.add_route nil, path, {}, {:id => nil}, {}
-
env = rails_env 'PATH_INFO' => '/%E3%81%BB%E3%81%92'
called = false
- router.recognize(env) do |r, params|
+ @router.recognize(env) do |r, params|
called = true
end
assert called
end
- def test_request_class_and_requirements_success
- klass = FakeRequestFeeler.new nil
- router = Router.new(routes)
-
- requirements = { :hello => /world/ }
-
- exp = Router::Strexp.build '/foo(/:id)', {}, ['/.?']
- path = Path::Pattern.new exp
-
- routes.add_route nil, path, requirements, {:id => nil}, {}
-
- env = rails_env({'PATH_INFO' => '/foo/10'}, klass)
- router.recognize(env) do |r, params|
- assert_equal({:id => '10'}, params)
- end
-
- assert klass.called, 'hello should have been called'
- assert_equal env.env, klass.env
- end
-
- def test_request_class_and_requirements_fail
- klass = FakeRequestFeeler.new nil
- router = Router.new(routes)
-
- requirements = { :hello => /mom/ }
-
- exp = Router::Strexp.build '/foo(/:id)', {}, ['/.?']
- path = Path::Pattern.new exp
-
- router.routes.add_route nil, path, requirements, {:id => nil}, {}
-
- env = rails_env({'PATH_INFO' => '/foo/10'}, klass)
- router.recognize(env) do |r, params|
- flunk 'route should not be found'
- end
-
- assert klass.called, 'hello should have been called'
- assert_equal env.env, klass.env
- end
-
- class CustomPathRequest < ActionDispatch::Request
- def path_info
- env['custom.path_info']
- end
-
- def path_info=(x)
- env['custom.path_info'] = x
- end
- end
-
- def test_request_class_overrides_path_info
- router = Router.new(routes)
-
- exp = Router::Strexp.build '/bar', {}, ['/.?']
- path = Path::Pattern.new exp
-
- routes.add_route nil, path, {}, {}, {}
-
- env = rails_env({'PATH_INFO' => '/foo',
- 'custom.path_info' => '/bar'}, CustomPathRequest)
-
- recognized = false
- router.recognize(env) do |r, params|
- recognized = true
- end
-
- assert recognized, "route should have been recognized"
- end
-
def test_regexp_first_precedence
- add_routes @router, [
- Router::Strexp.build("/whois/:domain", {:domain => /\w+\.[\w\.]+/}, ['/', '.', '?']),
- Router::Strexp.build("/whois/:id(.:format)", {}, ['/', '.', '?'])
- ]
+ mapper.get "/whois/:domain", :domain => /\w+\.[\w\.]+/, to: "foo#bar"
+ mapper.get "/whois/:id(.:format)", to: "foo#baz"
env = rails_env 'PATH_INFO' => '/whois/example.com'
@@ -147,25 +51,21 @@ module ActionDispatch
r = list.first
- assert_equal '/whois/:domain', r.path.spec.to_s
+ assert_equal '/whois/:domain(.:format)', r.path.spec.to_s
end
def test_required_parts_verified_are_anchored
- add_routes @router, [
- Router::Strexp.build("/foo/:id", { :id => /\d/ }, ['/', '.', '?'], false)
- ]
+ mapper.get "/foo/:id", :id => /\d/, anchor: false, to: "foo#bar"
assert_raises(ActionController::UrlGenerationError) do
- @formatter.generate(nil, { :id => '10' }, { })
+ @formatter.generate(nil, { :controller => "foo", :action => "bar", :id => '10' }, { })
end
end
def test_required_parts_are_verified_when_building
- add_routes @router, [
- Router::Strexp.build("/foo/:id", { :id => /\d+/ }, ['/', '.', '?'], false)
- ]
+ mapper.get "/foo/:id", :id => /\d+/, anchor: false, to: "foo#bar"
- path, _ = @formatter.generate(nil, { :id => '10' }, { })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :action => "bar", :id => '10' }, { })
assert_equal '/foo/10', path
assert_raises(ActionController::UrlGenerationError) do
@@ -174,25 +74,22 @@ module ActionDispatch
end
def test_only_required_parts_are_verified
- add_routes @router, [
- Router::Strexp.build("/foo(/:id)", {:id => /\d/}, ['/', '.', '?'], false)
- ]
+ mapper.get "/foo(/:id)", :id => /\d/, :to => "foo#bar"
- path, _ = @formatter.generate(nil, { :id => '10' }, { })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :action => "bar", :id => '10' }, { })
assert_equal '/foo/10', path
- path, _ = @formatter.generate(nil, { }, { })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :action => "bar" }, { })
assert_equal '/foo', path
- path, _ = @formatter.generate(nil, { :id => 'aa' }, { })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :action => "bar", :id => 'aa' }, { })
assert_equal '/foo/aa', path
end
def test_knows_what_parts_are_missing_from_named_route
route_name = "gorby_thunderhorse"
- pattern = Router::Strexp.build("/foo/:id", { :id => /\d+/ }, ['/', '.', '?'], false)
- path = Path::Pattern.new pattern
- @router.routes.add_route nil, path, {}, {}, route_name
+ mapper = ActionDispatch::Routing::Mapper.new @route_set
+ mapper.get "/foo/:id", :as => route_name, :id => /\d+/, :to => "foo#bar"
error = assert_raises(ActionController::UrlGenerationError) do
@formatter.generate(route_name, { }, { })
@@ -212,7 +109,7 @@ module ActionDispatch
end
def test_X_Cascade
- add_routes @router, [ "/messages(.:format)" ]
+ mapper.get "/messages(.:format)", to: "foo#bar"
resp = @router.serve(rails_env({ 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/lol' }))
assert_equal ['Not Found'], resp.last
assert_equal 'pass', resp[1]['X-Cascade']
@@ -233,24 +130,21 @@ module ActionDispatch
end
def test_defaults_merge_correctly
- path = Path::Pattern.from_string '/foo(/:id)'
- @router.routes.add_route nil, path, {}, {:id => nil}, {}
+ mapper.get '/foo(/:id)', to: "foo#bar", id: nil
env = rails_env 'PATH_INFO' => '/foo/10'
@router.recognize(env) do |r, params|
- assert_equal({:id => '10'}, params)
+ assert_equal({:id => '10', :controller => "foo", :action => "bar"}, params)
end
env = rails_env 'PATH_INFO' => '/foo'
@router.recognize(env) do |r, params|
- assert_equal({:id => nil}, params)
+ assert_equal({:id => nil, :controller => "foo", :action => "bar"}, params)
end
end
def test_recognize_with_unbound_regexp
- add_routes @router, [
- Router::Strexp.build("/foo", { }, ['/', '.', '?'], false)
- ]
+ mapper.get "/foo", anchor: false, to: "foo#bar"
env = rails_env 'PATH_INFO' => '/foo/bar'
@@ -261,9 +155,7 @@ module ActionDispatch
end
def test_bound_regexp_keeps_path_info
- add_routes @router, [
- Router::Strexp.build("/foo", { }, ['/', '.', '?'], true)
- ]
+ mapper.get "/foo", to: "foo#bar"
env = rails_env 'PATH_INFO' => '/foo'
@@ -276,12 +168,14 @@ module ActionDispatch
end
def test_path_not_found
- add_routes @router, [
+ [
"/messages(.:format)",
"/messages/new(.:format)",
"/messages/:id/edit(.:format)",
"/messages/:id(.:format)"
- ]
+ ].each do |path|
+ mapper.get path, to: "foo#bar"
+ end
env = rails_env 'PATH_INFO' => '/messages/unknown/path'
yielded = false
@@ -292,32 +186,29 @@ module ActionDispatch
end
def test_required_part_in_recall
- add_routes @router, [ "/messages/:a/:b" ]
+ mapper.get "/messages/:a/:b", to: "foo#bar"
- path, _ = @formatter.generate(nil, { :a => 'a' }, { :b => 'b' })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :action => "bar", :a => 'a' }, { :b => 'b' })
assert_equal "/messages/a/b", path
end
def test_splat_in_recall
- add_routes @router, [ "/*path" ]
+ mapper.get "/*path", to: "foo#bar"
- path, _ = @formatter.generate(nil, { }, { :path => 'b' })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :action => "bar" }, { :path => 'b' })
assert_equal "/b", path
end
def test_recall_should_be_used_when_scoring
- add_routes @router, [
- "/messages/:action(/:id(.:format))",
- "/messages/:id(.:format)"
- ]
+ mapper.get "/messages/:action(/:id(.:format))", to: 'foo#bar'
+ mapper.get "/messages/:id(.:format)", to: 'bar#baz'
- path, _ = @formatter.generate(nil, { :id => 10 }, { :action => 'index' })
+ path, _ = @formatter.generate(nil, { :controller => "foo", :id => 10 }, { :action => 'index' })
assert_equal "/messages/index/10", path
end
def test_nil_path_parts_are_ignored
- path = Path::Pattern.from_string "/:controller(/:action(.:format))"
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get "/:controller(/:action(.:format))", to: "tasks#lol"
params = { :controller => "tasks", :format => nil }
extras = { :action => 'lol' }
@@ -329,18 +220,14 @@ module ActionDispatch
def test_generate_slash
params = [ [:controller, "tasks"],
[:action, "show"] ]
- str = Router::Strexp.build("/", Hash[params], ['/', '.', '?'], true)
- path = Path::Pattern.new str
-
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get "/", Hash[params]
path, _ = @formatter.generate(nil, Hash[params], {})
assert_equal '/', path
end
def test_generate_calls_param_proc
- path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get '/:controller(/:action)', to: "foo#bar"
parameterized = []
params = [ [:controller, "tasks"],
@@ -356,8 +243,7 @@ module ActionDispatch
end
def test_generate_id
- path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get '/:controller(/:action)', to: 'foo#bar'
path, params = @formatter.generate(
nil, {:id=>1, :controller=>"tasks", :action=>"show"}, {})
@@ -366,8 +252,7 @@ module ActionDispatch
end
def test_generate_escapes
- path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get '/:controller(/:action)', to: "foo#bar"
path, _ = @formatter.generate(nil,
{ :controller => "tasks",
@@ -377,8 +262,7 @@ module ActionDispatch
end
def test_generate_escapes_with_namespaced_controller
- path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get '/:controller(/:action)', to: "foo#bar"
path, _ = @formatter.generate(
nil, { :controller => "admin/tasks",
@@ -388,8 +272,7 @@ module ActionDispatch
end
def test_generate_extra_params
- path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get '/:controller(/:action)', to: "foo#bar"
path, params = @formatter.generate(
nil, { :id => 1,
@@ -401,9 +284,34 @@ module ActionDispatch
assert_equal({:id => 1, :relative_url_root => nil}, params)
end
+ def test_generate_missing_keys_no_matches_different_format_keys
+ mapper.get '/:controller/:action/:name', to: "foo#bar"
+ primarty_parameters = {
+ :id => 1,
+ :controller => "tasks",
+ :action => "show",
+ :relative_url_root => nil
+ }
+ redirection_parameters = {
+ 'action'=>'show',
+ }
+ missing_key = 'name'
+ missing_parameters ={
+ missing_key => "task_1"
+ }
+ request_parameters = primarty_parameters.merge(redirection_parameters).merge(missing_parameters)
+
+ message = "No route matches #{Hash[request_parameters.sort_by{|k,v|k.to_s}].inspect} missing required keys: #{[missing_key.to_sym].inspect}"
+
+ error = assert_raises(ActionController::UrlGenerationError) do
+ @formatter.generate(
+ nil, request_parameters, request_parameters)
+ end
+ assert_equal message, error.message
+ end
+
def test_generate_uses_recall_if_needed
- path = Path::Pattern.from_string '/:controller(/:action(/:id))'
- @router.routes.add_route @app, path, {}, {}, {}
+ mapper.get '/:controller(/:action(/:id))', to: "foo#bar"
path, params = @formatter.generate(
nil,
@@ -414,8 +322,7 @@ module ActionDispatch
end
def test_generate_with_name
- path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, "tasks"
+ mapper.get '/:controller(/:action)', to: 'foo#bar', as: 'tasks'
path, params = @formatter.generate(
"tasks",
@@ -431,16 +338,15 @@ module ActionDispatch
'/content/show/10' => { :controller => 'content', :action => 'show', :id => "10" },
}.each do |request_path, expected|
define_method("test_recognize_#{expected.keys.map(&:to_s).join('_')}") do
- path = Path::Pattern.from_string "/:controller(/:action(/:id))"
- app = Object.new
- route = @router.routes.add_route(app, path, {}, {}, {})
+ mapper.get "/:controller(/:action(/:id))", to: 'foo#bar'
+ route = @routes.first
env = rails_env 'PATH_INFO' => request_path
called = false
@router.recognize(env) do |r, params|
assert_equal route, r
- assert_equal(expected, params)
+ assert_equal({ :action => "bar" }.merge(expected), params)
called = true
end
@@ -453,16 +359,15 @@ module ActionDispatch
:splat => ['/segment/a/b%20c+d', { :segment => 'segment', :splat => 'a/b c+d' }]
}.each do |name, (request_path, expected)|
define_method("test_recognize_#{name}") do
- path = Path::Pattern.from_string '/:segment/*splat'
- app = Object.new
- route = @router.routes.add_route(app, path, {}, {}, {})
+ mapper.get '/:segment/*splat', to: 'foo#bar'
env = rails_env 'PATH_INFO' => request_path
called = false
+ route = @routes.first
@router.recognize(env) do |r, params|
assert_equal route, r
- assert_equal(expected, params)
+ assert_equal(expected.merge(:controller=>"foo", :action=>"bar"), params)
called = true
end
@@ -471,14 +376,8 @@ module ActionDispatch
end
def test_namespaced_controller
- strexp = Router::Strexp.build(
- "/:controller(/:action(/:id))",
- { :controller => /.+?/ },
- ["/", ".", "?"]
- )
- path = Path::Pattern.new strexp
- app = Object.new
- route = @router.routes.add_route(app, path, {}, {}, {})
+ mapper.get "/:controller(/:action(/:id))", { :controller => /.+?/ }
+ route = @routes.first
env = rails_env 'PATH_INFO' => '/admin/users/show/10'
called = false
@@ -497,9 +396,8 @@ module ActionDispatch
end
def test_recognize_literal
- path = Path::Pattern.from_string "/books(/:action(.:format))"
- app = Object.new
- route = @router.routes.add_route(app, path, {}, {:controller => 'books'})
+ mapper.get "/books(/:action(.:format))", controller: "books"
+ route = @routes.first
env = rails_env 'PATH_INFO' => '/books/list.rss'
expected = { :controller => 'books', :action => 'list', :format => 'rss' }
@@ -514,10 +412,7 @@ module ActionDispatch
end
def test_recognize_head_route
- path = Path::Pattern.from_string "/books(/:action(.:format))"
- app = Object.new
- conditions = { request_method: 'HEAD' }
- @router.routes.add_route(app, path, conditions, {})
+ mapper.match "/books(/:action(.:format))", via: 'head', to: 'foo#bar'
env = rails_env(
'PATH_INFO' => '/books/list.rss',
@@ -533,12 +428,7 @@ module ActionDispatch
end
def test_recognize_head_request_as_get_route
- path = Path::Pattern.from_string "/books(/:action(.:format))"
- app = Object.new
- conditions = {
- :request_method => 'GET'
- }
- @router.routes.add_route(app, path, conditions, {})
+ mapper.get "/books(/:action(.:format))", to: 'foo#bar'
env = rails_env 'PATH_INFO' => '/books/list.rss',
"REQUEST_METHOD" => "HEAD"
@@ -551,11 +441,8 @@ module ActionDispatch
assert called
end
- def test_recognize_cares_about_verbs
- path = Path::Pattern.from_string "/books(/:action(.:format))"
- app = Object.new
- conditions = { request_method: 'GET' }
- @router.routes.add_route(app, path, conditions, {})
+ def test_recognize_cares_about_get_verbs
+ mapper.match "/books(/:action(.:format))", to: "foo#bar", via: :get
env = rails_env 'PATH_INFO' => '/books/list.rss',
"REQUEST_METHOD" => "POST"
@@ -566,34 +453,50 @@ module ActionDispatch
end
assert_not called
+ end
- conditions = conditions.dup
- conditions[:request_method] = 'POST'
+ def test_recognize_cares_about_post_verbs
+ mapper.match "/books(/:action(.:format))", to: "foo#bar", via: :post
- post = @router.routes.add_route(app, path, conditions, {})
+ env = rails_env 'PATH_INFO' => '/books/list.rss',
+ "REQUEST_METHOD" => "POST"
called = false
@router.recognize(env) do |r, params|
- assert_equal post, r
called = true
end
assert called
end
- private
+ def test_multi_verb_recognition
+ mapper.match "/books(/:action(.:format))", to: "foo#bar", via: [:post, :get]
+
+ %w( POST GET ).each do |verb|
+ env = rails_env 'PATH_INFO' => '/books/list.rss',
+ "REQUEST_METHOD" => verb
- def add_routes router, paths
- paths.each do |path|
- if String === path
- path = Path::Pattern.from_string path
- else
- path = Path::Pattern.new path
+ called = false
+ @router.recognize(env) do |r, params|
+ called = true
end
- router.routes.add_route @app, path, {}, {}, {}
+
+ assert called
+ end
+
+ env = rails_env 'PATH_INFO' => '/books/list.rss',
+ "REQUEST_METHOD" => 'PUT'
+
+ called = false
+ @router.recognize(env) do |r, params|
+ called = true
end
+
+ assert_not called
end
+ private
+
def rails_env env, klass = ActionDispatch::Request
klass.new(rack_env(env))
end
diff --git a/actionpack/test/journey/routes_test.rb b/actionpack/test/journey/routes_test.rb
index b54d961f66..f8293dfc5f 100644
--- a/actionpack/test/journey/routes_test.rb
+++ b/actionpack/test/journey/routes_test.rb
@@ -3,70 +3,57 @@ require 'abstract_unit'
module ActionDispatch
module Journey
class TestRoutes < ActiveSupport::TestCase
- setup do
- @routes = Routes.new
+ attr_reader :routes, :mapper
+
+ def setup
+ @route_set = ActionDispatch::Routing::RouteSet.new
+ @routes = @route_set.router.routes
+ @router = @route_set.router
+ @mapper = ActionDispatch::Routing::Mapper.new @route_set
+ super
end
def test_clear
- routes = Routes.new
- exp = Router::Strexp.build '/foo(/:id)', {}, ['/.?']
- path = Path::Pattern.new exp
- requirements = { :hello => /world/ }
-
- routes.add_route nil, path, requirements, {:id => nil}, {}
+ mapper.get "/foo(/:id)", to: "foo#bar", as: 'aaron'
+ assert_not_predicate routes, :empty?
assert_equal 1, routes.length
routes.clear
+ assert routes.empty?
assert_equal 0, routes.length
end
def test_ast
- routes = Routes.new
- path = Path::Pattern.from_string '/hello'
-
- routes.add_route nil, path, {}, {}, {}
+ mapper.get "/foo(/:id)", to: "foo#bar", as: 'aaron'
ast = routes.ast
- routes.add_route nil, path, {}, {}, {}
+ mapper.get "/foo(/:id)", to: "foo#bar", as: 'gorby'
assert_not_equal ast, routes.ast
end
def test_simulator_changes
- routes = Routes.new
- path = Path::Pattern.from_string '/hello'
-
- routes.add_route nil, path, {}, {}, {}
+ mapper.get "/foo(/:id)", to: "foo#bar", as: 'aaron'
sim = routes.simulator
- routes.add_route nil, path, {}, {}, {}
+ mapper.get "/foo(/:id)", to: "foo#bar", as: 'gorby'
assert_not_equal sim, routes.simulator
end
def test_partition_route
- path = Path::Pattern.from_string '/hello'
+ mapper.get "/foo(/:id)", to: "foo#bar", as: 'aaron'
- anchored_route = @routes.add_route nil, path, {}, {}, {}
- assert_equal [anchored_route], @routes.anchored_routes
- assert_equal [], @routes.custom_routes
+ assert_equal 1, @routes.anchored_routes.length
+ assert_predicate @routes.custom_routes, :empty?
- strexp = Router::Strexp.build(
- "/hello/:who", { who: /\d/ }, ['/', '.', '?']
- )
- path = Path::Pattern.new strexp
+ mapper.get "/hello/:who", to: "foo#bar", as: 'bar', who: /\d/
- custom_route = @routes.add_route nil, path, {}, {}, {}
- assert_equal [custom_route], @routes.custom_routes
- assert_equal [anchored_route], @routes.anchored_routes
+ assert_equal 1, @routes.custom_routes.length
+ assert_equal 1, @routes.anchored_routes.length
end
def test_first_name_wins
- routes = Routes.new
-
- one = Path::Pattern.from_string '/hello'
- two = Path::Pattern.from_string '/aaron'
-
- routes.add_route nil, one, {}, {}, 'aaron'
- routes.add_route nil, two, {}, {}, 'aaron'
-
- assert_equal '/hello', routes.named_routes['aaron'].path.spec.to_s
+ mapper.get "/hello", to: "foo#bar", as: 'aaron'
+ assert_raise(ArgumentError) do
+ mapper.get "/aaron", to: "foo#bar", as: 'aaron'
+ end
end
end
end