PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/bricooke/my-biz-expenses
Ruby | 440 lines | 407 code | 29 blank | 4 comment | 1 complexity | e95a93c2d97716af644b5283475213f7 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, BSD-3-Clause
  1. require File.dirname(__FILE__) + '/../abstract_unit'
  2. require 'action_controller/cgi_process'
  3. require 'action_controller/cgi_ext/cgi_ext'
  4. require 'stringio'
  5. class CGITest < Test::Unit::TestCase
  6. def setup
  7. @query_string = "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
  8. @query_string_with_nil = "action=create_customer&full_name="
  9. @query_string_with_array = "action=create_customer&selected[]=1&selected[]=2&selected[]=3"
  10. @query_string_with_amps = "action=create_customer&name=Don%27t+%26+Does"
  11. @query_string_with_multiple_of_same_name =
  12. "action=update_order&full_name=Lau%20Taarnskov&products=4&products=2&products=3"
  13. @query_string_with_many_equal = "action=create_customer&full_name=abc=def=ghi"
  14. @query_string_without_equal = "action"
  15. @query_string_with_many_ampersands =
  16. "&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
  17. @query_string_with_empty_key = "action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save"
  18. end
  19. def test_query_string
  20. assert_equal(
  21. { "action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"},
  22. CGIMethods.parse_query_parameters(@query_string)
  23. )
  24. end
  25. def test_deep_query_string
  26. expected = {'x' => {'y' => {'z' => '10'}}}
  27. assert_equal(expected, CGIMethods.parse_query_parameters('x[y][z]=10'))
  28. end
  29. def test_deep_query_string_with_array
  30. assert_equal({'x' => {'y' => {'z' => ['10']}}}, CGIMethods.parse_query_parameters('x[y][z][]=10'))
  31. assert_equal({'x' => {'y' => {'z' => ['10', '5']}}}, CGIMethods.parse_query_parameters('x[y][z][]=10&x[y][z][]=5'))
  32. end
  33. def test_deep_query_string_with_array_of_hash
  34. assert_equal({'x' => {'y' => [{'z' => '10'}]}}, CGIMethods.parse_query_parameters('x[y][][z]=10'))
  35. assert_equal({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][w]=10'))
  36. end
  37. def test_deep_query_string_with_array_of_hashes_with_one_pair
  38. assert_equal({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][z]=20'))
  39. assert_equal("10", CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][z]=20')["x"]["y"].first["z"])
  40. assert_equal("10", CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][z]=20').with_indifferent_access[:x][:y].first[:z])
  41. end
  42. def test_request_hash_parsing
  43. query = {
  44. "note[viewers][viewer][][type]" => ["User", "Group"],
  45. "note[viewers][viewer][][id]" => ["1", "2"]
  46. }
  47. expected = { "note" => { "viewers"=>{"viewer"=>[{ "id"=>"1", "type"=>"User"}, {"type"=>"Group", "id"=>"2"} ]} } }
  48. assert_equal(expected, CGIMethods.parse_request_parameters(query))
  49. end
  50. def test_deep_query_string_with_array_of_hashes_with_multiple_pairs
  51. assert_equal(
  52. {'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}},
  53. CGIMethods.parse_query_parameters('x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b')
  54. )
  55. end
  56. def test_query_string_with_nil
  57. assert_equal(
  58. { "action" => "create_customer", "full_name" => nil},
  59. CGIMethods.parse_query_parameters(@query_string_with_nil)
  60. )
  61. end
  62. def test_query_string_with_array
  63. assert_equal(
  64. { "action" => "create_customer", "selected" => ["1", "2", "3"]},
  65. CGIMethods.parse_query_parameters(@query_string_with_array)
  66. )
  67. end
  68. def test_query_string_with_amps
  69. assert_equal(
  70. { "action" => "create_customer", "name" => "Don't & Does"},
  71. CGIMethods.parse_query_parameters(@query_string_with_amps)
  72. )
  73. end
  74. def test_query_string_with_many_equal
  75. assert_equal(
  76. { "action" => "create_customer", "full_name" => "abc=def=ghi"},
  77. CGIMethods.parse_query_parameters(@query_string_with_many_equal)
  78. )
  79. end
  80. def test_query_string_without_equal
  81. assert_equal(
  82. { "action" => nil },
  83. CGIMethods.parse_query_parameters(@query_string_without_equal)
  84. )
  85. end
  86. def test_query_string_with_empty_key
  87. assert_equal(
  88. { "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
  89. CGIMethods.parse_query_parameters(@query_string_with_empty_key)
  90. )
  91. end
  92. def test_query_string_with_many_ampersands
  93. assert_equal(
  94. { "action" => "create_customer", "full_name" => "David Heinemeier Hansson"},
  95. CGIMethods.parse_query_parameters(@query_string_with_many_ampersands)
  96. )
  97. end
  98. def test_parse_params
  99. input = {
  100. "customers[boston][first][name]" => [ "David" ],
  101. "customers[boston][first][url]" => [ "http://David" ],
  102. "customers[boston][second][name]" => [ "Allan" ],
  103. "customers[boston][second][url]" => [ "http://Allan" ],
  104. "something_else" => [ "blah" ],
  105. "something_nil" => [ nil ],
  106. "something_empty" => [ "" ],
  107. "products[first]" => [ "Apple Computer" ],
  108. "products[second]" => [ "Pc" ],
  109. "" => [ 'Save' ]
  110. }
  111. expected_output = {
  112. "customers" => {
  113. "boston" => {
  114. "first" => {
  115. "name" => "David",
  116. "url" => "http://David"
  117. },
  118. "second" => {
  119. "name" => "Allan",
  120. "url" => "http://Allan"
  121. }
  122. }
  123. },
  124. "something_else" => "blah",
  125. "something_empty" => "",
  126. "something_nil" => "",
  127. "products" => {
  128. "first" => "Apple Computer",
  129. "second" => "Pc"
  130. }
  131. }
  132. assert_equal expected_output, CGIMethods.parse_request_parameters(input)
  133. end
  134. def test_parse_params_from_multipart_upload
  135. mockup = Struct.new(:content_type, :original_filename, :read, :rewind)
  136. file = mockup.new('img/jpeg', 'foo.jpg')
  137. ie_file = mockup.new('img/jpeg', 'c:\\Documents and Settings\\foo\\Desktop\\bar.jpg')
  138. non_file_text_part = mockup.new('text/plain', '', 'abc')
  139. input = {
  140. "something" => [ StringIO.new("") ],
  141. "array_of_stringios" => [[ StringIO.new("One"), StringIO.new("Two") ]],
  142. "mixed_types_array" => [[ StringIO.new("Three"), "NotStringIO" ]],
  143. "mixed_types_as_checkboxes[strings][nested]" => [[ file, "String", StringIO.new("StringIO")]],
  144. "ie_mixed_types_as_checkboxes[strings][nested]" => [[ ie_file, "String", StringIO.new("StringIO")]],
  145. "products[string]" => [ StringIO.new("Apple Computer") ],
  146. "products[file]" => [ file ],
  147. "ie_products[string]" => [ StringIO.new("Microsoft") ],
  148. "ie_products[file]" => [ ie_file ],
  149. "text_part" => [non_file_text_part]
  150. }
  151. expected_output = {
  152. "something" => "",
  153. "array_of_stringios" => ["One", "Two"],
  154. "mixed_types_array" => [ "Three", "NotStringIO" ],
  155. "mixed_types_as_checkboxes" => {
  156. "strings" => {
  157. "nested" => [ file, "String", "StringIO" ]
  158. },
  159. },
  160. "ie_mixed_types_as_checkboxes" => {
  161. "strings" => {
  162. "nested" => [ ie_file, "String", "StringIO" ]
  163. },
  164. },
  165. "products" => {
  166. "string" => "Apple Computer",
  167. "file" => file
  168. },
  169. "ie_products" => {
  170. "string" => "Microsoft",
  171. "file" => ie_file
  172. },
  173. "text_part" => "abc"
  174. }
  175. params = CGIMethods.parse_request_parameters(input)
  176. assert_equal expected_output, params
  177. # Lone filenames are preserved.
  178. assert_equal 'foo.jpg', params['mixed_types_as_checkboxes']['strings']['nested'].first.original_filename
  179. assert_equal 'foo.jpg', params['products']['file'].original_filename
  180. # But full Windows paths are reduced to their basename.
  181. assert_equal 'bar.jpg', params['ie_mixed_types_as_checkboxes']['strings']['nested'].first.original_filename
  182. assert_equal 'bar.jpg', params['ie_products']['file'].original_filename
  183. end
  184. def test_parse_params_with_file
  185. input = {
  186. "customers[boston][first][name]" => [ "David" ],
  187. "something_else" => [ "blah" ],
  188. "logo" => [ File.new(File.dirname(__FILE__) + "/cgi_test.rb").path ]
  189. }
  190. expected_output = {
  191. "customers" => {
  192. "boston" => {
  193. "first" => {
  194. "name" => "David"
  195. }
  196. }
  197. },
  198. "something_else" => "blah",
  199. "logo" => File.new(File.dirname(__FILE__) + "/cgi_test.rb").path,
  200. }
  201. assert_equal expected_output, CGIMethods.parse_request_parameters(input)
  202. end
  203. def test_parse_params_with_array
  204. input = { "selected[]" => [ "1", "2", "3" ] }
  205. expected_output = { "selected" => [ "1", "2", "3" ] }
  206. assert_equal expected_output, CGIMethods.parse_request_parameters(input)
  207. end
  208. def test_parse_params_with_non_alphanumeric_name
  209. input = { "a/b[c]" => %w(d) }
  210. expected = { "a/b" => { "c" => "d" }}
  211. assert_equal expected, CGIMethods.parse_request_parameters(input)
  212. end
  213. def test_parse_params_with_single_brackets_in_middle
  214. input = { "a/b[c]d" => %w(e) }
  215. expected = { "a/b" => {} }
  216. assert_equal expected, CGIMethods.parse_request_parameters(input)
  217. end
  218. def test_parse_params_with_separated_brackets
  219. input = { "a/b@[c]d[e]" => %w(f) }
  220. expected = { "a/b@" => { }}
  221. assert_equal expected, CGIMethods.parse_request_parameters(input)
  222. end
  223. def test_parse_params_with_separated_brackets_and_array
  224. input = { "a/b@[c]d[e][]" => %w(f) }
  225. expected = { "a/b@" => { }}
  226. assert_equal expected , CGIMethods.parse_request_parameters(input)
  227. end
  228. def test_parse_params_with_unmatched_brackets_and_array
  229. input = { "a/b@[c][d[e][]" => %w(f) }
  230. expected = { "a/b@" => { "c" => { }}}
  231. assert_equal expected, CGIMethods.parse_request_parameters(input)
  232. end
  233. def test_parse_params_with_nil_key
  234. input = { nil => nil, "test2" => %w(value1) }
  235. expected = { "test2" => "value1" }
  236. assert_equal expected, CGIMethods.parse_request_parameters(input)
  237. end
  238. end
  239. class MultipartCGITest < Test::Unit::TestCase
  240. FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart'
  241. def setup
  242. ENV['REQUEST_METHOD'] = 'POST'
  243. ENV['CONTENT_LENGTH'] = '0'
  244. ENV['CONTENT_TYPE'] = 'multipart/form-data, boundary=AaB03x'
  245. end
  246. def test_single_parameter
  247. params = process('single_parameter')
  248. assert_equal({ 'foo' => 'bar' }, params)
  249. end
  250. def test_text_file
  251. params = process('text_file')
  252. assert_equal %w(file foo), params.keys.sort
  253. assert_equal 'bar', params['foo']
  254. file = params['file']
  255. assert_kind_of StringIO, file
  256. assert_equal 'file.txt', file.original_filename
  257. assert_equal "text/plain\r", file.content_type
  258. assert_equal 'contents', file.read
  259. end
  260. def test_large_text_file
  261. params = process('large_text_file')
  262. assert_equal %w(file foo), params.keys.sort
  263. assert_equal 'bar', params['foo']
  264. file = params['file']
  265. assert_kind_of Tempfile, file
  266. assert_equal 'file.txt', file.original_filename
  267. assert_equal "text/plain\r", file.content_type
  268. assert ('a' * 20480) == file.read
  269. end
  270. def test_binary_file
  271. params = process('binary_file')
  272. assert_equal %w(file flowers foo), params.keys.sort
  273. assert_equal 'bar', params['foo']
  274. file = params['file']
  275. assert_kind_of StringIO, file
  276. assert_equal 'file.txt', file.original_filename
  277. assert_equal "text/plain\r", file.content_type
  278. assert_equal 'contents', file.read
  279. file = params['flowers']
  280. assert_kind_of StringIO, file
  281. assert_equal 'flowers.jpg', file.original_filename
  282. assert_equal "image/jpeg\r", file.content_type
  283. assert_equal 19512, file.size
  284. #assert_equal File.read(File.dirname(__FILE__) + '/../../../activerecord/test/fixtures/flowers.jpg'), file.read
  285. end
  286. def test_mixed_files
  287. params = process('mixed_files')
  288. assert_equal %w(files foo), params.keys.sort
  289. assert_equal 'bar', params['foo']
  290. # Ruby CGI doesn't handle multipart/mixed for us.
  291. assert_kind_of String, params['files']
  292. assert_equal 19756, params['files'].size
  293. end
  294. # Rewind readable cgi params so others may reread them (such as CGI::Session
  295. # when passing the session id in a multipart form).
  296. def test_multipart_param_rewound
  297. params = process('text_file')
  298. assert_equal 'bar', @cgi.params['foo'][0].read
  299. end
  300. private
  301. def process(name)
  302. old_stdin = $stdin
  303. File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
  304. ENV['CONTENT_LENGTH'] = file.stat.size.to_s
  305. $stdin = file
  306. @cgi = CGI.new
  307. CGIMethods.parse_request_parameters @cgi.params
  308. end
  309. ensure
  310. $stdin = old_stdin
  311. end
  312. end
  313. # Ensures that PUT works with multipart as well as POST.
  314. class PutMultipartCGITest < MultipartCGITest
  315. def setup
  316. super
  317. ENV['REQUEST_METHOD'] = 'PUT'
  318. end
  319. end
  320. class CGIRequestTest < Test::Unit::TestCase
  321. def setup
  322. @request_hash = {"HTTP_MAX_FORWARDS"=>"10", "SERVER_NAME"=>"glu.ttono.us:8007", "FCGI_ROLE"=>"RESPONDER", "HTTP_X_FORWARDED_HOST"=>"glu.ttono.us", "HTTP_ACCEPT_ENCODING"=>"gzip, deflate", "HTTP_USER_AGENT"=>"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/312.5.1 (KHTML, like Gecko) Safari/312.3.1", "PATH_INFO"=>"", "HTTP_ACCEPT_LANGUAGE"=>"en", "HTTP_HOST"=>"glu.ttono.us:8007", "SERVER_PROTOCOL"=>"HTTP/1.1", "REDIRECT_URI"=>"/dispatch.fcgi", "SCRIPT_NAME"=>"/dispatch.fcgi", "SERVER_ADDR"=>"207.7.108.53", "REMOTE_ADDR"=>"207.7.108.53", "SERVER_SOFTWARE"=>"lighttpd/1.4.5", "HTTP_COOKIE"=>"_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes", "HTTP_X_FORWARDED_SERVER"=>"glu.ttono.us", "REQUEST_URI"=>"/admin", "DOCUMENT_ROOT"=>"/home/kevinc/sites/typo/public", "SERVER_PORT"=>"8007", "QUERY_STRING"=>"", "REMOTE_PORT"=>"63137", "GATEWAY_INTERFACE"=>"CGI/1.1", "HTTP_X_FORWARDED_FOR"=>"65.88.180.234", "HTTP_ACCEPT"=>"*/*", "SCRIPT_FILENAME"=>"/home/kevinc/sites/typo/public/dispatch.fcgi", "REDIRECT_STATUS"=>"200", "REQUEST_METHOD"=>"GET"}
  323. # cookie as returned by some Nokia phone browsers (no space after semicolon separator)
  324. @alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace84796670c052c6ceb2451fb0f2;is_admin=yes"}
  325. @fake_cgi = Struct.new(:env_table).new(@request_hash)
  326. @request = ActionController::CgiRequest.new(@fake_cgi)
  327. end
  328. def test_proxy_request
  329. assert_equal 'glu.ttono.us', @request.host_with_port
  330. end
  331. def test_http_host
  332. @request_hash.delete "HTTP_X_FORWARDED_HOST"
  333. @request_hash['HTTP_HOST'] = "rubyonrails.org:8080"
  334. assert_equal "rubyonrails.org:8080", @request.host_with_port
  335. @request_hash['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org"
  336. assert_equal "www.secondhost.org", @request.host
  337. end
  338. def test_http_host_with_default_port_overrides_server_port
  339. @request_hash.delete "HTTP_X_FORWARDED_HOST"
  340. @request_hash['HTTP_HOST'] = "rubyonrails.org"
  341. assert_equal "rubyonrails.org", @request.host_with_port
  342. end
  343. def test_host_with_port_defaults_to_server_name_if_no_host_headers
  344. @request_hash.delete "HTTP_X_FORWARDED_HOST"
  345. @request_hash.delete "HTTP_HOST"
  346. assert_equal "glu.ttono.us:8007", @request.host_with_port
  347. end
  348. def test_host_with_port_falls_back_to_server_addr_if_necessary
  349. @request_hash.delete "HTTP_X_FORWARDED_HOST"
  350. @request_hash.delete "HTTP_HOST"
  351. @request_hash.delete "SERVER_NAME"
  352. assert_equal "207.7.108.53:8007", @request.host_with_port
  353. end
  354. def test_cookie_syntax_resilience
  355. cookies = CGI::Cookie::parse(@request_hash["HTTP_COOKIE"]);
  356. assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], cookies["_session_id"]
  357. assert_equal ["yes"], cookies["is_admin"]
  358. alt_cookies = CGI::Cookie::parse(@alt_cookie_fmt_request_hash["HTTP_COOKIE"]);
  359. assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], alt_cookies["_session_id"]
  360. assert_equal ["yes"], alt_cookies["is_admin"]
  361. end
  362. def test_unbalanced_query_string_with_array
  363. assert_equal(
  364. {'location' => ["1", "2"], 'age_group' => ["2"]},
  365. CGIMethods.parse_query_parameters("location[]=1&location[]=2&age_group[]=2")
  366. )
  367. assert_equal(
  368. {'location' => ["1", "2"], 'age_group' => ["2"]},
  369. CGIMethods.parse_request_parameters({'location[]' => ["1", "2"],
  370. 'age_group[]' => ["2"]})
  371. )
  372. end
  373. end