Froze rails gems
[depot.git] / vendor / rails / actionpack / lib / action_controller / assertions / selector_assertions.rb
1 #--
2 # Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
3 # Under MIT and/or CC By license.
4 #++
5
6 require 'rexml/document'
7 require 'html/document'
8
9 module ActionController
10 module Assertions
11 unless const_defined?(:NO_STRIP)
12 NO_STRIP = %w{pre script style textarea}
13 end
14
15 # Adds the +assert_select+ method for use in Rails functional
16 # test cases, which can be used to make assertions on the response HTML of a controller
17 # action. You can also call +assert_select+ within another +assert_select+ to
18 # make assertions on elements selected by the enclosing assertion.
19 #
20 # Use +css_select+ to select elements without making an assertions, either
21 # from the response HTML or elements selected by the enclosing assertion.
22 #
23 # In addition to HTML responses, you can make the following assertions:
24 # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations.
25 # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
26 # * +assert_select_email+ - Assertions on the HTML body of an e-mail.
27 #
28 # Also see HTML::Selector to learn how to use selectors.
29 module SelectorAssertions
30 # :call-seq:
31 # css_select(selector) => array
32 # css_select(element, selector) => array
33 #
34 # Select and return all matching elements.
35 #
36 # If called with a single argument, uses that argument as a selector
37 # to match all elements of the current page. Returns an empty array
38 # if no match is found.
39 #
40 # If called with two arguments, uses the first argument as the base
41 # element and the second argument as the selector. Attempts to match the
42 # base element and any of its children. Returns an empty array if no
43 # match is found.
44 #
45 # The selector may be a CSS selector expression (String), an expression
46 # with substitution values (Array) or an HTML::Selector object.
47 #
48 # ==== Examples
49 # # Selects all div tags
50 # divs = css_select("div")
51 #
52 # # Selects all paragraph tags and does something interesting
53 # pars = css_select("p")
54 # pars.each do |par|
55 # # Do something fun with paragraphs here...
56 # end
57 #
58 # # Selects all list items in unordered lists
59 # items = css_select("ul>li")
60 #
61 # # Selects all form tags and then all inputs inside the form
62 # forms = css_select("form")
63 # forms.each do |form|
64 # inputs = css_select(form, "input")
65 # ...
66 # end
67 #
68 def css_select(*args)
69 # See assert_select to understand what's going on here.
70 arg = args.shift
71
72 if arg.is_a?(HTML::Node)
73 root = arg
74 arg = args.shift
75 elsif arg == nil
76 raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
77 elsif @selected
78 matches = []
79
80 @selected.each do |selected|
81 subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
82 subset.each do |match|
83 matches << match unless matches.any? { |m| m.equal?(match) }
84 end
85 end
86
87 return matches
88 else
89 root = response_from_page_or_rjs
90 end
91
92 case arg
93 when String
94 selector = HTML::Selector.new(arg, args)
95 when Array
96 selector = HTML::Selector.new(*arg)
97 when HTML::Selector
98 selector = arg
99 else raise ArgumentError, "Expecting a selector as the first argument"
100 end
101
102 selector.select(root)
103 end
104
105 # :call-seq:
106 # assert_select(selector, equality?, message?)
107 # assert_select(element, selector, equality?, message?)
108 #
109 # An assertion that selects elements and makes one or more equality tests.
110 #
111 # If the first argument is an element, selects all matching elements
112 # starting from (and including) that element and all its children in
113 # depth-first order.
114 #
115 # If no element if specified, calling +assert_select+ will select from the
116 # response HTML. Calling #assert_select inside an +assert_select+ block will
117 # run the assertion for each element selected by the enclosing assertion.
118 #
119 # ==== Example
120 # assert_select "ol>li" do |elements|
121 # elements.each do |element|
122 # assert_select element, "li"
123 # end
124 # end
125 #
126 # Or for short:
127 # assert_select "ol>li" do
128 # assert_select "li"
129 # end
130 #
131 # The selector may be a CSS selector expression (String), an expression
132 # with substitution values, or an HTML::Selector object.
133 #
134 # === Equality Tests
135 #
136 # The equality test may be one of the following:
137 # * <tt>true</tt> - Assertion is true if at least one element selected.
138 # * <tt>false</tt> - Assertion is true if no element selected.
139 # * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
140 # one element matches the string or regular expression.
141 # * <tt>Integer</tt> - Assertion is true if exactly that number of
142 # elements are selected.
143 # * <tt>Range</tt> - Assertion is true if the number of selected
144 # elements fit the range.
145 # If no equality test specified, the assertion is true if at least one
146 # element selected.
147 #
148 # To perform more than one equality tests, use a hash with the following keys:
149 # * <tt>:text</tt> - Narrow the selection to elements that have this text
150 # value (string or regexp).
151 # * <tt>:html</tt> - Narrow the selection to elements that have this HTML
152 # content (string or regexp).
153 # * <tt>:count</tt> - Assertion is true if the number of selected elements
154 # is equal to this value.
155 # * <tt>:minimum</tt> - Assertion is true if the number of selected
156 # elements is at least this value.
157 # * <tt>:maximum</tt> - Assertion is true if the number of selected
158 # elements is at most this value.
159 #
160 # If the method is called with a block, once all equality tests are
161 # evaluated the block is called with an array of all matched elements.
162 #
163 # ==== Examples
164 #
165 # # At least one form element
166 # assert_select "form"
167 #
168 # # Form element includes four input fields
169 # assert_select "form input", 4
170 #
171 # # Page title is "Welcome"
172 # assert_select "title", "Welcome"
173 #
174 # # Page title is "Welcome" and there is only one title element
175 # assert_select "title", {:count=>1, :text=>"Welcome"},
176 # "Wrong title or more than one title element"
177 #
178 # # Page contains no forms
179 # assert_select "form", false, "This page must contain no forms"
180 #
181 # # Test the content and style
182 # assert_select "body div.header ul.menu"
183 #
184 # # Use substitution values
185 # assert_select "ol>li#?", /item-\d+/
186 #
187 # # All input fields in the form have a name
188 # assert_select "form input" do
189 # assert_select "[name=?]", /.+/ # Not empty
190 # end
191 def assert_select(*args, &block)
192 # Start with optional element followed by mandatory selector.
193 arg = args.shift
194
195 if arg.is_a?(HTML::Node)
196 # First argument is a node (tag or text, but also HTML root),
197 # so we know what we're selecting from.
198 root = arg
199 arg = args.shift
200 elsif arg == nil
201 # This usually happens when passing a node/element that
202 # happens to be nil.
203 raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
204 elsif @selected
205 root = HTML::Node.new(nil)
206 root.children.concat @selected
207 else
208 # Otherwise just operate on the response document.
209 root = response_from_page_or_rjs
210 end
211
212 # First or second argument is the selector: string and we pass
213 # all remaining arguments. Array and we pass the argument. Also
214 # accepts selector itself.
215 case arg
216 when String
217 selector = HTML::Selector.new(arg, args)
218 when Array
219 selector = HTML::Selector.new(*arg)
220 when HTML::Selector
221 selector = arg
222 else raise ArgumentError, "Expecting a selector as the first argument"
223 end
224
225 # Next argument is used for equality tests.
226 equals = {}
227 case arg = args.shift
228 when Hash
229 equals = arg
230 when String, Regexp
231 equals[:text] = arg
232 when Integer
233 equals[:count] = arg
234 when Range
235 equals[:minimum] = arg.begin
236 equals[:maximum] = arg.end
237 when FalseClass
238 equals[:count] = 0
239 when NilClass, TrueClass
240 equals[:minimum] = 1
241 else raise ArgumentError, "I don't understand what you're trying to match"
242 end
243
244 # By default we're looking for at least one match.
245 if equals[:count]
246 equals[:minimum] = equals[:maximum] = equals[:count]
247 else
248 equals[:minimum] = 1 unless equals[:minimum]
249 end
250
251 # Last argument is the message we use if the assertion fails.
252 message = args.shift
253 #- message = "No match made with selector #{selector.inspect}" unless message
254 if args.shift
255 raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
256 end
257
258 matches = selector.select(root)
259 # If text/html, narrow down to those elements that match it.
260 content_mismatch = nil
261 if match_with = equals[:text]
262 matches.delete_if do |match|
263 text = ""
264 text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding)
265 stack = match.children.reverse
266 while node = stack.pop
267 if node.tag?
268 stack.concat node.children.reverse
269 else
270 content = node.content
271 content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding)
272 text << content
273 end
274 end
275 text.strip! unless NO_STRIP.include?(match.name)
276 unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
277 content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text)
278 true
279 end
280 end
281 elsif match_with = equals[:html]
282 matches.delete_if do |match|
283 html = match.children.map(&:to_s).join
284 html.strip! unless NO_STRIP.include?(match.name)
285 unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
286 content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html)
287 true
288 end
289 end
290 end
291 # Expecting foo found bar element only if found zero, not if
292 # found one but expecting two.
293 message ||= content_mismatch if matches.empty?
294 # Test minimum/maximum occurrence.
295 min, max = equals[:minimum], equals[:maximum]
296 message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.)
297 assert matches.size >= min, message if min
298 assert matches.size <= max, message if max
299
300 # If a block is given call that block. Set @selected to allow
301 # nested assert_select, which can be nested several levels deep.
302 if block_given? && !matches.empty?
303 begin
304 in_scope, @selected = @selected, matches
305 yield matches
306 ensure
307 @selected = in_scope
308 end
309 end
310
311 # Returns all matches elements.
312 matches
313 end
314
315 def count_description(min, max) #:nodoc:
316 pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
317
318 if min && max && (max != min)
319 "between #{min} and #{max} elements"
320 elsif min && !(min == 1 && max == 1)
321 "at least #{min} #{pluralize['element', min]}"
322 elsif max
323 "at most #{max} #{pluralize['element', max]}"
324 end
325 end
326
327 # :call-seq:
328 # assert_select_rjs(id?) { |elements| ... }
329 # assert_select_rjs(statement, id?) { |elements| ... }
330 # assert_select_rjs(:insert, position, id?) { |elements| ... }
331 #
332 # Selects content from the RJS response.
333 #
334 # === Narrowing down
335 #
336 # With no arguments, asserts that one or more elements are updated or
337 # inserted by RJS statements.
338 #
339 # Use the +id+ argument to narrow down the assertion to only statements
340 # that update or insert an element with that identifier.
341 #
342 # Use the first argument to narrow down assertions to only statements
343 # of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>,
344 # <tt>:show</tt>, <tt>:hide</tt>, <tt>:toggle</tt>, <tt>:remove</tt> and
345 # <tt>:insert_html</tt>.
346 #
347 # Use the argument <tt>:insert</tt> followed by an insertion position to narrow
348 # down the assertion to only statements that insert elements in that
349 # position. Possible values are <tt>:top</tt>, <tt>:bottom</tt>, <tt>:before</tt>
350 # and <tt>:after</tt>.
351 #
352 # Using the <tt>:remove</tt> statement, you will be able to pass a block, but it will
353 # be ignored as there is no HTML passed for this statement.
354 #
355 # === Using blocks
356 #
357 # Without a block, +assert_select_rjs+ merely asserts that the response
358 # contains one or more RJS statements that replace or update content.
359 #
360 # With a block, +assert_select_rjs+ also selects all elements used in
361 # these statements and passes them to the block. Nested assertions are
362 # supported.
363 #
364 # Calling +assert_select_rjs+ with no arguments and using nested asserts
365 # asserts that the HTML content is returned by one or more RJS statements.
366 # Using +assert_select+ directly makes the same assertion on the content,
367 # but without distinguishing whether the content is returned in an HTML
368 # or JavaScript.
369 #
370 # ==== Examples
371 #
372 # # Replacing the element foo.
373 # # page.replace 'foo', ...
374 # assert_select_rjs :replace, "foo"
375 #
376 # # Replacing with the chained RJS proxy.
377 # # page[:foo].replace ...
378 # assert_select_rjs :chained_replace, 'foo'
379 #
380 # # Inserting into the element bar, top position.
381 # assert_select_rjs :insert, :top, "bar"
382 #
383 # # Remove the element bar
384 # assert_select_rjs :remove, "bar"
385 #
386 # # Changing the element foo, with an image.
387 # assert_select_rjs "foo" do
388 # assert_select "img[src=/images/logo.gif""
389 # end
390 #
391 # # RJS inserts or updates a list with four items.
392 # assert_select_rjs do
393 # assert_select "ol>li", 4
394 # end
395 #
396 # # The same, but shorter.
397 # assert_select "ol>li", 4
398 def assert_select_rjs(*args, &block)
399 rjs_type = args.first.is_a?(Symbol) ? args.shift : nil
400 id = args.first.is_a?(String) ? args.shift : nil
401
402 # If the first argument is a symbol, it's the type of RJS statement we're looking
403 # for (update, replace, insertion, etc). Otherwise, we're looking for just about
404 # any RJS statement.
405 if rjs_type
406 if rjs_type == :insert
407 position = args.shift
408 insertion = "insert_#{position}".to_sym
409 raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion]
410 statement = "(#{RJS_STATEMENTS[insertion]})"
411 else
412 raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
413 statement = "(#{RJS_STATEMENTS[rjs_type]})"
414 end
415 else
416 statement = "#{RJS_STATEMENTS[:any]}"
417 end
418
419 # Next argument we're looking for is the element identifier. If missing, we pick
420 # any element, otherwise we replace it in the statement.
421 pattern = Regexp.new(
422 id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement
423 )
424
425 # Duplicate the body since the next step involves destroying it.
426 matches = nil
427 case rjs_type
428 when :remove, :show, :hide, :toggle
429 matches = @response.body.match(pattern)
430 else
431 @response.body.gsub(pattern) do |match|
432 html = unescape_rjs(match)
433 matches ||= []
434 matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
435 ""
436 end
437 end
438
439 if matches
440 assert_block("") { true } # to count the assertion
441 if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
442 begin
443 in_scope, @selected = @selected, matches
444 yield matches
445 ensure
446 @selected = in_scope
447 end
448 end
449 matches
450 else
451 # RJS statement not found.
452 case rjs_type
453 when :remove, :show, :hide, :toggle
454 flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered."
455 else
456 flunk_message = "No RJS statement that replaces or inserts HTML content."
457 end
458 flunk args.shift || flunk_message
459 end
460 end
461
462 # :call-seq:
463 # assert_select_encoded(element?) { |elements| ... }
464 #
465 # Extracts the content of an element, treats it as encoded HTML and runs
466 # nested assertion on it.
467 #
468 # You typically call this method within another assertion to operate on
469 # all currently selected elements. You can also pass an element or array
470 # of elements.
471 #
472 # The content of each element is un-encoded, and wrapped in the root
473 # element +encoded+. It then calls the block with all un-encoded elements.
474 #
475 # ==== Examples
476 # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix)
477 # assert_select_feed :atom, 1.0 do
478 # # Select each entry item and then the title item
479 # assert_select "entry>title" do
480 # # Run assertions on the encoded title elements
481 # assert_select_encoded do
482 # assert_select "b"
483 # end
484 # end
485 # end
486 #
487 #
488 # # Selects all paragraph tags from within the description of an RSS feed
489 # assert_select_feed :rss, 2.0 do
490 # # Select description element of each feed item.
491 # assert_select "channel>item>description" do
492 # # Run assertions on the encoded elements.
493 # assert_select_encoded do
494 # assert_select "p"
495 # end
496 # end
497 # end
498 def assert_select_encoded(element = nil, &block)
499 case element
500 when Array
501 elements = element
502 when HTML::Node
503 elements = [element]
504 when nil
505 unless elements = @selected
506 raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
507 end
508 else
509 raise ArgumentError, "Argument is optional, and may be node or array of nodes"
510 end
511
512 fix_content = lambda do |node|
513 # Gets around a bug in the Rails 1.1 HTML parser.
514 node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) }
515 end
516
517 selected = elements.map do |element|
518 text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
519 root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
520 css_select(root, "encoded:root", &block)[0]
521 end
522
523 begin
524 old_selected, @selected = @selected, selected
525 assert_select ":root", &block
526 ensure
527 @selected = old_selected
528 end
529 end
530
531 # :call-seq:
532 # assert_select_email { }
533 #
534 # Extracts the body of an email and runs nested assertions on it.
535 #
536 # You must enable deliveries for this assertion to work, use:
537 # ActionMailer::Base.perform_deliveries = true
538 #
539 # ==== Examples
540 #
541 # assert_select_email do
542 # assert_select "h1", "Email alert"
543 # end
544 #
545 # assert_select_email do
546 # items = assert_select "ol>li"
547 # items.each do
548 # # Work with items here...
549 # end
550 # end
551 #
552 def assert_select_email(&block)
553 deliveries = ActionMailer::Base.deliveries
554 assert !deliveries.empty?, "No e-mail in delivery list"
555
556 for delivery in deliveries
557 for part in delivery.parts
558 if part["Content-Type"].to_s =~ /^text\/html\W/
559 root = HTML::Document.new(part.body).root
560 assert_select root, ":root", &block
561 end
562 end
563 end
564 end
565
566 protected
567 unless const_defined?(:RJS_STATEMENTS)
568 RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
569 RJS_ANY_ID = "\"([^\"])*\""
570 RJS_STATEMENTS = {
571 :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)",
572 :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)",
573 :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)",
574 :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)"
575 }
576 [:remove, :show, :hide, :toggle].each do |action|
577 RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)"
578 end
579 RJS_INSERTIONS = ["top", "bottom", "before", "after"]
580 RJS_INSERTIONS.each do |insertion|
581 RJS_STATEMENTS["insert_#{insertion}".to_sym] = "Element.insert\\(#{RJS_ANY_ID}, \\{ #{insertion}: #{RJS_PATTERN_HTML} \\}\\)"
582 end
583 RJS_STATEMENTS[:insert_html] = "Element.insert\\(#{RJS_ANY_ID}, \\{ (#{RJS_INSERTIONS.join('|')}): #{RJS_PATTERN_HTML} \\}\\)"
584 RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
585 RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
586 end
587
588 # +assert_select+ and +css_select+ call this to obtain the content in the HTML
589 # page, or from all the RJS statements, depending on the type of response.
590 def response_from_page_or_rjs()
591 content_type = @response.content_type
592
593 if content_type && content_type =~ /text\/javascript/
594 body = @response.body.dup
595 root = HTML::Node.new(nil)
596
597 while true
598 next if body.sub!(RJS_STATEMENTS[:any]) do |match|
599 html = unescape_rjs(match)
600 matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
601 root.children.concat matches
602 ""
603 end
604 break
605 end
606
607 root
608 else
609 html_document.root
610 end
611 end
612
613 # Unescapes a RJS string.
614 def unescape_rjs(rjs_string)
615 # RJS encodes double quotes and line breaks.
616 unescaped= rjs_string.gsub('\"', '"')
617 unescaped.gsub!(/\\\//, '/')
618 unescaped.gsub!('\n', "\n")
619 unescaped.gsub!('\076', '>')
620 unescaped.gsub!('\074', '<')
621 # RJS encodes non-ascii characters.
622 unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
623 unescaped
624 end
625 end
626 end
627 end