PageRenderTime 56ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/rails/actionpack/test/controller/routing_test.rb

https://github.com/apasha/insoshi
Ruby | 2435 lines | 1957 code | 454 blank | 24 comment | 9 complexity | 90d32193a58f672b7d456e350bcdd5b7 MD5 | raw file
Possible License(s): AGPL-3.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0

Large files files are truncated, but you can click here to view the full file

  1. require 'abstract_unit'
  2. require 'controller/fake_controllers'
  3. require 'action_controller/routing'
  4. class MilestonesController < ActionController::Base
  5. def index() head :ok end
  6. alias_method :show, :index
  7. def rescue_action(e) raise e end
  8. end
  9. RunTimeTests = ARGV.include? 'time'
  10. ROUTING = ActionController::Routing
  11. class ROUTING::RouteBuilder
  12. attr_reader :warn_output
  13. def warn(msg)
  14. (@warn_output ||= []) << msg
  15. end
  16. end
  17. # See RFC 3986, section 3.3 for allowed path characters.
  18. class UriReservedCharactersRoutingTest < Test::Unit::TestCase
  19. def setup
  20. ActionController::Routing.use_controllers! ['controller']
  21. @set = ActionController::Routing::RouteSet.new
  22. @set.draw do |map|
  23. map.connect ':controller/:action/:variable/*additional'
  24. end
  25. safe, unsafe = %w(: @ & = + $ , ;), %w(^ / ? # [ ])
  26. hex = unsafe.map { |char| '%' + char.unpack('H2').first.upcase }
  27. @segment = "#{safe.join}#{unsafe.join}".freeze
  28. @escaped = "#{safe.join}#{hex.join}".freeze
  29. end
  30. def test_route_generation_escapes_unsafe_path_characters
  31. assert_equal "/contr#{@segment}oller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
  32. @set.generate(:controller => "contr#{@segment}oller",
  33. :action => "act#{@segment}ion",
  34. :variable => "var#{@segment}iable",
  35. :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"])
  36. end
  37. def test_route_recognition_unescapes_path_components
  38. options = { :controller => "controller",
  39. :action => "act#{@segment}ion",
  40. :variable => "var#{@segment}iable",
  41. :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] }
  42. assert_equal options, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2")
  43. end
  44. def test_route_generation_allows_passing_non_string_values_to_generated_helper
  45. assert_equal "/controller/action/variable/1/2", @set.generate(:controller => "controller",
  46. :action => "action",
  47. :variable => "variable",
  48. :additional => [1, 2])
  49. end
  50. end
  51. class LegacyRouteSetTests < Test::Unit::TestCase
  52. attr_reader :rs
  53. def setup
  54. # These tests assume optimisation is on, so re-enable it.
  55. ActionController::Base.optimise_named_routes = true
  56. @rs = ::ActionController::Routing::RouteSet.new
  57. @rs.draw {|m| m.connect ':controller/:action/:id' }
  58. ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed)
  59. end
  60. def test_default_setup
  61. assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
  62. assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
  63. assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
  64. assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10"))
  65. assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10)
  66. assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  67. assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  68. assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  69. assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  70. end
  71. def test_ignores_leading_slash
  72. @rs.draw {|m| m.connect '/:controller/:action/:id'}
  73. test_default_setup
  74. end
  75. def test_time_recognition
  76. # We create many routes to make situation more realistic
  77. @rs = ::ActionController::Routing::RouteSet.new
  78. @rs.draw { |map|
  79. map.frontpage '', :controller => 'search', :action => 'new'
  80. map.resources :videos do |video|
  81. video.resources :comments
  82. video.resource :file, :controller => 'video_file'
  83. video.resource :share, :controller => 'video_shares'
  84. video.resource :abuse, :controller => 'video_abuses'
  85. end
  86. map.resources :abuses, :controller => 'video_abuses'
  87. map.resources :video_uploads
  88. map.resources :video_visits
  89. map.resources :users do |user|
  90. user.resource :settings
  91. user.resources :videos
  92. end
  93. map.resources :channels do |channel|
  94. channel.resources :videos, :controller => 'channel_videos'
  95. end
  96. map.resource :session
  97. map.resource :lost_password
  98. map.search 'search', :controller => 'search'
  99. map.resources :pages
  100. map.connect ':controller/:action/:id'
  101. }
  102. n = 1000
  103. if RunTimeTests
  104. GC.start
  105. rectime = Benchmark.realtime do
  106. n.times do
  107. rs.recognize_path("/videos/1234567", {:method => :get})
  108. rs.recognize_path("/videos/1234567/abuse", {:method => :get})
  109. rs.recognize_path("/users/1234567/settings", {:method => :get})
  110. rs.recognize_path("/channels/1234567", {:method => :get})
  111. rs.recognize_path("/session/new", {:method => :get})
  112. rs.recognize_path("/admin/user/show/10", {:method => :get})
  113. end
  114. end
  115. puts "\n\nRecognition (#{rs.routes.size} routes):"
  116. per_url = rectime / (n * 6)
  117. puts "#{per_url * 1000} ms/url"
  118. puts "#{1 / per_url} url/s\n\n"
  119. end
  120. end
  121. def test_time_generation
  122. n = 5000
  123. if RunTimeTests
  124. GC.start
  125. pairs = [
  126. [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}],
  127. [{:controller => 'content'}, {:controller => 'content', :action => 'index'}],
  128. [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}],
  129. [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}],
  130. [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}],
  131. [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}],
  132. [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}],
  133. [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}],
  134. ]
  135. p = nil
  136. gentime = Benchmark.realtime do
  137. n.times do
  138. pairs.each {|(a, b)| rs.generate(a, b)}
  139. end
  140. end
  141. puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)"
  142. per_url = gentime / (n * 8)
  143. puts "#{per_url * 1000} ms/url"
  144. puts "#{1 / per_url} url/s\n\n"
  145. end
  146. end
  147. def test_route_with_colon_first
  148. rs.draw do |map|
  149. map.connect '/:controller/:action/:id', :action => 'index', :id => nil
  150. map.connect ':url', :controller => 'tiny_url', :action => 'translate'
  151. end
  152. end
  153. def test_route_with_regexp_for_controller
  154. rs.draw do |map|
  155. map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/
  156. map.connect ':controller/:action/:id'
  157. end
  158. assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
  159. rs.recognize_path("/admin/user/foo"))
  160. assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo"))
  161. assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
  162. assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo")
  163. end
  164. def test_route_with_regexp_and_dot
  165. rs.draw do |map|
  166. map.connect ':controller/:action/:file',
  167. :controller => /admin|user/,
  168. :action => /upload|download/,
  169. :defaults => {:file => nil},
  170. :requirements => {:file => %r{[^/]+(\.[^/]+)?}}
  171. end
  172. # Without a file extension
  173. assert_equal '/user/download/file',
  174. rs.generate(:controller => "user", :action => "download", :file => "file")
  175. assert_equal(
  176. {:controller => "user", :action => "download", :file => "file"},
  177. rs.recognize_path("/user/download/file"))
  178. # Now, let's try a file with an extension, really a dot (.)
  179. assert_equal '/user/download/file.jpg',
  180. rs.generate(
  181. :controller => "user", :action => "download", :file => "file.jpg")
  182. assert_equal(
  183. {:controller => "user", :action => "download", :file => "file.jpg"},
  184. rs.recognize_path("/user/download/file.jpg"))
  185. end
  186. def test_basic_named_route
  187. rs.add_named_route :home, '', :controller => 'content', :action => 'list'
  188. x = setup_for_named_route
  189. assert_equal("http://named.route.test/",
  190. x.send(:home_url))
  191. end
  192. def test_basic_named_route_with_relative_url_root
  193. rs.add_named_route :home, '', :controller => 'content', :action => 'list'
  194. x = setup_for_named_route
  195. x.relative_url_root="/foo"
  196. assert_equal("http://named.route.test/foo/",
  197. x.send(:home_url))
  198. assert_equal "/foo/", x.send(:home_path)
  199. end
  200. def test_named_route_with_option
  201. rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page'
  202. x = setup_for_named_route
  203. assert_equal("http://named.route.test/page/new%20stuff",
  204. x.send(:page_url, :title => 'new stuff'))
  205. end
  206. def test_named_route_with_default
  207. rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
  208. x = setup_for_named_route
  209. assert_equal("http://named.route.test/page/AboutRails",
  210. x.send(:page_url, :title => "AboutRails"))
  211. end
  212. def test_named_route_with_nested_controller
  213. rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index'
  214. x = setup_for_named_route
  215. assert_equal("http://named.route.test/admin/user",
  216. x.send(:users_url))
  217. end
  218. uses_mocha "named route optimisation" do
  219. def test_optimised_named_route_call_never_uses_url_for
  220. rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index'
  221. rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
  222. x = setup_for_named_route
  223. x.expects(:url_for).never
  224. x.send(:users_url)
  225. x.send(:users_path)
  226. x.send(:user_url, 2, :foo=>"bar")
  227. x.send(:user_path, 3, :bar=>"foo")
  228. end
  229. def test_optimised_named_route_with_host
  230. rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
  231. x = setup_for_named_route
  232. x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
  233. x.send(:pages_url)
  234. end
  235. end
  236. def setup_for_named_route
  237. klass = Class.new(MockController)
  238. rs.install_helpers(klass)
  239. klass.new(rs)
  240. end
  241. def test_named_route_without_hash
  242. rs.draw do |map|
  243. map.normal ':controller/:action/:id'
  244. end
  245. end
  246. def test_named_route_root
  247. rs.draw do |map|
  248. map.root :controller => "hello"
  249. end
  250. x = setup_for_named_route
  251. assert_equal("http://named.route.test/", x.send(:root_url))
  252. assert_equal("/", x.send(:root_path))
  253. end
  254. def test_named_route_with_regexps
  255. rs.draw do |map|
  256. map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
  257. :year => /\d+/, :month => /\d+/, :day => /\d+/
  258. map.connect ':controller/:action/:id'
  259. end
  260. x = setup_for_named_route
  261. # assert_equal(
  262. # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
  263. # x.send(:article_url, :title => 'hi')
  264. # )
  265. assert_equal(
  266. "http://named.route.test/page/2005/6/10/hi",
  267. x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
  268. )
  269. end
  270. def test_changing_controller
  271. assert_equal '/admin/stuff/show/10', rs.generate(
  272. {:controller => 'stuff', :action => 'show', :id => 10},
  273. {:controller => 'admin/user', :action => 'index'}
  274. )
  275. end
  276. def test_paths_escaped
  277. rs.draw do |map|
  278. map.path 'file/*path', :controller => 'content', :action => 'show_file'
  279. map.connect ':controller/:action/:id'
  280. end
  281. # No + to space in URI escaping, only for query params.
  282. results = rs.recognize_path "/file/hello+world/how+are+you%3F"
  283. assert results, "Recognition should have succeeded"
  284. assert_equal ['hello+world', 'how+are+you?'], results[:path]
  285. # Use %20 for space instead.
  286. results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
  287. assert results, "Recognition should have succeeded"
  288. assert_equal ['hello world', 'how are you?'], results[:path]
  289. results = rs.recognize_path "/file"
  290. assert results, "Recognition should have succeeded"
  291. assert_equal [], results[:path]
  292. end
  293. def test_paths_slashes_unescaped_with_ordered_parameters
  294. rs.add_named_route :path, '/file/*path', :controller => 'content'
  295. # No / to %2F in URI, only for query params.
  296. x = setup_for_named_route
  297. assert_equal("/file/hello/world", x.send(:path_path, 'hello/world'))
  298. end
  299. def test_non_controllers_cannot_be_matched
  300. rs.draw do |map|
  301. map.connect ':controller/:action/:id'
  302. end
  303. assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
  304. end
  305. def test_paths_do_not_accept_defaults
  306. assert_raises(ActionController::RoutingError) do
  307. rs.draw do |map|
  308. map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
  309. map.connect ':controller/:action/:id'
  310. end
  311. end
  312. rs.draw do |map|
  313. map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => []
  314. map.connect ':controller/:action/:id'
  315. end
  316. end
  317. def test_should_list_options_diff_when_routing_requirements_dont_match
  318. rs.draw do |map|
  319. map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
  320. end
  321. exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
  322. assert_match /^post_url failed to generate/, exception.message
  323. from_match = exception.message.match(/from \{[^\}]+\}/).to_s
  324. assert_match /:bad_param=>"foo"/, from_match
  325. assert_match /:action=>"show"/, from_match
  326. assert_match /:controller=>"post"/, from_match
  327. expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s
  328. assert_no_match /:bad_param=>"foo"/, expected_match
  329. assert_match /:action=>"show"/, expected_match
  330. assert_match /:controller=>"post"/, expected_match
  331. diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s
  332. assert_match /:bad_param=>"foo"/, diff_match
  333. assert_no_match /:action=>"show"/, diff_match
  334. assert_no_match /:controller=>"post"/, diff_match
  335. end
  336. # this specifies the case where your formerly would get a very confusing error message with an empty diff
  337. def test_should_have_better_error_message_when_options_diff_is_empty
  338. rs.draw do |map|
  339. map.content '/content/:query', :controller => 'content', :action => 'show'
  340. end
  341. exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") }
  342. assert_match %r[:action=>"show"], exception.message
  343. assert_match %r[:controller=>"content"], exception.message
  344. assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message
  345. assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message
  346. end
  347. def test_dynamic_path_allowed
  348. rs.draw do |map|
  349. map.connect '*path', :controller => 'content', :action => 'show_file'
  350. end
  351. assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo))
  352. end
  353. def test_dynamic_recall_paths_allowed
  354. rs.draw do |map|
  355. map.connect '*path', :controller => 'content', :action => 'show_file'
  356. end
  357. recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo))
  358. assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path)
  359. end
  360. def test_backwards
  361. rs.draw do |map|
  362. map.connect 'page/:id/:action', :controller => 'pages', :action => 'show'
  363. map.connect ':controller/:action/:id'
  364. end
  365. assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
  366. assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show')
  367. assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo')
  368. end
  369. def test_route_with_fixnum_default
  370. rs.draw do |map|
  371. map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
  372. map.connect ':controller/:action/:id'
  373. end
  374. assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page')
  375. assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1)
  376. assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1')
  377. assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10)
  378. assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page"))
  379. assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1"))
  380. assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10"))
  381. end
  382. # For newer revision
  383. def test_route_with_text_default
  384. rs.draw do |map|
  385. map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
  386. map.connect ':controller/:action/:id'
  387. end
  388. assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
  389. assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
  390. token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
  391. escaped_token = CGI::escape(token)
  392. assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token)
  393. assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}"))
  394. end
  395. def test_action_expiry
  396. assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
  397. end
  398. def test_recognition_with_uppercase_controller_name
  399. assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content"))
  400. assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list"))
  401. assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10"))
  402. # these used to work, before the routes rewrite, but support for this was pulled in the new version...
  403. #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed"))
  404. #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed"))
  405. end
  406. def test_requirement_should_prevent_optional_id
  407. rs.draw do |map|
  408. map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
  409. end
  410. assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10)
  411. assert_raises ActionController::RoutingError do
  412. rs.generate(:controller => 'post', :action => 'show')
  413. end
  414. end
  415. def test_both_requirement_and_optional
  416. rs.draw do |map|
  417. map.blog('test/:year', :controller => 'post', :action => 'show',
  418. :defaults => { :year => nil },
  419. :requirements => { :year => /\d{4}/ }
  420. )
  421. map.connect ':controller/:action/:id'
  422. end
  423. assert_equal '/test', rs.generate(:controller => 'post', :action => 'show')
  424. assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil)
  425. x = setup_for_named_route
  426. assert_equal("http://named.route.test/test",
  427. x.send(:blog_url))
  428. end
  429. def test_set_to_nil_forgets
  430. rs.draw do |map|
  431. map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
  432. map.connect ':controller/:action/:id'
  433. end
  434. assert_equal '/pages/2005',
  435. rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
  436. assert_equal '/pages/2005/6',
  437. rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
  438. assert_equal '/pages/2005/6/12',
  439. rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
  440. assert_equal '/pages/2005/6/4',
  441. rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
  442. assert_equal '/pages/2005/6',
  443. rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
  444. assert_equal '/pages/2005',
  445. rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
  446. end
  447. def test_url_with_no_action_specified
  448. rs.draw do |map|
  449. map.connect '', :controller => 'content'
  450. map.connect ':controller/:action/:id'
  451. end
  452. assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
  453. assert_equal '/', rs.generate(:controller => 'content')
  454. end
  455. def test_named_url_with_no_action_specified
  456. rs.draw do |map|
  457. map.home '', :controller => 'content'
  458. map.connect ':controller/:action/:id'
  459. end
  460. assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
  461. assert_equal '/', rs.generate(:controller => 'content')
  462. x = setup_for_named_route
  463. assert_equal("http://named.route.test/",
  464. x.send(:home_url))
  465. end
  466. def test_url_generated_when_forgetting_action
  467. [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
  468. rs.draw do |map|
  469. map.home '', hash
  470. map.connect ':controller/:action/:id'
  471. end
  472. assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
  473. assert_equal '/', rs.generate({:controller => 'content'})
  474. assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
  475. end
  476. end
  477. def test_named_route_method
  478. rs.draw do |map|
  479. map.categories 'categories', :controller => 'content', :action => 'categories'
  480. map.connect ':controller/:action/:id'
  481. end
  482. assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories')
  483. assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
  484. end
  485. def test_named_routes_array
  486. test_named_route_method
  487. assert_equal [:categories], rs.named_routes.names
  488. end
  489. def test_nil_defaults
  490. rs.draw do |map|
  491. map.connect 'journal',
  492. :controller => 'content',
  493. :action => 'list_journal',
  494. :date => nil, :user_id => nil
  495. map.connect ':controller/:action/:id'
  496. end
  497. assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
  498. end
  499. def setup_request_method_routes_for(method)
  500. @request = ActionController::TestRequest.new
  501. @request.env["REQUEST_METHOD"] = method
  502. @request.request_uri = "/match"
  503. rs.draw do |r|
  504. r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
  505. r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
  506. r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
  507. r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
  508. end
  509. end
  510. %w(GET POST PUT DELETE).each do |request_method|
  511. define_method("test_request_method_recognized_with_#{request_method}") do
  512. begin
  513. Object.const_set(:BooksController, Class.new(ActionController::Base))
  514. setup_request_method_routes_for(request_method)
  515. assert_nothing_raised { rs.recognize(@request) }
  516. assert_equal request_method.downcase, @request.path_parameters[:action]
  517. ensure
  518. Object.send(:remove_const, :BooksController) rescue nil
  519. end
  520. end
  521. end
  522. def test_subpath_recognized
  523. Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
  524. rs.draw do |r|
  525. r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
  526. r.connect '/items/:id/:action', :controller => 'subpath_books'
  527. r.connect '/posts/new/:action', :controller => 'subpath_books'
  528. r.connect '/posts/:id', :controller => 'subpath_books', :action => "show"
  529. end
  530. hash = rs.recognize_path "/books/17/edit"
  531. assert_not_nil hash
  532. assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]]
  533. hash = rs.recognize_path "/items/3/complete"
  534. assert_not_nil hash
  535. assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]]
  536. hash = rs.recognize_path "/posts/new/preview"
  537. assert_not_nil hash
  538. assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]]
  539. hash = rs.recognize_path "/posts/7"
  540. assert_not_nil hash
  541. assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]]
  542. ensure
  543. Object.send(:remove_const, :SubpathBooksController) rescue nil
  544. end
  545. def test_subpath_generated
  546. Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
  547. rs.draw do |r|
  548. r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
  549. r.connect '/items/:id/:action', :controller => 'subpath_books'
  550. r.connect '/posts/new/:action', :controller => 'subpath_books'
  551. end
  552. assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit")
  553. assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete")
  554. assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview")
  555. ensure
  556. Object.send(:remove_const, :SubpathBooksController) rescue nil
  557. end
  558. def test_failed_requirements_raises_exception_with_violated_requirements
  559. rs.draw do |r|
  560. r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/}
  561. end
  562. x = setup_for_named_route
  563. assert_raises(ActionController::RoutingError) do
  564. x.send(:foo_with_requirement_url, "I am Against the requirements")
  565. end
  566. end
  567. end
  568. class SegmentTest < Test::Unit::TestCase
  569. def test_first_segment_should_interpolate_for_structure
  570. s = ROUTING::Segment.new
  571. def s.interpolation_statement(array) 'hello' end
  572. assert_equal 'hello', s.continue_string_structure([])
  573. end
  574. def test_interpolation_statement
  575. s = ROUTING::StaticSegment.new
  576. s.value = "Hello"
  577. assert_equal "Hello", eval(s.interpolation_statement([]))
  578. assert_equal "HelloHello", eval(s.interpolation_statement([s]))
  579. s2 = ROUTING::StaticSegment.new
  580. s2.value = "-"
  581. assert_equal "Hello-Hello", eval(s.interpolation_statement([s, s2]))
  582. s3 = ROUTING::StaticSegment.new
  583. s3.value = "World"
  584. assert_equal "Hello-World", eval(s3.interpolation_statement([s, s2]))
  585. end
  586. end
  587. class StaticSegmentTest < Test::Unit::TestCase
  588. def test_interpolation_chunk_should_respect_raw
  589. s = ROUTING::StaticSegment.new
  590. s.value = 'Hello World'
  591. assert ! s.raw?
  592. assert_equal 'Hello%20World', s.interpolation_chunk
  593. s.raw = true
  594. assert s.raw?
  595. assert_equal 'Hello World', s.interpolation_chunk
  596. end
  597. def test_regexp_chunk_should_escape_specials
  598. s = ROUTING::StaticSegment.new
  599. s.value = 'Hello*World'
  600. assert_equal 'Hello\*World', s.regexp_chunk
  601. s.value = 'HelloWorld'
  602. assert_equal 'HelloWorld', s.regexp_chunk
  603. end
  604. def test_regexp_chunk_should_add_question_mark_for_optionals
  605. s = ROUTING::StaticSegment.new
  606. s.value = "/"
  607. s.is_optional = true
  608. assert_equal "/?", s.regexp_chunk
  609. s.value = "hello"
  610. assert_equal "(?:hello)?", s.regexp_chunk
  611. end
  612. end
  613. class DynamicSegmentTest < Test::Unit::TestCase
  614. def segment
  615. unless @segment
  616. @segment = ROUTING::DynamicSegment.new
  617. @segment.key = :a
  618. end
  619. @segment
  620. end
  621. def test_extract_value
  622. s = ROUTING::DynamicSegment.new
  623. s.key = :a
  624. hash = {:a => '10', :b => '20'}
  625. assert_equal '10', eval(s.extract_value)
  626. hash = {:b => '20'}
  627. assert_equal nil, eval(s.extract_value)
  628. s.default = '20'
  629. assert_equal '20', eval(s.extract_value)
  630. end
  631. def test_default_local_name
  632. assert_equal 'a_value', segment.local_name,
  633. "Unexpected name -- all value_check tests will fail!"
  634. end
  635. def test_presence_value_check
  636. a_value = 10
  637. assert eval(segment.value_check)
  638. end
  639. def test_regexp_value_check_rejects_nil
  640. segment.regexp = /\d+/
  641. a_value = nil
  642. assert ! eval(segment.value_check)
  643. end
  644. def test_optional_regexp_value_check_should_accept_nil
  645. segment.regexp = /\d+/
  646. segment.is_optional = true
  647. a_value = nil
  648. assert eval(segment.value_check)
  649. end
  650. def test_regexp_value_check_rejects_no_match
  651. segment.regexp = /\d+/
  652. a_value = "Hello20World"
  653. assert ! eval(segment.value_check)
  654. a_value = "20Hi"
  655. assert ! eval(segment.value_check)
  656. end
  657. def test_regexp_value_check_accepts_match
  658. segment.regexp = /\d+/
  659. a_value = "30"
  660. assert eval(segment.value_check)
  661. end
  662. def test_value_check_fails_on_nil
  663. a_value = nil
  664. assert ! eval(segment.value_check)
  665. end
  666. def test_optional_value_needs_no_check
  667. segment.is_optional = true
  668. a_value = nil
  669. assert_equal nil, segment.value_check
  670. end
  671. def test_regexp_value_check_should_accept_match_with_default
  672. segment.regexp = /\d+/
  673. segment.default = '200'
  674. a_value = '100'
  675. assert eval(segment.value_check)
  676. end
  677. def test_expiry_should_not_trigger_once_expired
  678. expired = true
  679. hash = merged = {:a => 2, :b => 3}
  680. options = {:b => 3}
  681. expire_on = Hash.new { raise 'No!!!' }
  682. eval(segment.expiry_statement)
  683. rescue RuntimeError
  684. flunk "Expiry check should not have occurred!"
  685. end
  686. def test_expiry_should_occur_according_to_expire_on
  687. expired = false
  688. hash = merged = {:a => 2, :b => 3}
  689. options = {:b => 3}
  690. expire_on = {:b => true, :a => false}
  691. eval(segment.expiry_statement)
  692. assert !expired
  693. assert_equal({:a => 2, :b => 3}, hash)
  694. expire_on = {:b => true, :a => true}
  695. eval(segment.expiry_statement)
  696. assert expired
  697. assert_equal({:b => 3}, hash)
  698. end
  699. def test_extraction_code_should_return_on_nil
  700. hash = merged = {:b => 3}
  701. options = {:b => 3}
  702. a_value = nil
  703. # Local jump because of return inside eval.
  704. assert_raises(LocalJumpError) { eval(segment.extraction_code) }
  705. end
  706. def test_extraction_code_should_return_on_mismatch
  707. segment.regexp = /\d+/
  708. hash = merged = {:a => 'Hi', :b => '3'}
  709. options = {:b => '3'}
  710. a_value = nil
  711. # Local jump because of return inside eval.
  712. assert_raises(LocalJumpError) { eval(segment.extraction_code) }
  713. end
  714. def test_extraction_code_should_accept_value_and_set_local
  715. hash = merged = {:a => 'Hi', :b => '3'}
  716. options = {:b => '3'}
  717. a_value = nil
  718. expired = true
  719. eval(segment.extraction_code)
  720. assert_equal 'Hi', a_value
  721. end
  722. def test_extraction_should_work_without_value_check
  723. segment.default = 'hi'
  724. hash = merged = {:b => '3'}
  725. options = {:b => '3'}
  726. a_value = nil
  727. expired = true
  728. eval(segment.extraction_code)
  729. assert_equal 'hi', a_value
  730. end
  731. def test_extraction_code_should_perform_expiry
  732. expired = false
  733. hash = merged = {:a => 'Hi', :b => '3'}
  734. options = {:b => '3'}
  735. expire_on = {:a => true}
  736. a_value = nil
  737. eval(segment.extraction_code)
  738. assert_equal 'Hi', a_value
  739. assert expired
  740. assert_equal options, hash
  741. end
  742. def test_interpolation_chunk_should_replace_value
  743. a_value = 'Hi'
  744. assert_equal a_value, eval(%("#{segment.interpolation_chunk}"))
  745. end
  746. def test_interpolation_chunk_should_accept_nil
  747. a_value = nil
  748. assert_equal '', eval(%("#{segment.interpolation_chunk('a_value')}"))
  749. end
  750. def test_value_regexp_should_be_nil_without_regexp
  751. assert_equal nil, segment.value_regexp
  752. end
  753. def test_value_regexp_should_match_exacly
  754. segment.regexp = /\d+/
  755. assert_no_match segment.value_regexp, "Hello 10 World"
  756. assert_no_match segment.value_regexp, "Hello 10"
  757. assert_no_match segment.value_regexp, "10 World"
  758. assert_match segment.value_regexp, "10"
  759. end
  760. def test_regexp_chunk_should_return_string
  761. segment.regexp = /\d+/
  762. assert_kind_of String, segment.regexp_chunk
  763. end
  764. def test_build_pattern_non_optional_with_no_captures
  765. # Non optional
  766. a_segment = ROUTING::DynamicSegment.new
  767. a_segment.regexp = /\d+/ #number_of_captures is 0
  768. assert_equal "(\\d+)stuff", a_segment.build_pattern('stuff')
  769. end
  770. def test_build_pattern_non_optional_with_captures
  771. # Non optional
  772. a_segment = ROUTING::DynamicSegment.new
  773. a_segment.regexp = /(\d+)(.*?)/ #number_of_captures is 2
  774. assert_equal "((\\d+)(.*?))stuff", a_segment.build_pattern('stuff')
  775. end
  776. def test_optionality_implied
  777. a_segment = ROUTING::DynamicSegment.new
  778. a_segment.key = :id
  779. assert a_segment.optionality_implied?
  780. a_segment.key = :action
  781. assert a_segment.optionality_implied?
  782. end
  783. def test_modifiers_must_be_handled_sensibly
  784. a_segment = ROUTING::DynamicSegment.new
  785. a_segment.regexp = /david|jamis/i
  786. assert_equal "((?i-mx:david|jamis))stuff", a_segment.build_pattern('stuff')
  787. a_segment.regexp = /david|jamis/x
  788. assert_equal "((?x-mi:david|jamis))stuff", a_segment.build_pattern('stuff')
  789. a_segment.regexp = /david|jamis/
  790. assert_equal "(david|jamis)stuff", a_segment.build_pattern('stuff')
  791. end
  792. end
  793. class ControllerSegmentTest < Test::Unit::TestCase
  794. def test_regexp_should_only_match_possible_controllers
  795. ActionController::Routing.with_controllers %w(admin/accounts admin/users account pages) do
  796. cs = ROUTING::ControllerSegment.new :controller
  797. regexp = %r{\A#{cs.regexp_chunk}\Z}
  798. ActionController::Routing.possible_controllers.each do |name|
  799. assert_match regexp, name
  800. assert_no_match regexp, "#{name}_fake"
  801. match = regexp.match name
  802. assert_equal name, match[1]
  803. end
  804. end
  805. end
  806. end
  807. uses_mocha 'RouteTest' do
  808. class MockController
  809. attr_accessor :routes
  810. def initialize(routes)
  811. self.routes = routes
  812. end
  813. def url_for(options)
  814. only_path = options.delete(:only_path)
  815. port = options.delete(:port) || 80
  816. port_string = port == 80 ? '' : ":#{port}"
  817. host = options.delete(:host) || "named.route.test"
  818. anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
  819. path = routes.generate(options)
  820. only_path ? "#{path}#{anchor}" : "http://#{host}#{port_string}#{path}#{anchor}"
  821. end
  822. def request
  823. @request ||= MockRequest.new(:host => "named.route.test", :method => :get)
  824. end
  825. def relative_url_root=(value)
  826. request.relative_url_root=value
  827. end
  828. end
  829. class MockRequest
  830. attr_accessor :path, :path_parameters, :host, :subdomains, :domain,
  831. :method, :relative_url_root
  832. def initialize(values={})
  833. values.each { |key, value| send("#{key}=", value) }
  834. if values[:host]
  835. subdomain, self.domain = values[:host].split(/\./, 2)
  836. self.subdomains = [subdomain]
  837. end
  838. end
  839. def protocol
  840. "http://"
  841. end
  842. def host_with_port
  843. (subdomains * '.') + '.' + domain
  844. end
  845. end
  846. class RouteTest < Test::Unit::TestCase
  847. def setup
  848. @route = ROUTING::Route.new
  849. end
  850. def slash_segment(is_optional = false)
  851. returning ROUTING::DividerSegment.new('/') do |s|
  852. s.is_optional = is_optional
  853. end
  854. end
  855. def default_route
  856. unless defined?(@default_route)
  857. @default_route = ROUTING::Route.new
  858. @default_route.segments << (s = ROUTING::StaticSegment.new)
  859. s.value = '/'
  860. s.raw = true
  861. @default_route.segments << (s = ROUTING::DynamicSegment.new)
  862. s.key = :controller
  863. @default_route.segments << slash_segment(:optional)
  864. @default_route.segments << (s = ROUTING::DynamicSegment.new)
  865. s.key = :action
  866. s.default = 'index'
  867. s.is_optional = true
  868. @default_route.segments << slash_segment(:optional)
  869. @default_route.segments << (s = ROUTING::DynamicSegment.new)
  870. s.key = :id
  871. s.is_optional = true
  872. @default_route.segments << slash_segment(:optional)
  873. end
  874. @default_route
  875. end
  876. def test_default_route_recognition
  877. expected = {:controller => 'accounts', :action => 'show', :id => '10'}
  878. assert_equal expected, default_route.recognize('/accounts/show/10')
  879. assert_equal expected, default_route.recognize('/accounts/show/10/')
  880. expected[:id] = 'jamis'
  881. assert_equal expected, default_route.recognize('/accounts/show/jamis/')
  882. expected.delete :id
  883. assert_equal expected, default_route.recognize('/accounts/show')
  884. assert_equal expected, default_route.recognize('/accounts/show/')
  885. expected[:action] = 'index'
  886. assert_equal expected, default_route.recognize('/accounts/')
  887. assert_equal expected, default_route.recognize('/accounts')
  888. assert_equal nil, default_route.recognize('/')
  889. assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free')
  890. end
  891. def test_default_route_should_omit_default_action
  892. o = {:controller => 'accounts', :action => 'index'}
  893. assert_equal '/accounts', default_route.generate(o, o, {})
  894. end
  895. def test_default_route_should_include_default_action_when_id_present
  896. o = {:controller => 'accounts', :action => 'index', :id => '20'}
  897. assert_equal '/accounts/index/20', default_route.generate(o, o, {})
  898. end
  899. def test_default_route_should_work_with_action_but_no_id
  900. o = {:controller => 'accounts', :action => 'list_all'}
  901. assert_equal '/accounts/list_all', default_route.generate(o, o, {})
  902. end
  903. def test_default_route_should_uri_escape_pluses
  904. expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' }
  905. assert_equal expected, default_route.recognize('/accounts/show/hello world')
  906. assert_equal expected, default_route.recognize('/accounts/show/hello%20world')
  907. assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {})
  908. expected[:id] = 'hello+world'
  909. assert_equal expected, default_route.recognize('/accounts/show/hello+world')
  910. assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld')
  911. assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {})
  912. end
  913. def test_matches_controller_and_action
  914. # requirement_for should only be called for the action and controller _once_
  915. @route.expects(:requirement_for).with(:controller).times(1).returns('pages')
  916. @route.expects(:requirement_for).with(:action).times(1).returns('show')
  917. @route.requirements = {:controller => 'pages', :action => 'show'}
  918. assert @route.matches_controller_and_action?('pages', 'show')
  919. assert !@route.matches_controller_and_action?('not_pages', 'show')
  920. assert !@route.matches_controller_and_action?('pages', 'not_show')
  921. end
  922. def test_parameter_shell
  923. page_url = ROUTING::Route.new
  924. page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/}
  925. assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell)
  926. end
  927. def test_defaults
  928. route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html"
  929. assert_equal(
  930. { :controller => "users", :action => "show", :format => "html" },
  931. route.defaults)
  932. end
  933. def test_builder_complains_without_controller
  934. assert_raises(ArgumentError) do
  935. ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index"
  936. end
  937. end
  938. def test_significant_keys_for_default_route
  939. keys = default_route.significant_keys.sort_by {|k| k.to_s }
  940. assert_equal [:action, :controller, :id], keys
  941. end
  942. def test_significant_keys
  943. user_url = ROUTING::Route.new
  944. user_url.segments << (s = ROUTING::StaticSegment.new)
  945. s.value = '/'
  946. s.raw = true
  947. user_url.segments << (s = ROUTING::StaticSegment.new)
  948. s.value = 'user'
  949. user_url.segments << (s = ROUTING::StaticSegment.new)
  950. s.value = '/'
  951. s.raw = true
  952. s.is_optional = true
  953. user_url.segments << (s = ROUTING::DynamicSegment.new)
  954. s.key = :user
  955. user_url.segments << (s = ROUTING::StaticSegment.new)
  956. s.value = '/'
  957. s.raw = true
  958. s.is_optional = true
  959. user_url.requirements = {:controller => 'users', :action => 'show'}
  960. keys = user_url.significant_keys.sort_by { |k| k.to_s }
  961. assert_equal [:action, :controller, :user], keys
  962. end
  963. def test_build_empty_query_string
  964. assert_equal '', @route.build_query_string({})
  965. end
  966. def test_build_query_string_with_nil_value
  967. assert_equal '', @route.build_query_string({:x => nil})
  968. end
  969. def test_simple_build_query_string
  970. assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2'))
  971. end
  972. def test_convert_ints_build_query_string
  973. assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2))
  974. end
  975. def test_escape_spaces_build_query_string
  976. assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world'))
  977. end
  978. def test_expand_array_build_query_string
  979. assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2]))
  980. end
  981. def test_escape_spaces_build_query_string_selected_keys
  982. assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x]))
  983. end
  984. private
  985. def order_query_string(qs)
  986. '?' + qs[1..-1].split('&').sort.join('&')
  987. end
  988. end
  989. end # uses_mocha
  990. class RouteBuilderTest < Test::Unit::TestCase
  991. def builder
  992. @builder ||= ROUTING::RouteBuilder.new
  993. end
  994. def build(path, options)
  995. builder.build(path, options)
  996. end
  997. def test_options_should_not_be_modified
  998. requirements1 = { :id => /\w+/, :controller => /(?:[a-z](?:-?[a-z]+)*)/ }
  999. requirements2 = requirements1.dup
  1000. assert_equal requirements1, requirements2
  1001. with_options(:controller => 'folder',
  1002. :requirements => requirements2) do |m|
  1003. m.build 'folders/new', :action => 'new'
  1004. end
  1005. assert_equal requirements1, requirements2
  1006. end
  1007. def test_segment_for_static
  1008. segment, rest = builder.segment_for 'ulysses'
  1009. assert_equal '', rest
  1010. assert_kind_of ROUTING::StaticSegment, segment
  1011. assert_equal 'ulysses', segment.value
  1012. end
  1013. def test_segment_for_action
  1014. segment, rest = builder.segment_for ':action'
  1015. assert_equal '', rest
  1016. assert_kind_of ROUTING::DynamicSegment, segment
  1017. assert_equal :action, segment.key
  1018. assert_equal 'index', segment.default
  1019. end
  1020. def test_segment_for_dynamic
  1021. segment, rest = builder.segment_for ':login'
  1022. assert_equal '', rest
  1023. assert_kind_of ROUTING::DynamicSegment, segment
  1024. assert_equal :login, segment.key
  1025. assert_equal nil, segment.default
  1026. assert ! segment.optional?
  1027. end
  1028. def test_segment_for_with_rest
  1029. segment, rest = builder.segment_for ':login/:action'
  1030. assert_equal :login, segment.key
  1031. assert_equal '/:action', rest
  1032. segment, rest = builder.segment_for rest
  1033. assert_equal '/', segment.value
  1034. assert_equal ':action', rest
  1035. segment, rest = builder.segment_for rest
  1036. assert_equal :action, segment.key
  1037. assert_equal '', rest
  1038. end
  1039. def test_segments_for
  1040. segments = builder.segments_for_route_path '/:controller/:action/:id'
  1041. assert_kind_of ROUTING::DividerSegment, segments[0]
  1042. assert_equal '/', segments[2].value
  1043. assert_kind_of ROUTING::DynamicSegment, segments[1]
  1044. assert_equal :controller, segments[1].key
  1045. assert_kind_of ROUTING::DividerSegment, segments[2]
  1046. assert_equal '/', segments[2].value
  1047. assert_kind_of ROUTING::DynamicSegment, segments[3]
  1048. assert_equal :action, segments[3].key
  1049. assert_kind_of ROUTING::DividerSegment, segments[4]
  1050. assert_equal '/', segments[4].value
  1051. assert_kind_of ROUTING::DynamicSegment, segments[5]
  1052. assert_equal :id, segments[5].key
  1053. end
  1054. def test_segment_for_action
  1055. s, r = builder.segment_for(':action/something/else')
  1056. assert_equal '/something/else', r
  1057. assert_equal :action, s.key
  1058. end
  1059. def test_action_default_should_not_trigger_on_prefix
  1060. s, r = builder.segment_for ':action_name/something/else'
  1061. assert_equal '/something/else', r
  1062. assert_equal :action_name, s.key
  1063. assert_equal nil, s.default
  1064. end
  1065. def test_divide_route_options
  1066. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  1067. defaults, requirements = builder.divide_route_options(segments,
  1068. :action => 'buy', :person => /\w+/, :car => /\w+/,
  1069. :defaults => {:person => nil, :car => nil}
  1070. )
  1071. assert_equal({:action => 'buy', :person => nil, :car => nil}, defaults)
  1072. assert_equal({:person => /\w+/, :car => /\w+/}, requirements)
  1073. end
  1074. def test_assign_route_options
  1075. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  1076. defaults = {:action => 'buy', :person => nil, :car => nil}
  1077. requirements = {:person => /\w+/, :car => /\w+/}
  1078. route_requirements = builder.assign_route_options(segments, defaults, requirements)
  1079. assert_equal({}, route_requirements)
  1080. assert_equal :action, segments[3].key
  1081. assert_equal 'buy', segments[3].default
  1082. assert_equal :person, segments[5].key
  1083. assert_equal %r/\w+/, segments[5].regexp
  1084. assert segments[5].optional?
  1085. assert_equal :car, segments[7].key
  1086. assert_equal %r/\w+/, segments[7].regexp
  1087. assert segments[7].optional?
  1088. end
  1089. def test_assign_route_options_with_anchor_chars
  1090. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  1091. defaults = {:action => 'buy', :person => nil, :car => nil}
  1092. requirements = {:person => /\w+/, :car => /^\w+$/}
  1093. assert_raises ArgumentError do
  1094. route_requirements = builder.assign_route_options(segments, defaults, requirements)
  1095. end
  1096. requirements[:car] = /[^\/]+/
  1097. route_requirements = builder.assign_route_options(segments, defaults, requirements)
  1098. end
  1099. def test_optional_segments_preceding_required_segments
  1100. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  1101. defaults = {:action => 'buy', :person => nil, :car => "model-t"}
  1102. assert builder.assign_route_options(segments, defaults, {}).empty?
  1103. 0.upto(1) { |i| assert !segments[i].optional?, "segment #{i} is optional and it shouldn't be" }
  1104. assert segments[2].optional?
  1105. assert_equal nil, builder.warn_output # should only warn on the :person segment
  1106. end
  1107. def test_segmentation_of_dot_path
  1108. segments = builder.segments_for_route_path '/books/:action.rss'
  1109. assert builder.assign_route_options(segments, {}, {}).empty?
  1110. assert_equal 6, segments.length # "/", "books", "/", ":action", ".", "rss"
  1111. assert !segments.any? { |seg| seg.optional? }
  1112. end
  1113. def test_segmentation_of_dynamic_dot_path
  1114. segments = builder.segments_for_route_path '/books/:action.:format'
  1115. assert builder.assign_route_options(segments, {}, {}).empty?
  1116. assert_equal 6, segments.length # "/", "books", "/", ":action", ".", ":format"
  1117. assert !segments.any? { |seg| seg.optional? }
  1118. assert_kind_of ROUTING::DynamicSegment, segments.last
  1119. end
  1120. def test_assignment_of_default_options
  1121. segments = builder.segments_for_route_path '/:controller/:action/:id/'
  1122. action, id = segments[-4], segments[-2]
  1123. assert_equal :action, action.key
  1124. assert_equal :id, id.key
  1125. assert ! action.optional?
  1126. assert ! id.optional?
  1127. builder.assign_default_route_options(segments)
  1128. assert_equal 'index', action.default
  1129. assert action.optional?
  1130. assert id.optional?
  1131. end
  1132. def test_assignment_of_default_options_respects_existing_defaults
  1133. segments = builder.segments_for_route_path '/:controller/:action/:id/'
  1134. action, id = s

Large files files are truncated, but you can click here to view the full file