Froze rails gems
[depot.git] / vendor / rails / actionpack / test / controller / request_test.rb
1 require 'abstract_unit'
2 require 'action_controller/integration'
3
4 class RequestTest < Test::Unit::TestCase
5 def setup
6 ActionController::Base.relative_url_root = nil
7 @request = ActionController::TestRequest.new
8 end
9
10 def teardown
11 ActionController::Base.relative_url_root = nil
12 end
13
14 def test_remote_ip
15 assert_equal '0.0.0.0', @request.remote_ip
16
17 @request.remote_addr = '1.2.3.4'
18 assert_equal '1.2.3.4', @request.remote_ip(true)
19
20 @request.remote_addr = '1.2.3.4,3.4.5.6'
21 assert_equal '1.2.3.4', @request.remote_ip(true)
22
23 @request.env['HTTP_CLIENT_IP'] = '2.3.4.5'
24 assert_equal '1.2.3.4', @request.remote_ip(true)
25
26 @request.remote_addr = '192.168.0.1'
27 assert_equal '2.3.4.5', @request.remote_ip(true)
28 @request.env.delete 'HTTP_CLIENT_IP'
29
30 @request.remote_addr = '1.2.3.4'
31 @request.env['HTTP_X_FORWARDED_FOR'] = '3.4.5.6'
32 assert_equal '1.2.3.4', @request.remote_ip(true)
33
34 @request.remote_addr = '127.0.0.1'
35 @request.env['HTTP_X_FORWARDED_FOR'] = '3.4.5.6'
36 assert_equal '3.4.5.6', @request.remote_ip(true)
37
38 @request.env['HTTP_X_FORWARDED_FOR'] = 'unknown,3.4.5.6'
39 assert_equal '3.4.5.6', @request.remote_ip(true)
40
41 @request.env['HTTP_X_FORWARDED_FOR'] = '172.16.0.1,3.4.5.6'
42 assert_equal '3.4.5.6', @request.remote_ip(true)
43
44 @request.env['HTTP_X_FORWARDED_FOR'] = '192.168.0.1,3.4.5.6'
45 assert_equal '3.4.5.6', @request.remote_ip(true)
46
47 @request.env['HTTP_X_FORWARDED_FOR'] = '10.0.0.1,3.4.5.6'
48 assert_equal '3.4.5.6', @request.remote_ip(true)
49
50 @request.env['HTTP_X_FORWARDED_FOR'] = '10.0.0.1, 10.0.0.1, 3.4.5.6'
51 assert_equal '3.4.5.6', @request.remote_ip(true)
52
53 @request.env['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,3.4.5.6'
54 assert_equal '3.4.5.6', @request.remote_ip(true)
55
56 @request.env['HTTP_X_FORWARDED_FOR'] = 'unknown,192.168.0.1'
57 assert_equal 'unknown', @request.remote_ip(true)
58
59 @request.env['HTTP_X_FORWARDED_FOR'] = '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4'
60 assert_equal '3.4.5.6', @request.remote_ip(true)
61
62 @request.env['HTTP_CLIENT_IP'] = '8.8.8.8'
63 e = assert_raises(ActionController::ActionControllerError) {
64 @request.remote_ip(true)
65 }
66 assert_match /IP spoofing attack/, e.message
67 assert_match /HTTP_X_FORWARDED_FOR="9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4"/, e.message
68 assert_match /HTTP_CLIENT_IP="8.8.8.8"/, e.message
69
70 @request.env['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 9.9.9.9'
71 assert_equal '8.8.8.8', @request.remote_ip(true)
72
73 @request.env.delete 'HTTP_CLIENT_IP'
74 @request.env.delete 'HTTP_X_FORWARDED_FOR'
75 end
76
77 def test_domains
78 @request.host = "www.rubyonrails.org"
79 assert_equal "rubyonrails.org", @request.domain
80
81 @request.host = "www.rubyonrails.co.uk"
82 assert_equal "rubyonrails.co.uk", @request.domain(2)
83
84 @request.host = "192.168.1.200"
85 assert_nil @request.domain
86
87 @request.host = "foo.192.168.1.200"
88 assert_nil @request.domain
89
90 @request.host = "192.168.1.200.com"
91 assert_equal "200.com", @request.domain
92
93 @request.host = nil
94 assert_nil @request.domain
95 end
96
97 def test_subdomains
98 @request.host = "www.rubyonrails.org"
99 assert_equal %w( www ), @request.subdomains
100
101 @request.host = "www.rubyonrails.co.uk"
102 assert_equal %w( www ), @request.subdomains(2)
103
104 @request.host = "dev.www.rubyonrails.co.uk"
105 assert_equal %w( dev www ), @request.subdomains(2)
106
107 @request.host = "foobar.foobar.com"
108 assert_equal %w( foobar ), @request.subdomains
109
110 @request.host = "192.168.1.200"
111 assert_equal [], @request.subdomains
112
113 @request.host = "foo.192.168.1.200"
114 assert_equal [], @request.subdomains
115
116 @request.host = "192.168.1.200.com"
117 assert_equal %w( 192 168 1 ), @request.subdomains
118
119 @request.host = nil
120 assert_equal [], @request.subdomains
121 end
122
123 def test_port_string
124 @request.port = 80
125 assert_equal "", @request.port_string
126
127 @request.port = 8080
128 assert_equal ":8080", @request.port_string
129 end
130
131 def test_request_uri
132 @request.env['SERVER_SOFTWARE'] = 'Apache 42.342.3432'
133
134 @request.set_REQUEST_URI "http://www.rubyonrails.org/path/of/some/uri?mapped=1"
135 assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
136 assert_equal "/path/of/some/uri", @request.path
137
138 @request.set_REQUEST_URI "http://www.rubyonrails.org/path/of/some/uri"
139 assert_equal "/path/of/some/uri", @request.request_uri
140 assert_equal "/path/of/some/uri", @request.path
141
142 @request.set_REQUEST_URI "/path/of/some/uri"
143 assert_equal "/path/of/some/uri", @request.request_uri
144 assert_equal "/path/of/some/uri", @request.path
145
146 @request.set_REQUEST_URI "/"
147 assert_equal "/", @request.request_uri
148 assert_equal "/", @request.path
149
150 @request.set_REQUEST_URI "/?m=b"
151 assert_equal "/?m=b", @request.request_uri
152 assert_equal "/", @request.path
153
154 @request.set_REQUEST_URI "/"
155 @request.env['SCRIPT_NAME'] = "/dispatch.cgi"
156 assert_equal "/", @request.request_uri
157 assert_equal "/", @request.path
158
159 ActionController::Base.relative_url_root = "/hieraki"
160 @request.set_REQUEST_URI "/hieraki/"
161 @request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
162 assert_equal "/hieraki/", @request.request_uri
163 assert_equal "/", @request.path
164 ActionController::Base.relative_url_root = nil
165
166 ActionController::Base.relative_url_root = "/collaboration/hieraki"
167 @request.set_REQUEST_URI "/collaboration/hieraki/books/edit/2"
168 @request.env['SCRIPT_NAME'] = "/collaboration/hieraki/dispatch.cgi"
169 assert_equal "/collaboration/hieraki/books/edit/2", @request.request_uri
170 assert_equal "/books/edit/2", @request.path
171 ActionController::Base.relative_url_root = nil
172
173 # The following tests are for when REQUEST_URI is not supplied (as in IIS)
174 @request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1"
175 @request.env['SCRIPT_NAME'] = nil #"/path/dispatch.rb"
176 @request.set_REQUEST_URI nil
177 assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
178 assert_equal "/path/of/some/uri", @request.path
179
180 ActionController::Base.relative_url_root = '/path'
181 @request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1"
182 @request.env['SCRIPT_NAME'] = "/path/dispatch.rb"
183 @request.set_REQUEST_URI nil
184 assert_equal "/path/of/some/uri?mapped=1", @request.request_uri(true)
185 assert_equal "/of/some/uri", @request.path(true)
186 ActionController::Base.relative_url_root = nil
187
188 @request.env['PATH_INFO'] = "/path/of/some/uri"
189 @request.env['SCRIPT_NAME'] = nil
190 @request.set_REQUEST_URI nil
191 assert_equal "/path/of/some/uri", @request.request_uri
192 assert_equal "/path/of/some/uri", @request.path
193
194 @request.env['PATH_INFO'] = "/"
195 @request.set_REQUEST_URI nil
196 assert_equal "/", @request.request_uri
197 assert_equal "/", @request.path
198
199 @request.env['PATH_INFO'] = "/?m=b"
200 @request.set_REQUEST_URI nil
201 assert_equal "/?m=b", @request.request_uri
202 assert_equal "/", @request.path
203
204 @request.env['PATH_INFO'] = "/"
205 @request.env['SCRIPT_NAME'] = "/dispatch.cgi"
206 @request.set_REQUEST_URI nil
207 assert_equal "/", @request.request_uri
208 assert_equal "/", @request.path
209
210 ActionController::Base.relative_url_root = '/hieraki'
211 @request.env['PATH_INFO'] = "/hieraki/"
212 @request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
213 @request.set_REQUEST_URI nil
214 assert_equal "/hieraki/", @request.request_uri
215 assert_equal "/", @request.path
216 ActionController::Base.relative_url_root = nil
217
218 @request.set_REQUEST_URI '/hieraki/dispatch.cgi'
219 ActionController::Base.relative_url_root = '/hieraki'
220 assert_equal "/dispatch.cgi", @request.path(true)
221 ActionController::Base.relative_url_root = nil
222
223 @request.set_REQUEST_URI '/hieraki/dispatch.cgi'
224 ActionController::Base.relative_url_root = '/foo'
225 assert_equal "/hieraki/dispatch.cgi", @request.path(true)
226 ActionController::Base.relative_url_root = nil
227
228 # This test ensures that Rails uses REQUEST_URI over PATH_INFO
229 ActionController::Base.relative_url_root = nil
230 @request.env['REQUEST_URI'] = "/some/path"
231 @request.env['PATH_INFO'] = "/another/path"
232 @request.env['SCRIPT_NAME'] = "/dispatch.cgi"
233 assert_equal "/some/path", @request.request_uri(true)
234 assert_equal "/some/path", @request.path(true)
235 end
236
237 def test_host_with_default_port
238 @request.host = "rubyonrails.org"
239 @request.port = 80
240 assert_equal "rubyonrails.org", @request.host_with_port
241 end
242
243 def test_host_with_non_default_port
244 @request.host = "rubyonrails.org"
245 @request.port = 81
246 assert_equal "rubyonrails.org:81", @request.host_with_port
247 end
248
249 def test_server_software
250 assert_equal nil, @request.server_software(true)
251
252 @request.env['SERVER_SOFTWARE'] = 'Apache3.422'
253 assert_equal 'apache', @request.server_software(true)
254
255 @request.env['SERVER_SOFTWARE'] = 'lighttpd(1.1.4)'
256 assert_equal 'lighttpd', @request.server_software(true)
257 end
258
259 def test_xml_http_request
260 assert !@request.xml_http_request?
261 assert !@request.xhr?
262
263 @request.env['HTTP_X_REQUESTED_WITH'] = "DefinitelyNotAjax1.0"
264 assert !@request.xml_http_request?
265 assert !@request.xhr?
266
267 @request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
268 assert @request.xml_http_request?
269 assert @request.xhr?
270 end
271
272 def test_reports_ssl
273 assert !@request.ssl?
274 @request.env['HTTPS'] = 'on'
275 assert @request.ssl?
276 end
277
278 def test_reports_ssl_when_proxied_via_lighttpd
279 assert !@request.ssl?
280 @request.env['HTTP_X_FORWARDED_PROTO'] = 'https'
281 assert @request.ssl?
282 end
283
284 def test_symbolized_request_methods
285 [:get, :post, :put, :delete].each do |method|
286 self.request_method = method
287 assert_equal method, @request.method
288 end
289 end
290
291 def test_invalid_http_method_raises_exception
292 assert_raises(ActionController::UnknownHttpMethod) do
293 self.request_method = :random_method
294 end
295 end
296
297 def test_allow_method_hacking_on_post
298 self.request_method = :post
299 [:get, :head, :options, :put, :post, :delete].each do |method|
300 @request.instance_eval { @parameters = { :_method => method.to_s } ; @request_method = nil }
301 @request.request_method(true)
302 assert_equal(method == :head ? :get : method, @request.method)
303 end
304 end
305
306 def test_invalid_method_hacking_on_post_raises_exception
307 self.request_method = :post
308 @request.instance_eval { @parameters = { :_method => :random_method } ; @request_method = nil }
309 assert_raises(ActionController::UnknownHttpMethod) do
310 @request.request_method(true)
311 end
312 end
313
314 def test_restrict_method_hacking
315 @request.instance_eval { @parameters = { :_method => 'put' } }
316 [:get, :put, :delete].each do |method|
317 self.request_method = method
318 assert_equal method, @request.method
319 end
320 end
321
322 def test_head_masquerading_as_get
323 self.request_method = :head
324 assert_equal :get, @request.method
325 assert @request.get?
326 assert @request.head?
327 end
328
329 def test_xml_format
330 @request.instance_eval { @parameters = { :format => 'xml' } }
331 assert_equal Mime::XML, @request.format
332 end
333
334 def test_xhtml_format
335 @request.instance_eval { @parameters = { :format => 'xhtml' } }
336 assert_equal Mime::HTML, @request.format
337 end
338
339 def test_txt_format
340 @request.instance_eval { @parameters = { :format => 'txt' } }
341 assert_equal Mime::TEXT, @request.format
342 end
343
344 def test_nil_format
345 ActionController::Base.use_accept_header, old =
346 false, ActionController::Base.use_accept_header
347
348 @request.instance_eval { @parameters = {} }
349 @request.env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
350 assert @request.xhr?
351 assert_equal Mime::JS, @request.format
352
353 ensure
354 ActionController::Base.use_accept_header = old
355 end
356
357 def test_content_type
358 @request.env["CONTENT_TYPE"] = "text/html"
359 assert_equal Mime::HTML, @request.content_type
360 end
361
362 def test_format_assignment_should_set_format
363 @request.instance_eval { self.format = :txt }
364 assert !@request.format.xml?
365 @request.instance_eval { self.format = :xml }
366 assert @request.format.xml?
367 end
368
369 def test_content_no_type
370 assert_equal nil, @request.content_type
371 end
372
373 def test_content_type_xml
374 @request.env["CONTENT_TYPE"] = "application/xml"
375 assert_equal Mime::XML, @request.content_type
376 end
377
378 def test_content_type_with_charset
379 @request.env["CONTENT_TYPE"] = "application/xml; charset=UTF-8"
380 assert_equal Mime::XML, @request.content_type
381 end
382
383 def test_user_agent
384 assert_not_nil @request.user_agent
385 end
386
387 def test_parameters
388 @request.instance_eval { @request_parameters = { "foo" => 1 } }
389 @request.instance_eval { @query_parameters = { "bar" => 2 } }
390
391 assert_equal({"foo" => 1, "bar" => 2}, @request.parameters)
392 assert_equal({"foo" => 1}, @request.request_parameters)
393 assert_equal({"bar" => 2}, @request.query_parameters)
394 end
395
396 protected
397 def request_method=(method)
398 @request.env['REQUEST_METHOD'] = method.to_s.upcase
399 @request.request_method(true)
400 end
401 end
402
403 class UrlEncodedRequestParameterParsingTest < Test::Unit::TestCase
404 def setup
405 @query_string = "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
406 @query_string_with_empty = "action=create_customer&full_name="
407 @query_string_with_array = "action=create_customer&selected[]=1&selected[]=2&selected[]=3"
408 @query_string_with_amps = "action=create_customer&name=Don%27t+%26+Does"
409 @query_string_with_multiple_of_same_name =
410 "action=update_order&full_name=Lau%20Taarnskov&products=4&products=2&products=3"
411 @query_string_with_many_equal = "action=create_customer&full_name=abc=def=ghi"
412 @query_string_without_equal = "action"
413 @query_string_with_many_ampersands =
414 "&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
415 @query_string_with_empty_key = "action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save"
416 end
417
418 def test_query_string
419 assert_equal(
420 { "action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"},
421 ActionController::AbstractRequest.parse_query_parameters(@query_string)
422 )
423 end
424
425 def test_deep_query_string
426 expected = {'x' => {'y' => {'z' => '10'}}}
427 assert_equal(expected, ActionController::AbstractRequest.parse_query_parameters('x[y][z]=10'))
428 end
429
430 def test_deep_query_string_with_array
431 assert_equal({'x' => {'y' => {'z' => ['10']}}}, ActionController::AbstractRequest.parse_query_parameters('x[y][z][]=10'))
432 assert_equal({'x' => {'y' => {'z' => ['10', '5']}}}, ActionController::AbstractRequest.parse_query_parameters('x[y][z][]=10&x[y][z][]=5'))
433 end
434
435 def test_deep_query_string_with_array_of_hash
436 assert_equal({'x' => {'y' => [{'z' => '10'}]}}, ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10'))
437 assert_equal({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][w]=10'))
438 end
439
440 def test_deep_query_string_with_array_of_hashes_with_one_pair
441 assert_equal({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][z]=20'))
442 assert_equal("10", ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][z]=20')["x"]["y"].first["z"])
443 assert_equal("10", ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][z]=20').with_indifferent_access[:x][:y].first[:z])
444 end
445
446 def test_deep_query_string_with_array_of_hashes_with_multiple_pairs
447 assert_equal(
448 {'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}},
449 ActionController::AbstractRequest.parse_query_parameters('x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b')
450 )
451 end
452
453 def test_query_string_with_nil
454 assert_equal(
455 { "action" => "create_customer", "full_name" => ''},
456 ActionController::AbstractRequest.parse_query_parameters(@query_string_with_empty)
457 )
458 end
459
460 def test_query_string_with_array
461 assert_equal(
462 { "action" => "create_customer", "selected" => ["1", "2", "3"]},
463 ActionController::AbstractRequest.parse_query_parameters(@query_string_with_array)
464 )
465 end
466
467 def test_query_string_with_amps
468 assert_equal(
469 { "action" => "create_customer", "name" => "Don't & Does"},
470 ActionController::AbstractRequest.parse_query_parameters(@query_string_with_amps)
471 )
472 end
473
474 def test_query_string_with_many_equal
475 assert_equal(
476 { "action" => "create_customer", "full_name" => "abc=def=ghi"},
477 ActionController::AbstractRequest.parse_query_parameters(@query_string_with_many_equal)
478 )
479 end
480
481 def test_query_string_without_equal
482 assert_equal(
483 { "action" => nil },
484 ActionController::AbstractRequest.parse_query_parameters(@query_string_without_equal)
485 )
486 end
487
488 def test_query_string_with_empty_key
489 assert_equal(
490 { "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
491 ActionController::AbstractRequest.parse_query_parameters(@query_string_with_empty_key)
492 )
493 end
494
495 def test_query_string_with_many_ampersands
496 assert_equal(
497 { "action" => "create_customer", "full_name" => "David Heinemeier Hansson"},
498 ActionController::AbstractRequest.parse_query_parameters(@query_string_with_many_ampersands)
499 )
500 end
501
502 def test_unbalanced_query_string_with_array
503 assert_equal(
504 {'location' => ["1", "2"], 'age_group' => ["2"]},
505 ActionController::AbstractRequest.parse_query_parameters("location[]=1&location[]=2&age_group[]=2")
506 )
507 assert_equal(
508 {'location' => ["1", "2"], 'age_group' => ["2"]},
509 ActionController::AbstractRequest.parse_request_parameters({'location[]' => ["1", "2"],
510 'age_group[]' => ["2"]})
511 )
512 end
513
514 def test_request_hash_parsing
515 query = {
516 "note[viewers][viewer][][type]" => ["User", "Group"],
517 "note[viewers][viewer][][id]" => ["1", "2"]
518 }
519
520 expected = { "note" => { "viewers"=>{"viewer"=>[{ "id"=>"1", "type"=>"User"}, {"type"=>"Group", "id"=>"2"} ]} } }
521
522 assert_equal(expected, ActionController::AbstractRequest.parse_request_parameters(query))
523 end
524
525 def test_parse_params
526 input = {
527 "customers[boston][first][name]" => [ "David" ],
528 "customers[boston][first][url]" => [ "http://David" ],
529 "customers[boston][second][name]" => [ "Allan" ],
530 "customers[boston][second][url]" => [ "http://Allan" ],
531 "something_else" => [ "blah" ],
532 "something_nil" => [ nil ],
533 "something_empty" => [ "" ],
534 "products[first]" => [ "Apple Computer" ],
535 "products[second]" => [ "Pc" ],
536 "" => [ 'Save' ]
537 }
538
539 expected_output = {
540 "customers" => {
541 "boston" => {
542 "first" => {
543 "name" => "David",
544 "url" => "http://David"
545 },
546 "second" => {
547 "name" => "Allan",
548 "url" => "http://Allan"
549 }
550 }
551 },
552 "something_else" => "blah",
553 "something_empty" => "",
554 "something_nil" => "",
555 "products" => {
556 "first" => "Apple Computer",
557 "second" => "Pc"
558 }
559 }
560
561 assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input)
562 end
563
564 UploadedStringIO = ActionController::UploadedStringIO
565 class MockUpload < UploadedStringIO
566 def initialize(content_type, original_path, *args)
567 self.content_type = content_type
568 self.original_path = original_path
569 super *args
570 end
571 end
572
573 def test_parse_params_from_multipart_upload
574 file = MockUpload.new('img/jpeg', 'foo.jpg')
575 ie_file = MockUpload.new('img/jpeg', 'c:\\Documents and Settings\\foo\\Desktop\\bar.jpg')
576 non_file_text_part = MockUpload.new('text/plain', '', 'abc')
577
578 input = {
579 "something" => [ UploadedStringIO.new("") ],
580 "array_of_stringios" => [[ UploadedStringIO.new("One"), UploadedStringIO.new("Two") ]],
581 "mixed_types_array" => [[ UploadedStringIO.new("Three"), "NotStringIO" ]],
582 "mixed_types_as_checkboxes[strings][nested]" => [[ file, "String", UploadedStringIO.new("StringIO")]],
583 "ie_mixed_types_as_checkboxes[strings][nested]" => [[ ie_file, "String", UploadedStringIO.new("StringIO")]],
584 "products[string]" => [ UploadedStringIO.new("Apple Computer") ],
585 "products[file]" => [ file ],
586 "ie_products[string]" => [ UploadedStringIO.new("Microsoft") ],
587 "ie_products[file]" => [ ie_file ],
588 "text_part" => [non_file_text_part]
589 }
590
591 expected_output = {
592 "something" => "",
593 "array_of_stringios" => ["One", "Two"],
594 "mixed_types_array" => [ "Three", "NotStringIO" ],
595 "mixed_types_as_checkboxes" => {
596 "strings" => {
597 "nested" => [ file, "String", "StringIO" ]
598 },
599 },
600 "ie_mixed_types_as_checkboxes" => {
601 "strings" => {
602 "nested" => [ ie_file, "String", "StringIO" ]
603 },
604 },
605 "products" => {
606 "string" => "Apple Computer",
607 "file" => file
608 },
609 "ie_products" => {
610 "string" => "Microsoft",
611 "file" => ie_file
612 },
613 "text_part" => "abc"
614 }
615
616 params = ActionController::AbstractRequest.parse_request_parameters(input)
617 assert_equal expected_output, params
618
619 # Lone filenames are preserved.
620 assert_equal 'foo.jpg', params['mixed_types_as_checkboxes']['strings']['nested'].first.original_filename
621 assert_equal 'foo.jpg', params['products']['file'].original_filename
622
623 # But full Windows paths are reduced to their basename.
624 assert_equal 'bar.jpg', params['ie_mixed_types_as_checkboxes']['strings']['nested'].first.original_filename
625 assert_equal 'bar.jpg', params['ie_products']['file'].original_filename
626 end
627
628 def test_parse_params_with_file
629 input = {
630 "customers[boston][first][name]" => [ "David" ],
631 "something_else" => [ "blah" ],
632 "logo" => [ File.new(File.dirname(__FILE__) + "/cgi_test.rb").path ]
633 }
634
635 expected_output = {
636 "customers" => {
637 "boston" => {
638 "first" => {
639 "name" => "David"
640 }
641 }
642 },
643 "something_else" => "blah",
644 "logo" => File.new(File.dirname(__FILE__) + "/cgi_test.rb").path,
645 }
646
647 assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input)
648 end
649
650 def test_parse_params_with_array
651 input = { "selected[]" => [ "1", "2", "3" ] }
652
653 expected_output = { "selected" => [ "1", "2", "3" ] }
654
655 assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input)
656 end
657
658 def test_parse_params_with_non_alphanumeric_name
659 input = { "a/b[c]" => %w(d) }
660 expected = { "a/b" => { "c" => "d" }}
661 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
662 end
663
664 def test_parse_params_with_single_brackets_in_middle
665 input = { "a/b[c]d" => %w(e) }
666 expected = { "a/b" => {} }
667 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
668 end
669
670 def test_parse_params_with_separated_brackets
671 input = { "a/b@[c]d[e]" => %w(f) }
672 expected = { "a/b@" => { }}
673 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
674 end
675
676 def test_parse_params_with_separated_brackets_and_array
677 input = { "a/b@[c]d[e][]" => %w(f) }
678 expected = { "a/b@" => { }}
679 assert_equal expected , ActionController::AbstractRequest.parse_request_parameters(input)
680 end
681
682 def test_parse_params_with_unmatched_brackets_and_array
683 input = { "a/b@[c][d[e][]" => %w(f) }
684 expected = { "a/b@" => { "c" => { }}}
685 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
686 end
687
688 def test_parse_params_with_nil_key
689 input = { nil => nil, "test2" => %w(value1) }
690 expected = { "test2" => "value1" }
691 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
692 end
693
694 def test_parse_params_with_array_prefix_and_hashes
695 input = { "a[][b][c]" => %w(d) }
696 expected = {"a" => [{"b" => {"c" => "d"}}]}
697 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
698 end
699
700 def test_parse_params_with_complex_nesting
701 input = { "a[][b][c][][d][]" => %w(e) }
702 expected = {"a" => [{"b" => {"c" => [{"d" => ["e"]}]}}]}
703 assert_equal expected, ActionController::AbstractRequest.parse_request_parameters(input)
704 end
705 end
706
707 class MultipartRequestParameterParsingTest < Test::Unit::TestCase
708 FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart'
709
710 def test_single_parameter
711 params = process('single_parameter')
712 assert_equal({ 'foo' => 'bar' }, params)
713 end
714
715 def test_bracketed_param
716 assert_equal({ 'foo' => { 'baz' => 'bar'}}, process('bracketed_param'))
717 end
718
719 def test_text_file
720 params = process('text_file')
721 assert_equal %w(file foo), params.keys.sort
722 assert_equal 'bar', params['foo']
723
724 file = params['file']
725 assert_kind_of StringIO, file
726 assert_equal 'file.txt', file.original_filename
727 assert_equal "text/plain", file.content_type
728 assert_equal 'contents', file.read
729 end
730
731 def test_boundary_problem_file
732 params = process('boundary_problem_file')
733 assert_equal %w(file foo), params.keys.sort
734
735 file = params['file']
736 foo = params['foo']
737
738 assert_kind_of Tempfile, file
739
740 assert_equal 'file.txt', file.original_filename
741 assert_equal "text/plain", file.content_type
742
743 assert_equal 'bar', foo
744 end
745
746 def test_large_text_file
747 params = process('large_text_file')
748 assert_equal %w(file foo), params.keys.sort
749 assert_equal 'bar', params['foo']
750
751 file = params['file']
752
753 assert_kind_of Tempfile, file
754
755 assert_equal 'file.txt', file.original_filename
756 assert_equal "text/plain", file.content_type
757 assert ('a' * 20480) == file.read
758 end
759
760 uses_mocha "test_no_rewind_stream" do
761 def test_no_rewind_stream
762 # Ensures that parse_multipart_form_parameters works with streams that cannot be rewound
763 file = File.open(File.join(FIXTURE_PATH, 'large_text_file'), 'rb')
764 file.expects(:rewind).raises(Errno::ESPIPE)
765 params = ActionController::AbstractRequest.parse_multipart_form_parameters(file, 'AaB03x', file.stat.size, {})
766 assert_not_equal 0, file.pos # file was not rewound after reading
767 end
768 end
769
770 def test_binary_file
771 params = process('binary_file')
772 assert_equal %w(file flowers foo), params.keys.sort
773 assert_equal 'bar', params['foo']
774
775 file = params['file']
776 assert_kind_of StringIO, file
777 assert_equal 'file.csv', file.original_filename
778 assert_nil file.content_type
779 assert_equal 'contents', file.read
780
781 file = params['flowers']
782 assert_kind_of StringIO, file
783 assert_equal 'flowers.jpg', file.original_filename
784 assert_equal "image/jpeg", file.content_type
785 assert_equal 19512, file.size
786 #assert_equal File.read(File.dirname(__FILE__) + '/../../../activerecord/test/fixtures/flowers.jpg'), file.read
787 end
788
789 def test_mixed_files
790 params = process('mixed_files')
791 assert_equal %w(files foo), params.keys.sort
792 assert_equal 'bar', params['foo']
793
794 # Ruby CGI doesn't handle multipart/mixed for us.
795 files = params['files']
796 assert_kind_of String, files
797 files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
798 assert_equal 19756, files.size
799 end
800
801 private
802 def process(name)
803 File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
804 params = ActionController::AbstractRequest.parse_multipart_form_parameters(file, 'AaB03x', file.stat.size, {})
805 assert_equal 0, file.pos # file was rewound after reading
806 params
807 end
808 end
809 end
810
811 class XmlParamsParsingTest < Test::Unit::TestCase
812 def test_hash_params
813 person = parse_body("<person><name>David</name></person>")[:person]
814 assert_kind_of Hash, person
815 assert_equal 'David', person['name']
816 end
817
818 def test_single_file
819 person = parse_body("<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></person>")
820
821 assert_equal "image/jpg", person['person']['avatar'].content_type
822 assert_equal "me.jpg", person['person']['avatar'].original_filename
823 assert_equal "ABC", person['person']['avatar'].read
824 end
825
826 def test_multiple_files
827 person = parse_body(<<-end_body)
828 <person>
829 <name>David</name>
830 <avatars>
831 <avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar>
832 <avatar type='file' name='you.gif' content_type='image/gif'>#{ActiveSupport::Base64.encode64('DEF')}</avatar>
833 </avatars>
834 </person>
835 end_body
836
837 assert_equal "image/jpg", person['person']['avatars']['avatar'].first.content_type
838 assert_equal "me.jpg", person['person']['avatars']['avatar'].first.original_filename
839 assert_equal "ABC", person['person']['avatars']['avatar'].first.read
840
841 assert_equal "image/gif", person['person']['avatars']['avatar'].last.content_type
842 assert_equal "you.gif", person['person']['avatars']['avatar'].last.original_filename
843 assert_equal "DEF", person['person']['avatars']['avatar'].last.read
844 end
845
846 private
847 def parse_body(body)
848 env = { 'rack.input' => StringIO.new(body),
849 'CONTENT_TYPE' => 'application/xml',
850 'CONTENT_LENGTH' => body.size.to_s }
851 ActionController::RackRequest.new(env).request_parameters
852 end
853 end
854
855 class LegacyXmlParamsParsingTest < XmlParamsParsingTest
856 private
857 def parse_body(body)
858 env = { 'rack.input' => StringIO.new(body),
859 'HTTP_X_POST_DATA_FORMAT' => 'xml',
860 'CONTENT_LENGTH' => body.size.to_s }
861 ActionController::RackRequest.new(env).request_parameters
862 end
863 end
864
865 class JsonParamsParsingTest < Test::Unit::TestCase
866 def test_hash_params_for_application_json
867 person = parse_body({:person => {:name => "David"}}.to_json,'application/json')[:person]
868 assert_kind_of Hash, person
869 assert_equal 'David', person['name']
870 end
871
872 def test_hash_params_for_application_jsonrequest
873 person = parse_body({:person => {:name => "David"}}.to_json,'application/jsonrequest')[:person]
874 assert_kind_of Hash, person
875 assert_equal 'David', person['name']
876 end
877
878 private
879 def parse_body(body,content_type)
880 env = { 'rack.input' => StringIO.new(body),
881 'CONTENT_TYPE' => content_type,
882 'CONTENT_LENGTH' => body.size.to_s }
883 ActionController::RackRequest.new(env).request_parameters
884 end
885 end