PageRenderTime 49ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://github.com/tolsen/limeberry
Ruby | 2013 lines | 1604 code | 388 blank | 21 comment | 6 complexity | 5606392576d3df0dffa7ad7982606fb0 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.0

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

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

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