Module: Test::Unit::Assertions

Defined in:
lib/assert2.rb,
lib/assert2/rjs.rb,
lib/assert2/flunk.rb,
lib/assert2/xhtml.rb,
lib/assert2/xpath.rb,
lib/assert2/ripper_reflector.rb,
lib/assert2/rubynode_reflector.rb

Defined Under Namespace

Modules: Coulor Classes: AssertRjs, AssertXPathArguments, RubyReflector

Constant Summary collapse

FlunkError =
if defined? Test::Unit::AssertionFailedError
  Test::Unit::AssertionFailedError
else
  MiniTest::Assertion
end

Instance Method Summary collapse

Instance Method Details

#__interpret_rjs(response, command, *args, &block) ⇒ Object



186
187
188
189
190
191
192
193
# File 'lib/assert2/rjs.rb', line 186

def __interpret_rjs(response, command, *args, &block)
  klass = command.to_s.upcase
  klass = eval("AssertRjs::#{klass}") rescue
    flunk("#{command} not implemented!")
  asserter = klass.new(response, command, self)
  sample = asserter.pwn(*args, &block)
  return sample, asserter
end

#_assert_raise(*args) ⇒ Object

TODO reinstall ruby-1.9.0 and pass all cross-tests!!



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/assert2/flunk.rb', line 60

def _assert_raise(*args)
#        _wrap_assertion do
    if Module === args.last
      message = ""
    else
      message = args.pop
    end
    exceptions, modules = args, [] # _check_exception_class(args)

    expected = args.size == 1 ? args.first : args
    actual_exception = nil
    full_message = build_message(message, "<?> exception expected but none was thrown.", expected)
    assert_block(full_message) do
      begin
        yield
      rescue Exception => actual_exception
        break
      end
      false
    end
    full_message = build_message(message, "<?> exception expected but was\n?", expected, actual_exception)
    assert_block(full_message) {exceptions.include?(actual_exception.class)}
    actual_exception
  #      end
end

#_assert_xml(xml) ⇒ Object

, parser = XML::Parser)



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/assert2/xpath.rb', line 14

def _assert_xml(xml) #, parser = XML::Parser)
  if false
    xp = parser.new()
    xp.string = xml
    
    if XML.respond_to? :'default_pedantic_parser='
      XML.default_pedantic_parser = true
    else
      XML::Parser.default_pedantic_parser = true
    end  #  CONSIDER  uh, figure out the best libxml-ruby??
    
    @xdoc = xp.parse.root
  else
    #  CONSIDER  figure out how entities are supposed to work!!
    xml = xml.gsub('&mdash;', '--')
    doc = REXML::Document.new(xml)
    @xdoc = doc.root
  end
end

#_assert_xml_(xml) ⇒ Object

, parser = XML::Parser)



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/assert2/xpath.rb', line 38

def _assert_xml_(xml) #, parser = XML::Parser)
  if false
    xp = parser.new()
    xp.string = xml
    
    if XML.respond_to? :'default_pedantic_parser='
      XML.default_pedantic_parser = true
    else
      XML::Parser.default_pedantic_parser = true
    end  #  CONSIDER  uh, figure out the best libxml-ruby??
    
    @xdoc = xp.parse.root
  else
    #  TODO  figure out how entities are supposed to work!!
    xml = xml.gsub('&mdash;', '--')
    doc = Nokogiri::XML(xml)
    @xdoc = doc.root
  end
end

#add_assertionObject



189
190
191
# File 'lib/assert2.rb', line 189

def add_assertion
  self._assertions += 1
end

#add_diagnostic(whatever = nil, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/assert2.rb', line 37

def add_diagnostic(whatever = nil, &block)
  @__additional_diagnostics ||= []  #  TODO move that inside the reflector object, and persist it thru a test case event
  
  if whatever == :clear
    @__additional_diagnostics = []
    whatever = nil
  end
  
  @__additional_diagnostics += [whatever, block]  # note .compact will take care of them if they don't exist
end

#add_exception(ex) ⇒ Object



221
222
223
224
225
# File 'lib/assert2.rb', line 221

def add_exception(ex)
  ex.backtrace[0..10].each do |line|
    add_diagnostic '  ' + line
  end
end

#assert(*args, &block) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/assert2.rb', line 48

