Froze rails gems
[depot.git] / vendor / rails / actionpack / test / controller / test_test.rb
1 require 'abstract_unit'
2 require 'controller/fake_controllers'
3
4 class TestTest < Test::Unit::TestCase
5 class TestController < ActionController::Base
6 def no_op
7 render :text => 'dummy'
8 end
9
10 def set_flash
11 flash["test"] = ">#{flash["test"]}<"
12 render :text => 'ignore me'
13 end
14
15 def set_flash_now
16 flash.now["test_now"] = ">#{flash["test_now"]}<"
17 render :text => 'ignore me'
18 end
19
20 def set_session
21 session['string'] = 'A wonder'
22 session[:symbol] = 'it works'
23 render :text => 'Success'
24 end
25
26 def render_raw_post
27 raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank?
28 render :text => request.raw_post
29 end
30
31 def render_body
32 render :text => request.body.read
33 end
34
35 def test_params
36 render :text => params.inspect
37 end
38
39 def test_uri
40 render :text => request.request_uri
41 end
42
43 def test_query_string
44 render :text => request.query_string
45 end
46
47 def test_html_output
48 render :text => <<HTML
49 <html>
50 <body>
51 <a href="/"><img src="/images/button.png" /></a>
52 <div id="foo">
53 <ul>
54 <li class="item">hello</li>
55 <li class="item">goodbye</li>
56 </ul>
57 </div>
58 <div id="bar">
59 <form action="/somewhere">
60 Name: <input type="text" name="person[name]" id="person_name" />
61 </form>
62 </div>
63 </body>
64 </html>
65 HTML
66 end
67
68 def test_xml_output
69 response.content_type = "application/xml"
70 render :text => <<XML
71 <?xml version="1.0" encoding="UTF-8"?>
72 <root>
73 <area>area is an empty tag in HTML, raising an error if not in xml mode</area>
74 </root>
75 XML
76 end
77
78 def test_only_one_param
79 render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
80 end
81
82 def test_remote_addr
83 render :text => (request.remote_addr || "not specified")
84 end
85
86 def test_file_upload
87 render :text => params[:file].size
88 end
89
90 def test_send_file
91 send_file(File.expand_path(__FILE__))
92 end
93
94 def redirect_to_same_controller
95 redirect_to :controller => 'test', :action => 'test_uri', :id => 5
96 end
97
98 def redirect_to_different_controller
99 redirect_to :controller => 'fail', :id => 5
100 end
101
102 def create
103 head :created, :location => 'created resource'
104 end
105
106 private
107 def rescue_action(e)
108 raise e
109 end
110
111 def generate_url(opts)
112 url_for(opts.merge(:action => "test_uri"))
113 end
114 end
115
116 def setup
117 @controller = TestController.new
118 @request = ActionController::TestRequest.new
119 @response = ActionController::TestResponse.new
120 ActionController::Routing.use_controllers! %w(content admin/user test_test/test)
121 ActionController::Routing::Routes.load_routes!
122 end
123
124 def teardown
125 ActionController::Routing::Routes.reload
126 end
127
128 def test_raw_post_handling
129 params = {:page => {:name => 'page name'}, 'some key' => 123}
130 post :render_raw_post, params.dup
131
132 assert_equal params.to_query, @response.body
133 end
134
135 def test_body_stream
136 params = { :page => { :name => 'page name' }, 'some key' => 123 }
137
138 post :render_body, params.dup
139
140 assert_equal params.to_query, @response.body
141 end
142
143 def test_process_without_flash
144 process :set_flash
145 assert_equal '><', flash['test']
146 end
147
148 def test_process_with_flash
149 process :set_flash, nil, nil, { "test" => "value" }
150 assert_equal '>value<', flash['test']
151 end
152
153 def test_process_with_flash_now
154 process :set_flash_now, nil, nil, { "test_now" => "value_now" }
155 assert_equal '>value_now<', flash['test_now']
156 end
157
158 def test_process_with_session
159 process :set_session
160 assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
161 assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access"
162 assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access"
163 assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
164 end
165
166 def test_process_with_session_arg
167 process :no_op, nil, { 'string' => 'value1', :symbol => 'value2' }
168 assert_equal 'value1', session['string']
169 assert_equal 'value1', session[:string]
170 assert_equal 'value2', session['symbol']
171 assert_equal 'value2', session[:symbol]
172 end
173
174 def test_process_with_request_uri_with_no_params
175 process :test_uri
176 assert_equal "/test_test/test/test_uri", @response.body
177 end
178
179 def test_process_with_request_uri_with_params
180 process :test_uri, :id => 7
181 assert_equal "/test_test/test/test_uri/7", @response.body
182 end
183
184 def test_process_with_request_uri_with_params_with_explicit_uri
185 @request.set_REQUEST_URI "/explicit/uri"
186 process :test_uri, :id => 7
187 assert_equal "/explicit/uri", @response.body
188 end
189
190 def test_process_with_query_string
191 process :test_query_string, :q => 'test'
192 assert_equal "q=test", @response.body
193 end
194
195 def test_process_with_query_string_with_explicit_uri
196 @request.set_REQUEST_URI "/explicit/uri?q=test?extra=question"
197 process :test_query_string
198 assert_equal "q=test?extra=question", @response.body
199 end
200
201 def test_multiple_calls
202 process :test_only_one_param, :left => true
203 assert_equal "OK", @response.body
204 process :test_only_one_param, :right => true
205 assert_equal "OK", @response.body
206 end
207
208 def test_assert_tag_tag
209 process :test_html_output
210
211 # there is a 'form' tag
212 assert_tag :tag => 'form'
213 # there is not an 'hr' tag
214 assert_no_tag :tag => 'hr'
215 end
216
217 def test_assert_tag_attributes
218 process :test_html_output
219
220 # there is a tag with an 'id' of 'bar'
221 assert_tag :attributes => { :id => "bar" }
222 # there is no tag with a 'name' of 'baz'
223 assert_no_tag :attributes => { :name => "baz" }
224 end
225
226 def test_assert_tag_parent
227 process :test_html_output
228
229 # there is a tag with a parent 'form' tag
230 assert_tag :parent => { :tag => "form" }
231 # there is no tag with a parent of 'input'
232 assert_no_tag :parent => { :tag => "input" }
233 end
234
235 def test_assert_tag_child
236 process :test_html_output
237
238 # there is a tag with a child 'input' tag
239 assert_tag :child => { :tag => "input" }
240 # there is no tag with a child 'strong' tag
241 assert_no_tag :child => { :tag => "strong" }
242 end
243
244 def test_assert_tag_ancestor
245 process :test_html_output
246
247 # there is a 'li' tag with an ancestor having an id of 'foo'
248 assert_tag :ancestor => { :attributes => { :id => "foo" } }, :tag => "li"
249 # there is no tag of any kind with an ancestor having an href matching 'foo'
250 assert_no_tag :ancestor => { :attributes => { :href => /foo/ } }
251 end
252
253 def test_assert_tag_descendant
254 process :test_html_output
255
256 # there is a tag with a descendant 'li' tag
257 assert_tag :descendant => { :tag => "li" }
258 # there is no tag with a descendant 'html' tag
259 assert_no_tag :descendant => { :tag => "html" }
260 end
261
262 def test_assert_tag_sibling
263 process :test_html_output
264
265 # there is a tag with a sibling of class 'item'
266 assert_tag :sibling => { :attributes => { :class => "item" } }
267 # there is no tag with a sibling 'ul' tag
268 assert_no_tag :sibling => { :tag => "ul" }
269 end
270
271 def test_assert_tag_after
272 process :test_html_output
273
274 # there is a tag following a sibling 'div' tag
275 assert_tag :after => { :tag => "div" }
276 # there is no tag following a sibling tag with id 'bar'
277 assert_no_tag :after => { :attributes => { :id => "bar" } }
278 end
279
280 def test_assert_tag_before
281 process :test_html_output
282
283 # there is a tag preceding a tag with id 'bar'
284 assert_tag :before => { :attributes => { :id => "bar" } }
285 # there is no tag preceding a 'form' tag
286 assert_no_tag :before => { :tag => "form" }
287 end
288
289 def test_assert_tag_children_count
290 process :test_html_output
291
292 # there is a tag with 2 children
293 assert_tag :children => { :count => 2 }
294 # in particular, there is a <ul> tag with two children (a nameless pair of <li>s)
295 assert_tag :tag => 'ul', :children => { :count => 2 }
296 # there is no tag with 4 children
297 assert_no_tag :children => { :count => 4 }
298 end
299
300 def test_assert_tag_children_less_than
301 process :test_html_output
302
303 # there is a tag with less than 5 children
304 assert_tag :children => { :less_than => 5 }
305 # there is no 'ul' tag with less than 2 children
306 assert_no_tag :children => { :less_than => 2 }, :tag => "ul"
307 end
308
309 def test_assert_tag_children_greater_than
310 process :test_html_output
311
312 # there is a 'body' tag with more than 1 children
313 assert_tag :children => { :greater_than => 1 }, :tag => "body"
314 # there is no tag with more than 10 children
315 assert_no_tag :children => { :greater_than => 10 }
316 end
317
318 def test_assert_tag_children_only
319 process :test_html_output
320
321 # there is a tag containing only one child with an id of 'foo'
322 assert_tag :children => { :count => 1,
323 :only => { :attributes => { :id => "foo" } } }
324 # there is no tag containing only one 'li' child
325 assert_no_tag :children => { :count => 1, :only => { :tag => "li" } }
326 end
327
328 def test_assert_tag_content
329 process :test_html_output
330
331 # the output contains the string "Name"
332 assert_tag :content => /Name/
333 # the output does not contain the string "test"
334 assert_no_tag :content => /test/
335 end
336
337 def test_assert_tag_multiple
338 process :test_html_output
339
340 # there is a 'div', id='bar', with an immediate child whose 'action'
341 # attribute matches the regexp /somewhere/.
342 assert_tag :tag => "div", :attributes => { :id => "bar" },
343 :child => { :attributes => { :action => /somewhere/ } }
344
345 # there is no 'div', id='foo', with a 'ul' child with more than
346 # 2 "li" children.
347 assert_no_tag :tag => "div", :attributes => { :id => "foo" },
348 :child => {
349 :tag => "ul",
350 :children => { :greater_than => 2,
351 :only => { :tag => "li" } } }
352 end
353
354 def test_assert_tag_children_without_content
355 process :test_html_output
356
357 # there is a form tag with an 'input' child which is a self closing tag
358 assert_tag :tag => "form",
359 :children => { :count => 1,
360 :only => { :tag => "input" } }
361
362 # the body tag has an 'a' child which in turn has an 'img' child
363 assert_tag :tag => "body",
364 :children => { :count => 1,
365 :only => { :tag => "a",
366 :children => { :count => 1,
367 :only => { :tag => "img" } } } }
368 end
369
370 def test_should_not_impose_childless_html_tags_in_xml
371 process :test_xml_output
372
373 begin
374 $stderr = StringIO.new
375 assert_select 'area' #This will cause a warning if content is processed as HTML
376 $stderr.rewind && err = $stderr.read
377 ensure
378 $stderr = STDERR
379 end
380
381 assert err.empty?
382 end
383
384 def test_assert_tag_attribute_matching
385 @response.body = '<input type="text" name="my_name">'
386 assert_tag :tag => 'input',
387 :attributes => { :name => /my/, :type => 'text' }
388 assert_no_tag :tag => 'input',
389 :attributes => { :name => 'my', :type => 'text' }
390 assert_no_tag :tag => 'input',
391 :attributes => { :name => /^my$/, :type => 'text' }
392 end
393
394 def test_assert_tag_content_matching
395 @response.body = "<p>hello world</p>"
396 assert_tag :tag => "p", :content => "hello world"
397 assert_tag :tag => "p", :content => /hello/
398 assert_no_tag :tag => "p", :content => "hello"
399 end
400
401 def test_assert_generates
402 assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
403 assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action"}
404 assert_generates 'controller/action/5', {:controller => "controller", :action => "action", :id => "5", :name => "bob"}, {}, {:name => "bob"}
405 assert_generates 'controller/action/7', {:id => "7", :name => "bob"}, {:controller => "controller", :action => "action"}, {:name => "bob"}
406 assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action", :name => "bob"}, {}
407 end
408
409 def test_assert_routing
410 assert_routing 'content', :controller => 'content', :action => 'index'
411 end
412
413 def test_assert_routing_with_method
414 with_routing do |set|
415 set.draw { |map| map.resources(:content) }
416 assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
417 end
418 end
419
420 def test_assert_routing_in_module
421 assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
422 end
423
424 def test_params_passing
425 get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
426 parsed_params = eval(@response.body)
427 assert_equal(
428 {'controller' => 'test_test/test', 'action' => 'test_params',
429 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
430 parsed_params
431 )
432 end
433
434 def test_id_converted_to_string
435 get :test_params, :id => 20, :foo => Object.new
436 assert_kind_of String, @request.path_parameters['id']
437 end
438
439 def test_array_path_parameter_handled_properly
440 with_routing do |set|
441 set.draw do |map|
442 map.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params'
443 map.connect ':controller/:action/:id'
444 end
445
446 get :test_params, :path => ['hello', 'world']
447 assert_equal ['hello', 'world'], @request.path_parameters['path']
448 assert_equal 'hello/world', @request.path_parameters['path'].to_s
449 end
450 end
451
452 def test_assert_realistic_path_parameters
453 get :test_params, :id => 20, :foo => Object.new
454
455 # All elements of path_parameters should use string keys
456 @request.path_parameters.keys.each do |key|
457 assert_kind_of String, key
458 end
459 end
460
461 def test_with_routing_places_routes_back
462 assert ActionController::Routing::Routes
463 routes_id = ActionController::Routing::Routes.object_id
464
465 begin
466 with_routing { raise 'fail' }
467 fail 'Should not be here.'
468 rescue RuntimeError
469 end
470
471 assert ActionController::Routing::Routes
472 assert_equal routes_id, ActionController::Routing::Routes.object_id
473 end
474
475 def test_remote_addr
476 get :test_remote_addr
477 assert_equal "0.0.0.0", @response.body
478
479 @request.remote_addr = "192.0.0.1"
480 get :test_remote_addr
481 assert_equal "192.0.0.1", @response.body
482 end
483
484 def test_header_properly_reset_after_remote_http_request
485 xhr :get, :test_params
486 assert_nil @request.env['HTTP_X_REQUESTED_WITH']
487 end
488
489 def test_header_properly_reset_after_get_request
490 get :test_params
491 @request.recycle!
492 assert_nil @request.instance_variable_get("@request_method")
493 end
494
495 %w(controller response request).each do |variable|
496 %w(get post put delete head process).each do |method|
497 define_method("test_#{variable}_missing_for_#{method}_raises_error") do
498 remove_instance_variable "@#{variable}"
499 begin
500 send(method, :test_remote_addr)
501 assert false, "expected RuntimeError, got nothing"
502 rescue RuntimeError => error
503 assert true
504 assert_match %r{@#{variable} is nil}, error.message
505 rescue => error
506 assert false, "expected RuntimeError, got #{error.class}"
507 end
508 end
509 end
510 end
511
512 FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
513
514 if RUBY_VERSION < '1.9'
515 READ_BINARY = 'rb'
516 READ_PLAIN = 'r'
517 else
518 READ_BINARY = 'rb:binary'
519 READ_PLAIN = 'r:binary'
520 end
521
522 def test_test_uploaded_file
523 filename = 'mona_lisa.jpg'
524 path = "#{FILES_DIR}/#{filename}"
525 content_type = 'image/png'
526 expected = File.read(path)
527 expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding)
528
529 file = ActionController::TestUploadedFile.new(path, content_type)
530 assert_equal filename, file.original_filename
531 assert_equal content_type, file.content_type
532 assert_equal file.path, file.local_path
533 assert_equal expected, file.read
534
535 new_content_type = "new content_type"
536 file.content_type = new_content_type
537 assert_equal new_content_type, file.content_type
538
539 end
540
541 def test_test_uploaded_file_with_binary
542 filename = 'mona_lisa.jpg'
543 path = "#{FILES_DIR}/#{filename}"
544 content_type = 'image/png'
545
546 binary_uploaded_file = ActionController::TestUploadedFile.new(path, content_type, :binary)
547 assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read
548
549 plain_uploaded_file = ActionController::TestUploadedFile.new(path, content_type)
550 assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
551 end
552
553 def test_fixture_file_upload_with_binary
554 filename = 'mona_lisa.jpg'
555 path = "#{FILES_DIR}/#{filename}"
556 content_type = 'image/jpg'
557
558 binary_file_upload = fixture_file_upload(path, content_type, :binary)
559 assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
560
561 plain_file_upload = fixture_file_upload(path, content_type)
562 assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
563 end
564
565 def test_fixture_file_upload
566 post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
567 assert_equal '159528', @response.body
568 end
569
570 def test_test_uploaded_file_exception_when_file_doesnt_exist
571 assert_raise(RuntimeError) { ActionController::TestUploadedFile.new('non_existent_file') }
572 end
573
574 def test_redirect_url_only_cares_about_location_header
575 get :create
576 assert_response :created
577
578 # Redirect url doesn't care that it wasn't a :redirect response.
579 assert_equal 'created resource', @response.redirect_url
580 assert_equal @response.redirect_url, redirect_to_url
581
582 # Must be a :redirect response.
583 assert_raise(Test::Unit::AssertionFailedError) do
584 assert_redirected_to 'created resource'
585 end
586 end
587
588 def test_binary_content_works_with_send_file
589 get :test_send_file
590 assert_nothing_raised(NoMethodError) { @response.binary_content }
591 end
592
593 protected
594 def with_foo_routing
595 with_routing do |set|
596 set.draw do |map|
597 map.generate_url 'foo', :controller => 'test'
598 map.connect ':controller/:action/:id'
599 end
600 yield set
601 end
602 end
603 end
604
605 class CleanBacktraceTest < Test::Unit::TestCase
606 def test_should_reraise_the_same_object
607 exception = Test::Unit::AssertionFailedError.new('message')
608 clean_backtrace { raise exception }
609 rescue Exception => caught
610 assert_equal exception.object_id, caught.object_id
611 assert_equal exception.message, caught.message
612 end
613
614 def test_should_clean_assertion_lines_from_backtrace
615 path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller")
616 exception = Test::Unit::AssertionFailedError.new('message')
617 exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
618 clean_backtrace { raise exception }
619 rescue Exception => caught
620 assert_equal ["#{path}/abc"], caught.backtrace
621 end
622
623 def test_should_only_clean_assertion_failure_errors
624 clean_backtrace do
625 raise "can't touch this", [File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/assertions/abc")]
626 end
627 rescue => caught
628 assert !caught.backtrace.empty?
629 end
630 end
631
632 class InferringClassNameTest < Test::Unit::TestCase
633 def test_determine_controller_class
634 assert_equal ContentController, determine_class("ContentControllerTest")
635 end
636
637 def test_determine_controller_class_with_nonsense_name
638 assert_raises ActionController::NonInferrableControllerError do
639 determine_class("HelloGoodBye")
640 end
641 end
642
643 def test_determine_controller_class_with_sensible_name_where_no_controller_exists
644 assert_raises ActionController::NonInferrableControllerError do
645 determine_class("NoControllerWithThisNameTest")
646 end
647 end
648
649 private
650 def determine_class(name)
651 ActionController::TestCase.determine_default_controller_class(name)
652 end
653 end
654
655 class CrazyNameTest < ActionController::TestCase
656 tests ContentController
657
658 def test_controller_class_can_be_set_manually_not_just_inferred
659 assert_equal ContentController, self.class.controller_class
660 end
661 end
662
663 class NamedRoutesControllerTest < ActionController::TestCase
664 tests ContentController
665
666 def test_should_be_able_to_use_named_routes_before_a_request_is_done
667 with_routing do |set|
668 set.draw { |map| map.resources :contents }
669 assert_equal 'http://test.host/contents/new', new_content_url
670 assert_equal 'http://test.host/contents/1', content_url(:id => 1)
671 end
672 end
673 end