File: routing.rb

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (343 lines) | stat: -rw-r--r-- 13,501 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# frozen_string_literal: true

# :markup: markdown

require "uri"
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/access"
require "action_controller/metal/exceptions"

module ActionDispatch
  module Assertions
    # Suite of assertions to test routes generated by Rails and the handling of
    # requests made to them.
    module RoutingAssertions
      extend ActiveSupport::Concern

      module WithIntegrationRouting # :nodoc:
        extend ActiveSupport::Concern

        module ClassMethods
          def with_routing(&block)
            old_routes = nil
            old_integration_session = nil

            setup do
              old_routes = app.routes
              old_integration_session = integration_session
              create_routes(&block)
            end

            teardown do
              reset_routes(old_routes, old_integration_session)
            end
          end
        end

        def with_routing(&block)
          old_routes = app.routes
          old_integration_session = integration_session
          create_routes(&block)
        ensure
          reset_routes(old_routes, old_integration_session)
        end

        private
          def create_routes
            app = self.app
            routes = ActionDispatch::Routing::RouteSet.new
            rack_app = app.config.middleware.build(routes)
            https = integration_session.https?
            host = integration_session.host

            app.instance_variable_set(:@routes, routes)
            app.instance_variable_set(:@app, rack_app)
            @integration_session = Class.new(ActionDispatch::Integration::Session) do
              include app.routes.url_helpers
              include app.routes.mounted_helpers
            end.new(app)
            @integration_session.https! https
            @integration_session.host! host
            @routes = routes

            yield routes
          end

          def reset_routes(old_routes, old_integration_session)
            old_rack_app = app.config.middleware.build(old_routes)

            app.instance_variable_set(:@routes, old_routes)
            app.instance_variable_set(:@app, old_rack_app)
            @integration_session = old_integration_session
            @routes = old_routes
          end
      end

      module ClassMethods
        # A helper to make it easier to test different route configurations. This method
        # temporarily replaces @routes with a new RouteSet instance before each test.
        #
        # The new instance is yielded to the passed block. Typically the block will
        # create some routes using `set.draw { match ... }`:
        #
        #     with_routing do |set|
        #       set.draw do
        #         resources :users
        #       end
        #     end
        #
        def with_routing(&block)
          old_routes, old_controller = nil

          setup do
            old_routes, old_controller = @routes, @controller
            create_routes(&block)
          end

          teardown do
            reset_routes(old_routes, old_controller)
          end
        end
      end

      def setup # :nodoc:
        @routes ||= nil
        super
      end

      # A helper to make it easier to test different route configurations. This method
      # temporarily replaces @routes with a new RouteSet instance.
      #
      # The new instance is yielded to the passed block. Typically the block will
      # create some routes using `set.draw { match ... }`:
      #
      #     with_routing do |set|
      #       set.draw do
      #         resources :users
      #       end
      #       assert_equal "/users", users_path
      #     end
      #
      def with_routing(&block)
        old_routes, old_controller = @routes, @controller
        create_routes(&block)
      ensure
        reset_routes(old_routes, old_controller)
      end

      # Asserts that the routing of the given `path` was handled correctly and that
      # the parsed options (given in the `expected_options` hash) match `path`.
      # Basically, it asserts that Rails recognizes the route given by
      # `expected_options`.
      #
      # Pass a hash in the second argument (`path`) to specify the request method.
      # This is useful for routes requiring a specific HTTP method. The hash should
      # contain a `:path` with the incoming request path and a `:method` containing
      # the required HTTP verb.
      #
      #     # 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 will end up in the params hash correctly. To test query strings
      # you must use the extras argument because appending the query string on the
      # path directly will not work. For example:
      #
      #     # 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.
      #
      #     # Check the default route (i.e., the index action)
      #     assert_recognizes({controller: 'items', action: 'index'}, 'items')
      #
      #     # Test a specific action
      #     assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
      #
      #     # Test an action with a parameter
      #     assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
      #
      #     # Test a custom route
      #     assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
      def assert_recognizes(expected_options, path, extras = {}, msg = nil)
        if path.is_a?(Hash) && path[:method].to_s == "all"
          [:get, :post, :put, :delete].each do |method|
            assert_recognizes(expected_options, path.merge(method: method), extras, msg)
          end
        else
          request = recognized_request_for(path, extras, msg)

          expected_options = expected_options.clone

          expected_options.stringify_keys!

          msg = message(msg, "") {
            sprintf("The recognized options <%s> did not match <%s>, difference:",
                    request.path_parameters, expected_options)
          }

          assert_equal(expected_options, request.path_parameters, msg)
        end
      end

      # Asserts that the provided options can be used to generate the provided path.
      # This is the inverse of `assert_recognizes`. The `extras` parameter is used to
      # tell the request the names and values of additional request parameters that
      # would be in a query string. The `message` parameter allows you to specify a
      # custom error message for assertion failures.
      #
      # The `defaults` parameter is unused.
      #
      #     # Asserts that the default action is generated for a route with no action
      #     assert_generates "/items", controller: "items", action: "index"
      #
      #     # Tests that the list action is properly routed
      #     assert_generates "/items/list", controller: "items", action: "list"
      #
      #     # Tests the generation of a route with a parameter
      #     assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
      #
      #     # Asserts that the generated route gives us our custom route
      #     assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
      def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)
        if expected_path.include?("://")
          fail_on(URI::InvalidURIError, message) do
            uri = URI.parse(expected_path)
            expected_path = uri.path.to_s.empty? ? "/" : uri.path
          end
        else
          expected_path = "/#{expected_path}" unless expected_path.start_with?("/")
        end

        options = options.clone
        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)

        msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
            expected_path)
        assert_equal(expected_path, generated_path, msg)
      end

      # Asserts that path and options match both ways; in other words, it verifies
      # that `path` generates `options` and then that `options` generates `path`. This
      # essentially combines `assert_recognizes` and `assert_generates` into one step.
      #
      # 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.
      #
      #     # 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
      #
      #     # 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
      #     assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}
      #
      #     # Tests a route with an HTTP method
      #     assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
      def assert_routing(path, options, defaults = {}, extras = {}, message = nil)
        assert_recognizes(options, path, extras, message)

        controller, default_controller = options[:controller], defaults[:controller]
        if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
          options[:controller] = "/#{controller}"
        end

        generate_options = options.dup.delete_if { |k, _| defaults.key?(k) }
        assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
      end

      # ROUTES TODO: These assertions should really work in an integration context
      def method_missing(selector, ...)
        if @controller && @routes&.named_routes&.route_defined?(selector)
          @controller.public_send(selector, ...)
        else
          super
        end
      end

      private
        def create_routes
          @routes = ActionDispatch::Routing::RouteSet.new
          if @controller
            @controller = @controller.clone
            _routes = @routes

            @controller.singleton_class.include(_routes.url_helpers)

            if @controller.respond_to? :view_context_class
              view_context_class = Class.new(@controller.view_context_class) do
                include _routes.url_helpers
              end

              custom_view_context = Module.new {
                define_method(:view_context_class) do
                  view_context_class
                end
              }
              @controller.extend(custom_view_context)
            end
          end
          yield @routes
        end

        def reset_routes(old_routes, old_controller)
          @routes = old_routes
          if @controller
            @controller = old_controller
          end
        end

        # Recognizes the route for a given path.
        def recognized_request_for(path, extras = {}, msg)
          if path.is_a?(Hash)
            method = path[:method]
            path   = path[:path]
          else
            method = :get
          end

          controller = @controller if defined?(@controller)
          request = ActionController::TestRequest.create controller&.class

          if path.include?("://")
            fail_on(URI::InvalidURIError, msg) do
              uri = URI.parse(path)
              request.env["rack.url_scheme"] = uri.scheme || "http"
              request.host = uri.host if uri.host
              request.port = uri.port if uri.port
              request.path = uri.path.to_s.empty? ? "/" : uri.path
            end
          else
            path = "/#{path}" unless path.start_with?("/")
            request.path = path
          end

          request.request_method = method if method

          params = fail_on(ActionController::RoutingError, msg) do
            @routes.recognize_path(path, method: method, extras: extras)
          end
          request.path_parameters = params.with_indifferent_access

          request
        end

        def fail_on(exception_class, message)
          yield
        rescue exception_class => e
          raise Minitest::Assertion, message || e.message
        end
    end
  end
end