def assert(*args, &block)
#  This assertion calls a block, and faults if it returns
#  +false+ or +nil+. The fault diagnostic will reflect the
#  assertion's complete source - with comments - and will
#  reevaluate the every variable and expression in the
#  block.
#
#  The first argument can be a diagnostic string:
#
#    assert("foo failed"){ foo() }
#
#  The fault diagnostic will print that line.
# 
#  The next time you think to write any of these assertions...
#  
#  - +assert+
#  - +assert_equal+
#  - +assert_instance_of+
#  - +assert_kind_of+
#  - +assert_operator+
#  - +assert_match+
#  - +assert_not_nil+
#  
#  use <code>assert{ 2.1 }</code> instead.
#
#  If no block is provided, the assertion calls +assert_classic+,
#  which simulates RubyUnit's standard <code>assert()</code>.
  if block
    assert_ *args, &block
  else
    assert_classic *args
  end
  return true # or die trying ;-)
end

#assert_(diagnostic = nil, options = {}, &block) ⇒ Object

The new assert() calls this to interpret

blocks of assertive statements.


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/assert2.rb', line 204

def assert_(diagnostic = nil, options = {}, &block)
  options[:keep_diagnostics] or add_diagnostic :clear
  
  begin
    if got = block.call(*options[:args])
      add_assertion
      return got
    end
  rescue FlunkError
    raise  #  asserts inside assertions that fail do not decorate the outer assertion
  rescue => got
    add_exception got
  end

  flunk diagnose(diagnostic, got, caller[1], options, block)
end

#assert_classic(boolean, message = nil) ⇒ Object



179
180
181
182
183
184
185
186
187
# File 'lib/assert2.rb', line 179

def assert_classic(test, msg=nil)
  msg ||= "Failed assertion, no message given."
  self._assertions += 1
  unless test then
    msg = msg.call if Proc === msg
    raise MiniTest::Assertion, msg
  end
  true
end

#assert_flunk(matcher, message = nil, &block) ⇒ Object



54
55
56
# File 'lib/assert2/flunk.rb', line 54

def assert_flunk(matcher, message = nil, &block)
  assert_raise_message FlunkError, matcher, message, &block
end

#assert_no_rjs_(*args, &block) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/assert2/rjs.rb', line 208

def assert_no_rjs_(*args, &block)
  if args.first.class == Symbol
    command, *args = *args
    response = @response.body
  else
    response, command, *args = *args  #  TODO  test me!
  end
  
  sample, asserter = __interpret_rjs(response, command, *args, &block)
  asserter.failure_message and return sample
  flunk("should not find #{sample.inspect} in\n#{asserter.js}") #  TODO  complaint system
end

#assert_raise_message(types, expected_message, message = nil, &block) ⇒ Object

Assert that a block raises a given Exception type matching a given message

  • types - single exception class or array of classes

  • matcher - Regular Expression to match the inner_text of XML nodes

  • diagnostic - optional string to add to failure message

  • block - Ruby statements that should raise an exception

Examples: %transclude AssertXPathSuite#test_assert_raise_message_detects_assertion_failure

%transclude AssertXPathSuite#test_assert_raise_message_raises_message

See: assert_raise - Don’t Just Say “No”



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/assert2/flunk.rb', line 21

def assert_raise_message(types, expected_message, message = nil, &block)
  args = [types].flatten + [message]
  exception = _assert_raise(*args, &block)
  exception_message = exception.message.dup
  
  if expected_message.kind_of? String
    exception_message.gsub!(/^\s+/, '')  #  if we cosmetically strip leading spaces from both the matcher and matchee,
    expected_message.gsub!(/^\s+/, '')  #  then multi-line assert_flunk messages are easier on the eyes!
    expected_message = Regexp.escape(expected_message)
  end

  assert message do
    exception_message.match(expected_message)
  end
  
  return exception.message
end

#assert_rjs_(*args, &block) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/assert2/rjs.rb', line 195

def assert_rjs_(*args, &block)
  if args.first.class == Symbol
    command, *args = *args
    response = @response.body
  else
    response, command, *args = *args
  end
  
  sample, asserter = __interpret_rjs(response, command, *args, &block)
  asserter.failure_message and flunk(asserter.failure_message)
  return sample
end

#assert_xhtml(xhtml) ⇒ Object

ERGO merge



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/assert2/xhtml.rb', line 322

def assert_xhtml(*args, &block)  # ERGO merge
  xhtml, message = args
  
  if @response and message.nil?
    message = xhtml
    xhtml = @response.body
  end
  
  if block
    matcher = BeHtmlWith.new(self, &block)
    matcher.message = message
    matcher.matches?(xhtml, &block)
    message = matcher.failure_message
    flunk message if message.to_s != ''
    return matcher.returnable
  else
   _assert_xml(xhtml)
    return @xdoc
  end
