PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/jruby-1.7.3/lib/ruby/1.8/test/unit/assertions.rb

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Ruby | 622 lines | 376 code | 76 blank | 170 comment | 22 complexity | 3153a5444e41087f2a30dd3c619e1019 MD5 | raw file
  1. # Author:: Nathaniel Talbott.
  2. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
  3. # License:: Ruby license.
  4. require 'test/unit/assertionfailederror'
  5. require 'test/unit/util/backtracefilter'
  6. module Test
  7. module Unit
  8. ##
  9. # Test::Unit::Assertions contains the standard Test::Unit assertions.
  10. # Assertions is included in Test::Unit::TestCase.
  11. #
  12. # To include it in your own code and use its functionality, you simply
  13. # need to rescue Test::Unit::AssertionFailedError. Additionally you may
  14. # override add_assertion to get notified whenever an assertion is made.
  15. #
  16. # Notes:
  17. # * The message to each assertion, if given, will be propagated with the
  18. # failure.
  19. # * It is easy to add your own assertions based on assert_block().
  20. #
  21. # = Example Custom Assertion
  22. #
  23. # def deny(boolean, message = nil)
  24. # message = build_message message, '<?> is not false or nil.', boolean
  25. # assert_block message do
  26. # not boolean
  27. # end
  28. # end
  29. module Assertions
  30. ##
  31. # The assertion upon which all other assertions are based. Passes if the
  32. # block yields true.
  33. #
  34. # Example:
  35. # assert_block "Couldn't do the thing" do
  36. # do_the_thing
  37. # end
  38. public
  39. def assert_block(message="assert_block failed.") # :yields:
  40. _wrap_assertion do
  41. if (! yield)
  42. raise AssertionFailedError.new(message.to_s)
  43. end
  44. end
  45. end
  46. ##
  47. # Asserts that +boolean+ is not false or nil.
  48. #
  49. # Example:
  50. # assert [1, 2].include?(5)
  51. public
  52. def assert(boolean, message=nil)
  53. _wrap_assertion do
  54. assert_block("assert should not be called with a block.") { !block_given? }
  55. assert_block(build_message(message, "<?> is not true.", boolean)) { boolean }
  56. end
  57. end
  58. ##
  59. # Passes if +expected+ == +actual.
  60. #
  61. # Note that the ordering of arguments is important, since a helpful
  62. # error message is generated when this one fails that tells you the
  63. # values of expected and actual.
  64. #
  65. # Example:
  66. # assert_equal 'MY STRING', 'my string'.upcase
  67. public
  68. def assert_equal(expected, actual, message=nil)
  69. full_message = build_message(message, <<EOT, expected, actual)
  70. <?> expected but was
  71. <?>.
  72. EOT
  73. assert_block(full_message) { expected == actual }
  74. end
  75. private
  76. def _check_exception_class(args) # :nodoc:
  77. args.partition do |klass|
  78. next if klass.instance_of?(Module)
  79. assert(Exception >= klass, "Should expect a class of exception, #{klass}")
  80. true
  81. end
  82. end
  83. private
  84. def _expected_exception?(actual_exception, exceptions, modules) # :nodoc:
  85. exceptions.include?(actual_exception.class) or
  86. modules.any? {|mod| actual_exception.is_a?(mod)}
  87. end
  88. ##
  89. # Passes if the block raises one of the given exceptions.
  90. #
  91. # Example:
  92. # assert_raise RuntimeError, LoadError do
  93. # raise 'Boom!!!'
  94. # end
  95. public
  96. def assert_raise(*args)
  97. _wrap_assertion do
  98. if Module === args.last
  99. message = ""
  100. else
  101. message = args.pop
  102. end
  103. exceptions, modules = _check_exception_class(args)
  104. expected = args.size == 1 ? args.first : args
  105. actual_exception = nil
  106. full_message = build_message(message, "<?> exception expected but none was thrown.", expected)
  107. assert_block(full_message) do
  108. begin
  109. yield
  110. rescue Exception => actual_exception
  111. break
  112. end
  113. false
  114. end
  115. full_message = build_message(message, "<?> exception expected but was\n?", expected, actual_exception)
  116. assert_block(full_message) {_expected_exception?(actual_exception, exceptions, modules)}
  117. actual_exception
  118. end
  119. end
  120. ##
  121. # Alias of assert_raise.
  122. #
  123. # Will be deprecated in 1.9, and removed in 2.0.
  124. public
  125. def assert_raises(*args, &block)
  126. assert_raise(*args, &block)
  127. end
  128. ##
  129. # Passes if +object+ .instance_of? +klass+
  130. #
  131. # Example:
  132. # assert_instance_of String, 'foo'
  133. public
  134. def assert_instance_of(klass, object, message="")
  135. _wrap_assertion do
  136. assert_equal(Class, klass.class, "assert_instance_of takes a Class as its first argument")
  137. full_message = build_message(message, <<EOT, object, klass, object.class)
  138. <?> expected to be an instance of
  139. <?> but was
  140. <?>.
  141. EOT
  142. assert_block(full_message){object.instance_of?(klass)}
  143. end
  144. end
  145. ##
  146. # Passes if +object+ is nil.
  147. #
  148. # Example:
  149. # assert_nil [1, 2].uniq!
  150. public
  151. def assert_nil(object, message="")
  152. assert_equal(nil, object, message)
  153. end
  154. ##
  155. # Passes if +object+ .kind_of? +klass+
  156. #
  157. # Example:
  158. # assert_kind_of Object, 'foo'
  159. public
  160. def assert_kind_of(klass, object, message="")
  161. _wrap_assertion do
  162. assert(klass.kind_of?(Module), "The first parameter to assert_kind_of should be a kind_of Module.")
  163. full_message = build_message(message, "<?>\nexpected to be kind_of\\?\n<?> but was\n<?>.", object, klass, object.class)
  164. assert_block(full_message){object.kind_of?(klass)}
  165. end
  166. end
  167. ##
  168. # Passes if +object+ .respond_to? +method+
  169. #
  170. # Example:
  171. # assert_respond_to 'bugbear', :slice
  172. public
  173. def assert_respond_to(object, method, message="")
  174. _wrap_assertion do
  175. full_message = build_message(nil, "<?>\ngiven as the method name argument to #assert_respond_to must be a Symbol or #respond_to\\?(:to_str).", method)
  176. assert_block(full_message) do
  177. method.kind_of?(Symbol) || method.respond_to?(:to_str)
  178. end
  179. full_message = build_message(message, <<EOT, object, object.class, method)
  180. <?>
  181. of type <?>
  182. expected to respond_to\\?<?>.
  183. EOT
  184. assert_block(full_message) { object.respond_to?(method) }
  185. end
  186. end
  187. ##
  188. # Passes if +string+ =~ +pattern+.
  189. #
  190. # Example:
  191. # assert_match(/\d+/, 'five, 6, seven')
  192. public
  193. def assert_match(pattern, string, message="")
  194. _wrap_assertion do
  195. pattern = case(pattern)
  196. when String
  197. Regexp.new(Regexp.escape(pattern))
  198. else
  199. pattern
  200. end
  201. full_message = build_message(message, "<?> expected to be =~\n<?>.", string, pattern)
  202. assert_block(full_message) { string =~ pattern }
  203. end
  204. end
  205. ##
  206. # Passes if +actual+ .equal? +expected+ (i.e. they are the same
  207. # instance).
  208. #
  209. # Example:
  210. # o = Object.new
  211. # assert_same o, o
  212. public
  213. def assert_same(expected, actual, message="")
  214. full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
  215. <?>
  216. with id <?> expected to be equal\\? to
  217. <?>
  218. with id <?>.
  219. EOT
  220. assert_block(full_message) { actual.equal?(expected) }
  221. end
  222. ##
  223. # Compares the +object1+ with +object2+ using +operator+.
  224. #
  225. # Passes if object1.__send__(operator, object2) is true.
  226. #
  227. # Example:
  228. # assert_operator 5, :>=, 4
  229. public
  230. def assert_operator(object1, operator, object2, message="")
  231. _wrap_assertion do
  232. full_message = build_message(nil, "<?>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
  233. assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
  234. full_message = build_message(message, <<EOT, object1, AssertionMessage.literal(operator), object2)
  235. <?> expected to be
  236. ?
  237. <?>.
  238. EOT
  239. assert_block(full_message) { object1.__send__(operator, object2) }
  240. end
  241. end
  242. ##
  243. # Passes if block does not raise an exception.
  244. #
  245. # Example:
  246. # assert_nothing_raised do
  247. # [1, 2].uniq
  248. # end
  249. public
  250. def assert_nothing_raised(*args)
  251. _wrap_assertion do
  252. if Module === args.last
  253. message = ""
  254. else
  255. message = args.pop
  256. end
  257. exceptions, modules = _check_exception_class(args)
  258. begin
  259. yield
  260. rescue Exception => e
  261. if ((args.empty? && !e.instance_of?(AssertionFailedError)) ||
  262. _expected_exception?(e, exceptions, modules))
  263. assert_block(build_message(message, "Exception raised:\n?", e)){false}
  264. else
  265. raise
  266. end
  267. end
  268. nil
  269. end
  270. end
  271. ##
  272. # Flunk always fails.
  273. #
  274. # Example:
  275. # flunk 'Not done testing yet.'
  276. public
  277. def flunk(message="Flunked")
  278. assert_block(build_message(message)){false}
  279. end
  280. ##
  281. # Passes if ! +actual+ .equal? +expected+
  282. #
  283. # Example:
  284. # assert_not_same Object.new, Object.new
  285. public
  286. def assert_not_same(expected, actual, message="")
  287. full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
  288. <?>
  289. with id <?> expected to not be equal\\? to
  290. <?>
  291. with id <?>.
  292. EOT
  293. assert_block(full_message) { !actual.equal?(expected) }
  294. end
  295. ##
  296. # Passes if +expected+ != +actual+
  297. #
  298. # Example:
  299. # assert_not_equal 'some string', 5
  300. public
  301. def assert_not_equal(expected, actual, message="")
  302. full_message = build_message(message, "<?> expected to be != to\n<?>.", expected, actual)
  303. assert_block(full_message) { expected != actual }
  304. end
  305. ##
  306. # Passes if ! +object+ .nil?
  307. #
  308. # Example:
  309. # assert_not_nil '1 two 3'.sub!(/two/, '2')
  310. public
  311. def assert_not_nil(object, message="")
  312. full_message = build_message(message, "<?> expected to not be nil.", object)
  313. assert_block(full_message){!object.nil?}
  314. end
  315. ##
  316. # Passes if +regexp+ !~ +string+
  317. #
  318. # Example:
  319. # assert_no_match(/two/, 'one 2 three')
  320. public
  321. def assert_no_match(regexp, string, message="")
  322. _wrap_assertion do
  323. assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.")
  324. full_message = build_message(message, "<?> expected to not match\n<?>.", regexp, string)
  325. assert_block(full_message) { regexp !~ string }
  326. end
  327. end
  328. UncaughtThrow = {NameError => /^uncaught throw \`(.+)\'$/,
  329. ThreadError => /^uncaught throw \`(.+)\' in thread /} #`
  330. ##
  331. # Passes if the block throws +expected_symbol+
  332. #
  333. # Example:
  334. # assert_throws :done do
  335. # throw :done
  336. # end
  337. public
  338. def assert_throws(expected_symbol, message="", &proc)
  339. _wrap_assertion do
  340. assert_instance_of(Symbol, expected_symbol, "assert_throws expects the symbol that should be thrown for its first argument")
  341. assert_block("Should have passed a block to assert_throws."){block_given?}
  342. caught = true
  343. begin
  344. catch(expected_symbol) do
  345. proc.call
  346. caught = false
  347. end
  348. full_message = build_message(message, "<?> should have been thrown.", expected_symbol)
  349. assert_block(full_message){caught}
  350. rescue NameError, ThreadError => error
  351. if UncaughtThrow[error.class] !~ error.message
  352. raise error
  353. end
  354. full_message = build_message(message, "<?> expected to be thrown but\n<?> was thrown.", expected_symbol, $1.intern)
  355. flunk(full_message)
  356. end
  357. end
  358. end
  359. ##
  360. # Passes if block does not throw anything.
  361. #
  362. # Example:
  363. # assert_nothing_thrown do
  364. # [1, 2].uniq
  365. # end
  366. public
  367. def assert_nothing_thrown(message="", &proc)
  368. _wrap_assertion do
  369. assert(block_given?, "Should have passed a block to assert_nothing_thrown")
  370. begin
  371. proc.call
  372. rescue NameError, ThreadError => error
  373. if UncaughtThrow[error.class] !~ error.message
  374. raise error
  375. end
  376. full_message = build_message(message, "<?> was thrown when nothing was expected", $1.intern)
  377. flunk(full_message)
  378. end
  379. assert(true, "Expected nothing to be thrown")
  380. end
  381. end
  382. ##
  383. # Passes if +expected_float+ and +actual_float+ are equal
  384. # within +delta+ tolerance.
  385. #
  386. # Example:
  387. # assert_in_delta 0.05, (50000.0 / 10**6), 0.00001
  388. public
  389. def assert_in_delta(expected_float, actual_float, delta, message="")
  390. _wrap_assertion do
  391. {expected_float => "first float", actual_float => "second float", delta => "delta"}.each do |float, name|
  392. assert_respond_to(float, :to_f, "The arguments must respond to to_f; the #{name} did not")
  393. end
  394. assert_operator(delta, :>=, 0.0, "The delta should not be negative")
  395. full_message = build_message(message, <<EOT, expected_float, actual_float, delta)
  396. <?> and
  397. <?> expected to be within
  398. <?> of each other.
  399. EOT
  400. assert_block(full_message) { (expected_float.to_f - actual_float.to_f).abs <= delta.to_f }
  401. end
  402. end
  403. ##
  404. # Passes if the method send returns a true value.
  405. #
  406. # +send_array+ is composed of:
  407. # * A receiver
  408. # * A method
  409. # * Arguments to the method
  410. #
  411. # Example:
  412. # assert_send [[1, 2], :include?, 4]
  413. public
  414. def assert_send(send_array, message="")
  415. _wrap_assertion do
  416. assert_instance_of(Array, send_array, "assert_send requires an array of send information")
  417. assert(send_array.size >= 2, "assert_send requires at least a receiver and a message name")
  418. full_message = build_message(message, <<EOT, send_array[0], AssertionMessage.literal(send_array[1].to_s), send_array[2..-1])
  419. <?> expected to respond to
  420. <?(?)> with a true value.
  421. EOT
  422. assert_block(full_message) { send_array[0].__send__(send_array[1], *send_array[2..-1]) }
  423. end
  424. end
  425. ##
  426. # Builds a failure message. +head+ is added before the +template+ and
  427. # +arguments+ replaces the '?'s positionally in the template.
  428. public
  429. def build_message(head, template=nil, *arguments)
  430. template &&= template.chomp
  431. return AssertionMessage.new(head, template, arguments)
  432. end
  433. private
  434. def _wrap_assertion
  435. @_assertion_wrapped ||= false
  436. unless (@_assertion_wrapped)
  437. @_assertion_wrapped = true
  438. begin
  439. add_assertion
  440. return yield
  441. ensure
  442. @_assertion_wrapped = false
  443. end
  444. else
  445. return yield
  446. end
  447. end
  448. ##
  449. # Called whenever an assertion is made. Define this in classes that
  450. # include Test::Unit::Assertions to record assertion counts.
  451. private
  452. def add_assertion
  453. end
  454. ##
  455. # Select whether or not to use the pretty-printer. If this option is set
  456. # to false before any assertions are made, pp.rb will not be required.
  457. public
  458. def self.use_pp=(value)
  459. AssertionMessage.use_pp = value
  460. end
  461. # :stopdoc:
  462. class AssertionMessage
  463. @use_pp = true
  464. class << self
  465. attr_accessor :use_pp
  466. end
  467. class Literal
  468. def initialize(value)
  469. @value = value
  470. end
  471. def inspect
  472. @value.to_s
  473. end
  474. end
  475. class Template
  476. def self.create(string)
  477. parts = (string ? string.scan(/(?=[^\\])\?|(?:\\\?|[^\?])+/m) : [])
  478. self.new(parts)
  479. end
  480. attr_reader :count
  481. def initialize(parts)
  482. @parts = parts
  483. @count = parts.find_all{|e| e == '?'}.size
  484. end
  485. def result(parameters)
  486. raise "The number of parameters does not match the number of substitutions." if(parameters.size != count)
  487. params = parameters.dup
  488. @parts.collect{|e| e == '?' ? params.shift : e.gsub(/\\\?/m, '?')}.join('')
  489. end
  490. end
  491. def self.literal(value)
  492. Literal.new(value)
  493. end
  494. include Util::BacktraceFilter
  495. def initialize(head, template_string, parameters)
  496. @head = head
  497. @template_string = template_string
  498. @parameters = parameters
  499. end
  500. def convert(object)
  501. case object
  502. when Exception
  503. <<EOM.chop
  504. Class: <#{convert(object.class)}>
  505. Message: <#{convert(object.message)}>
  506. ---Backtrace---
  507. #{filter_backtrace(object.backtrace).join("\n")}
  508. ---------------
  509. EOM
  510. else
  511. if(self.class.use_pp)
  512. begin
  513. require 'pp'
  514. rescue LoadError
  515. self.class.use_pp = false
  516. return object.inspect
  517. end unless(defined?(PP))
  518. PP.pp(object, '').chomp
  519. else
  520. object.inspect
  521. end
  522. end
  523. end
  524. def template
  525. @template ||= Template.create(@template_string)
  526. end
  527. def add_period(string)
  528. (string =~ /\.\Z/ ? string : string + '.')
  529. end
  530. def to_s
  531. message_parts = []
  532. if (@head)
  533. head = @head.to_s
  534. unless(head.empty?)
  535. message_parts << add_period(head)
  536. end
  537. end
  538. tail = template.result(@parameters.collect{|e| convert(e)})
  539. message_parts << tail unless(tail.empty?)
  540. message_parts.join("\n")
  541. end
  542. end
  543. # :startdoc:
  544. end
  545. end
  546. end