end

#assert_xhtml_(xhtml) ⇒ Object



34
35
36
# File 'lib/assert2/xpath.rb', line 34

def assert_xhtml_(xhtml)
  return _assert_xml_(xhtml) # , XML::HTMLParser)
end

#assert_yin_yang(*args, &block) ⇒ Object

wrap this common idiom:

  foo = assemble()
  deny{ foo.bar() }
  foo.activate()
  assert{ foo.bar() }

that becomes:
  foo = assemble()

  assert_yin_yang proc{ foo.bar() } do
    foo.activate()
  end


311
312
313
314
315
316
317
318
319
320
321
# File 'lib/assert2.rb', line 311

def assert_yin_yang(*args, &block)
    # prock(s), diagnostic = nil, &block)
  procks, diagnostic = args.partition{|p| p.respond_to? :call }
  block ||= procks.shift
  source = reflect_source(&block)
  fuss = [diagnostic, "fault before calling:", source].compact.join("\n")
  procks.each do |prock|  deny(fuss, &prock);  end
  block.call
  fuss = [diagnostic, "fault after calling:", source].compact.join("\n")
  procks.each do |prock|  assert(fuss, &prock);  end
end

#colorize(to_color) ⇒ Object



169
170
171
# File 'lib/assert2.rb', line 169

def colorize(to_color)
  RubyReflector.new.colorize(to_color)
end

#deny(diagnostic = nil, options = {}, &block) ⇒ Object Also known as: denigh

This assertion replaces:

- +assert_nil+
- +assert_no_match+
- +assert_not_equal+

It faults, and prints its block's contents and values,
if its block returns non-+false+ and non-+nil+.


236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/assert2.rb', line 236

def deny(diagnostic = nil, options = {}, &block)
    #  "None shall pass!" --the Black Knight
    
  options[:keep_diagnostics] or add_diagnostic :clear
  
  begin
    got = block.call(*options[:args]) or (add_assertion ; return true)
  rescue FlunkError
    raise
  rescue => got
    add_exception got
  end

  flunk diagnose(diagnostic, got, caller[0], options, block)
end

#deny_(diagnostic = nil, options = {}, &block) ⇒ Object

“You’re a looney!” – King Arthur



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/assert2.rb', line 252

def deny_(diagnostic = nil, options = {}, &block)
    #  "None shall pass!" --the Black Knight
    
  options[:keep_diagnostics] or add_diagnostic :clear
  
  begin
    got = block.call(*options[:args]) or (add_assertion ; return true)
  rescue FlunkError
    raise
  rescue => got
    add_exception got
  end

  flunk diagnose(diagnostic, got, caller[0], options, block)
end

#deny_raise_message(types, matcher, diagnostic = nil, &block) ⇒ Object

TODO rebuild this



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/assert2/flunk.rb', line 40

def deny_raise_message(types, matcher, diagnostic = nil, &block) #:nodoc:
  exception = assert_raise_message(types, //, diagnostic, &block)
  
  assert_no_match matcher,
               exception.message,
               [ diagnostic, 
                 "exception #{ exception.class.name 
                   } with this message should not raise from block:", 
                 "\t"+reflect_source(&block).split("\n").join("\n\t")
                 ].compact.join("\n")
  
  return exception.message
end

#deny_yin_yang(*args, &block) ⇒ Object

the prock assertion must pass on both sides of the called block



325
326
327
328
329
330
331
332
333
334
335
# File 'lib/assert2.rb', line 325

def deny_yin_yang(*args, &block)
    # prock(s), diagnostic = nil, &block)
  procks, diagnostic = args.partition{|p| p.respond_to? :call }
  block ||= procks.shift
  source = reflect_source(&block)
  fuss = [diagnostic, "fault before calling:", source].compact.join("\n")
  procks.each do |prock|  assert(fuss, &prock);  end
  block.call
  fuss = [diagnostic, "fault after calling:", source].compact.join("\n")
  procks.each do |prock|  assert(fuss, &prock);  end
end

#diagnose(diagnostic = nil, got = nil, called = , options = {}, block = nil) ⇒ Object

!doc!



287
288
289
290
291
292
293
294
295
# File 'lib/assert2.rb', line 287

def diagnose(diagnostic = nil, got = nil, called = caller[0],
              options = {}, block = nil)                    #   TODO  make this directly callable
  rf = RubyReflector.new
  rf.diagnose(diagnostic, got, called, options, block, @__additional_diagnostics)
  #~ options = { :args => [] }.merge(options)
   #~ # CONSIDER only capture the block_vars if there be args?
  #~ @__additional_diagnostics.unshift diagnostic
  #~ return __build_message(__reflect_assertion(called, options, block, got))
end

#indent_xml(node = @xdoc) ⇒ Object

TODO trap LibXML::XML::XPath::InvalidPath and explicate it’s an XPath problem



158
159
160
161
162
163
# File 'lib/assert2/xpath.rb', line 158

def indent_xml(node = @xdoc)
  bar = REXML::Formatters::Pretty.new
  out = String.new
  bar.write(node, out)
  return out
end

#reflect(&block) ⇒ Object

This reflects a block of code, by evaluating it, reflecting its

source, and reflecting all its intermediate values


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/assert2/rubynode_reflector.rb', line 33

def reflect(&block)
  result = block.call
  rf = RubyReflector.new
  rf.block = block
  
  begin
    waz = rf.colorize?
    rf.colorize(false)
    return rf.result + rf.arrow_result(result) + "\n" + rf.format_evaluations
  ensure
    rf.colorize(waz)
  end
end

#reflect_source(&block) ⇒ Object

This reflects a block of code, /without/ evaluating it.

The function only compiles the source and reflects it as
a string of disassembled Ruby


51
52
53
# File 'lib/assert2/rubynode_reflector.rb', line 51

def reflect_source(&block)
  RubyReflector.new(nil, block, false).result
end

#reflect_string(string) ⇒ Object

This compiles a string and reflects its source…

as another string.


58
59
60
61
62
63
64
65
# File 'lib/assert2/rubynode_reflector.rb', line 58

def reflect_string(string)
  rf = RubyReflector.new # def initialize
  rf.block = proc{}
  rf.reflect_values = false
    # pp string.parse_to_nodes.transform
  got = rf.reflect_nodes(string.parse_to_nodes)
  return got
end

#wrap_expectation(whatever) ⇒ Object



320
# File 'lib/assert2/xhtml.rb', line 320

def wrap_expectation whatever;  yield;  end

#xpath(path, id = nil, options = {}, &block) ⇒ Object

if node = @xdoc.find_first(path) ## for libxml

def node.text
  find_first('text()').to_s
end


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/assert2/xpath.rb', line 102

def xpath(path, id = nil, options = {}, &block)
  former_xdoc = @xdoc
  apa = AssertXPathArguments.new(path, id, options)
  node = REXML::XPath.first(@xdoc, apa.xpath, nil, apa.subs)
  
  add_diagnostic :clear do
    diagnostic = "xpath: #{ apa.xpath.inspect }\n"
    diagnostic << "arguments: #{ apa.subs.pretty_inspect }\n" if apa.subs.any?
    diagnostic + "xml context:\n" + indent_xml
  end

  if node
    def node.[](symbol)
      return attributes[symbol.to_s]
    end
  end

  if block
    assert_('this xpath cannot find a node', :keep_diagnostics => true){ node }
    assert_ nil, :args => [@xdoc = node], :keep_diagnostics => true, &block  #  TODO  need the _ ?
  end
  
  return node
  # TODO raid http://thebogles.com/blog/an-hpricot-style-interface-to-libxml/
ensure
  @xdoc = former_xdoc
end

#xpath_(path, id = nil, options = {}, &block) ⇒ Object

TODO trap LibXML::XML::XPath::InvalidPath and explicate it’s an XPath problem



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/assert2/xpath.rb', line 130

def xpath_(path, id = nil, options = {}, &block)
  former_xdoc = @xdoc
  apa = AssertXPathArguments.new(path, id, options)
  node = @xdoc.xpath(apa.xpath) #, nil, apa.subs)
     
  add_diagnostic :clear do
    diagnostic = "xpath: #{ apa.xpath.inspect }\n"
    diagnostic << "arguments: #{ apa.subs.pretty_inspect }\n" if apa.subs.any?
    diagnostic + "xml context:\n" + indent_xml
  end

  if node
    def node.[](symbol)
      return attributes[symbol.to_s]
    end
  end

  if block
    assert_('this xpath cannot find a node', :keep_diagnostics => true){ node }
    assert_ nil, :args => [@xdoc = node], :keep_diagnostics => true, &block  #  TODO  need the _ ?
  end
  
  return node
  # TODO raid http://thebogles.com/blog/an-hpricot-style-interface-to-libxml/
ensure
  @xdoc = former_xdoc
end