PageRenderTime 28ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/Ruby/ruby19/lib/ruby/gems/1.9.1/gems/test-unit-2.1.1/lib/test/unit/assertions.rb

http://github.com/IronLanguages/main
Ruby | 1334 lines | 933 code | 120 blank | 281 comment | 59 complexity | ed0c2a0550c286fc0c69361ac058c72e MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. # Author:: Nathaniel Talbott.
  2. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
  3. # Copyright (c) 2009-2010 Kouhei Sutou. All rights reserved.
  4. # License:: Ruby license.
  5. require 'test/unit/assertionfailederror'
  6. require 'test/unit/util/backtracefilter'
  7. require 'test/unit/util/method-owner-finder'
  8. require 'test/unit/diff'
  9. module Test
  10. module Unit
  11. ##
  12. # Test::Unit::Assertions contains the standard Test::Unit assertions.
  13. # Assertions is included in Test::Unit::TestCase.
  14. #
  15. # To include it in your own code and use its functionality, you simply
  16. # need to rescue Test::Unit::AssertionFailedError. Additionally you may
  17. # override add_assertion to get notified whenever an assertion is made.
  18. #
  19. # Notes:
  20. # * The message to each assertion, if given, will be propagated with the
  21. # failure.
  22. # * It is easy to add your own assertions based on assert_block().
  23. #
  24. # = Example Custom Assertion
  25. #
  26. # def deny(boolean, message = nil)
  27. # message = build_message message, '<?> is not false or nil.', boolean
  28. # assert_block message do
  29. # not boolean
  30. # end
  31. # end
  32. module Assertions
  33. ##
  34. # The assertion upon which all other assertions are based. Passes if the
  35. # block yields true.
  36. #
  37. # Example:
  38. # assert_block "Couldn't do the thing" do
  39. # do_the_thing
  40. # end
  41. public
  42. def assert_block(message="assert_block failed.") # :yields:
  43. _wrap_assertion do
  44. if (! yield)
  45. raise AssertionFailedError.new(message.to_s)
  46. end
  47. end
  48. end
  49. ##
  50. # Asserts that +boolean+ is not false or nil.
  51. #
  52. # Example:
  53. # assert [1, 2].include?(5)
  54. public
  55. def assert(boolean, message=nil)
  56. _wrap_assertion do
  57. assert_block("assert should not be called with a block.") { !block_given? }
  58. assert_block(build_message(message, "<?> is not true.", boolean)) { boolean }
  59. end
  60. end
  61. ##
  62. # Passes if +expected+ == +actual.
  63. #
  64. # Note that the ordering of arguments is important, since a helpful
  65. # error message is generated when this one fails that tells you the
  66. # values of expected and actual.
  67. #
  68. # Example:
  69. # assert_equal 'MY STRING', 'my string'.upcase
  70. public
  71. def assert_equal(expected, actual, message=nil)
  72. diff = AssertionMessage.delayed_diff(expected, actual)
  73. if expected.respond_to?(:encoding) and
  74. actual.respond_to?(:encoding) and
  75. expected.encoding != actual.encoding
  76. format = <<EOT
  77. <?>(?) expected but was
  78. <?>(?).?
  79. EOT
  80. full_message = build_message(message, format,
  81. expected, expected.encoding.name,
  82. actual, actual.encoding.name,
  83. diff)
  84. else
  85. full_message = build_message(message, <<EOT, expected, actual, diff)
  86. <?> expected but was
  87. <?>.?
  88. EOT
  89. end
  90. begin
  91. assert_block(full_message) { expected == actual }
  92. rescue AssertionFailedError => failure
  93. failure.expected = expected
  94. failure.actual = actual
  95. failure.inspected_expected = AssertionMessage.convert(expected)
  96. failure.inspected_actual = AssertionMessage.convert(actual)
  97. failure.user_message = message
  98. raise
  99. end
  100. end
  101. ##
  102. # Passes if the block raises one of the expected
  103. # exceptions. When an expected exception is an Exception
  104. # object, passes if expected_exception == actual_exception.
  105. #
  106. # Example:
  107. # assert_raise(RuntimeError, LoadError) do
  108. # raise 'Boom!!!'
  109. # end # -> pass
  110. #
  111. # assert_raise do
  112. # raise Exception, 'Any exception should be raised!!!'
  113. # end # -> pass
  114. #
  115. # assert_raise(RuntimeError.new("XXX")) {raise "XXX"} # -> pass
  116. # assert_raise(MyError.new("XXX")) {raise "XXX"} # -> fail
  117. # assert_raise(RuntimeError.new("ZZZ")) {raise "XXX"} # -> fail
  118. public
  119. def assert_raise(*args, &block)
  120. assert_expected_exception = Proc.new do |*_args|
  121. message, assert_exception_helper, actual_exception = _args
  122. expected = assert_exception_helper.expected_exceptions
  123. full_message = build_message(message,
  124. "<?> exception expected but was\n?",
  125. expected, actual_exception)
  126. assert_block(full_message) do
  127. expected == [] or assert_exception_helper.expected?(actual_exception)
  128. end
  129. end
  130. _assert_raise(assert_expected_exception, *args, &block)
  131. end
  132. ##
  133. # Alias of assert_raise.
  134. #
  135. # Will be deprecated in 1.9, and removed in 2.0.
  136. public
  137. def assert_raises(*args, &block)
  138. assert_raise(*args, &block)
  139. end
  140. ##
  141. # Passes if the block raises one of the given
  142. # exceptions or sub exceptions of the given exceptions.
  143. #
  144. # Example:
  145. # assert_raise_kind_of(SystemCallError) do
  146. # raise Errno::EACCES
  147. # end
  148. def assert_raise_kind_of(*args, &block)
  149. assert_expected_exception = Proc.new do |*_args|
  150. message, assert_exception_helper, actual_exception = _args
  151. expected = assert_exception_helper.expected_exceptions
  152. full_message = build_message(message,
  153. "<?> family exception expected " +
  154. "but was\n?",
  155. expected, actual_exception)
  156. assert_block(full_message) do
  157. assert_exception_helper.expected?(actual_exception, :kind_of?)
  158. end
  159. end
  160. _assert_raise(assert_expected_exception, *args, &block)
  161. end
  162. ##
  163. # Passes if +object+.instance_of?(+klass+). When +klass+ is
  164. # an array of classes, it passes if any class
  165. # satisfies +object.instance_of?(class).
  166. #
  167. # Example:
  168. # assert_instance_of(String, 'foo') # -> pass
  169. # assert_instance_of([Fixnum, NilClass], 100) # -> pass
  170. # assert_instance_of([Numeric, NilClass], 100) # -> fail
  171. public
  172. def assert_instance_of(klass, object, message="")
  173. _wrap_assertion do
  174. klasses = nil
  175. klasses = klass if klass.is_a?(Array)
  176. assert_block("The first parameter to assert_instance_of should be " +
  177. "a Class or an Array of Class.") do
  178. if klasses
  179. klasses.all? {|k| k.is_a?(Class)}
  180. else
  181. klass.is_a?(Class)
  182. end
  183. end
  184. klass_message = AssertionMessage.maybe_container(klass) do |value|
  185. "<#{value}>"
  186. end
  187. full_message = build_message(message, <<EOT, object, klass_message, object.class)
  188. <?> expected to be an instance of
  189. ? but was
  190. <?>.
  191. EOT
  192. assert_block(full_message) do
  193. if klasses
  194. klasses.any? {|k| object.instance_of?(k)}
  195. else
  196. object.instance_of?(klass)
  197. end
  198. end
  199. end
  200. end
  201. ##
  202. # Passes if +object+ is nil.
  203. #
  204. # Example:
  205. # assert_nil [1, 2].uniq!
  206. public
  207. def assert_nil(object, message="")
  208. full_message = build_message(message, <<EOT, object)
  209. <?> expected to be nil.
  210. EOT
  211. assert_block(full_message) { object.nil? }
  212. end
  213. ##
  214. # Passes if +object+.kind_of?(+klass+). When +klass+ is
  215. # an array of classes or modules, it passes if any
  216. # class or module satisfies +object.kind_of?(class_or_module).
  217. #
  218. # Example:
  219. # assert_kind_of(Object, 'foo') # -> pass
  220. # assert_kind_of([Fixnum, NilClass], 100) # -> pass
  221. # assert_kind_of([Fixnum, NilClass], "string") # -> fail
  222. public
  223. def assert_kind_of(klass, object, message="")
  224. _wrap_assertion do
  225. klasses = nil
  226. klasses = klass if klass.is_a?(Array)
  227. assert_block("The first parameter to assert_kind_of should be " +
  228. "a kind_of Module or an Array of a kind_of Module.") do
  229. if klasses
  230. klasses.all? {|k| k.kind_of?(Module)}
  231. else
  232. klass.kind_of?(Module)
  233. end
  234. end
  235. klass_message = AssertionMessage.maybe_container(klass) do |value|
  236. "<#{value}>"
  237. end
  238. full_message = build_message(message,
  239. "<?> expected to be kind_of\\?\n" +
  240. "? but was\n" +
  241. "<?>.",
  242. object,
  243. klass_message,
  244. object.class)
  245. assert_block(full_message) do
  246. if klasses
  247. klasses.any? {|k| object.kind_of?(k)}
  248. else
  249. object.kind_of?(klass)
  250. end
  251. end
  252. end
  253. end
  254. ##
  255. # Passes if +object+ .respond_to? +method+
  256. #
  257. # Example:
  258. # assert_respond_to 'bugbear', :slice
  259. public
  260. def assert_respond_to(object, method, message="")
  261. _wrap_assertion do
  262. full_message = build_message(message,
  263. "<?>.kind_of\\?(Symbol) or\n" +
  264. "<?>.respond_to\\?(:to_str) expected",
  265. method, method)
  266. assert_block(full_message) do
  267. method.kind_of?(Symbol) or method.respond_to?(:to_str)
  268. end
  269. full_message = build_message(message,
  270. "<?>.respond_to\\?(?) expected\n" +
  271. "(Class: <?>)",
  272. object, method, object.class)
  273. assert_block(full_message) {object.respond_to?(method)}
  274. end
  275. end
  276. ##
  277. # Passes if +string+ =~ +pattern+.
  278. #
  279. # Example:
  280. # assert_match(/\d+/, 'five, 6, seven')
  281. public
  282. def assert_match(pattern, string, message="")
  283. _wrap_assertion do
  284. pattern = case(pattern)
  285. when String
  286. Regexp.new(Regexp.escape(pattern))
  287. else
  288. pattern
  289. end
  290. full_message = build_message(message, "<?> expected to be =~\n<?>.", string, pattern)
  291. assert_block(full_message) { string =~ pattern }
  292. end
  293. end
  294. ##
  295. # Passes if +actual+ .equal? +expected+ (i.e. they are the same
  296. # instance).
  297. #
  298. # Example:
  299. # o = Object.new
  300. # assert_same o, o
  301. public
  302. def assert_same(expected, actual, message="")
  303. full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
  304. <?>
  305. with id <?> expected to be equal\\? to
  306. <?>
  307. with id <?>.
  308. EOT
  309. assert_block(full_message) { actual.equal?(expected) }
  310. end
  311. ##
  312. # Compares the +object1+ with +object2+ using +operator+.
  313. #
  314. # Passes if object1.__send__(operator, object2) is true.
  315. #
  316. # Example:
  317. # assert_operator 5, :>=, 4
  318. public
  319. def assert_operator(object1, operator, object2, message="")
  320. _wrap_assertion do
  321. full_message = build_message(nil, "<?>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
  322. assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
  323. full_message = build_message(message, <<EOT, object1, AssertionMessage.literal(operator), object2)
  324. <?> expected to be
  325. ?
  326. <?>.
  327. EOT
  328. assert_block(full_message) { object1.__send__(operator, object2) }
  329. end
  330. end
  331. ##
  332. # Passes if block does not raise an exception.
  333. #
  334. # Example:
  335. # assert_nothing_raised do
  336. # [1, 2].uniq
  337. # end
  338. public
  339. def assert_nothing_raised(*args)
  340. _wrap_assertion do
  341. if args.last.is_a?(String)
  342. message = args.pop
  343. else
  344. message = ""
  345. end
  346. assert_exception_helper = AssertExceptionHelper.new(self, args)
  347. begin
  348. yield
  349. rescue Exception => e
  350. if ((args.empty? && !e.instance_of?(AssertionFailedError)) ||
  351. assert_exception_helper.expected?(e))
  352. failure_message = build_message(message, "Exception raised:\n?", e)
  353. assert_block(failure_message) {false}
  354. else
  355. raise
  356. end
  357. end
  358. nil
  359. end
  360. end
  361. ##
  362. # Flunk always fails.
  363. #
  364. # Example:
  365. # flunk 'Not done testing yet.'
  366. public
  367. def flunk(message="Flunked")
  368. assert_block(build_message(message)){false}
  369. end
  370. ##
  371. # Passes if ! +actual+ .equal? +expected+
  372. #
  373. # Example:
  374. # assert_not_same Object.new, Object.new
  375. public
  376. def assert_not_same(expected, actual, message="")
  377. full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
  378. <?>
  379. with id <?> expected to not be equal\\? to
  380. <?>
  381. with id <?>.
  382. EOT
  383. assert_block(full_message) { !actual.equal?(expected) }
  384. end
  385. ##
  386. # Passes if +expected+ != +actual+
  387. #
  388. # Example:
  389. # assert_not_equal 'some string', 5
  390. public
  391. def assert_not_equal(expected, actual, message="")
  392. full_message = build_message(message, "<?> expected to be != to\n<?>.", expected, actual)
  393. assert_block(full_message) { expected != actual }
  394. end
  395. ##
  396. # Passes if ! +object+ .nil?
  397. #
  398. # Example:
  399. # assert_not_nil '1 two 3'.sub!(/two/, '2')
  400. public
  401. def assert_not_nil(object, message="")
  402. full_message = build_message(message, "<?> expected to not be nil.", object)
  403. assert_block(full_message){!object.nil?}
  404. end
  405. ##
  406. # Passes if +regexp+ !~ +string+
  407. #
  408. # Example:
  409. # assert_no_match(/two/, 'one 2 three')
  410. public
  411. def assert_no_match(regexp, string, message="")
  412. _wrap_assertion do
  413. assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.")
  414. full_message = build_message(message, "<?> expected to not match\n<?>.", regexp, string)
  415. assert_block(full_message) { regexp !~ string }
  416. end
  417. end
  418. UncaughtThrow = {
  419. NameError => /^uncaught throw \`(.+)\'$/,
  420. ArgumentError => /^uncaught throw (.+)$/,
  421. ThreadError => /^uncaught throw \`(.+)\' in thread /
  422. } #`
  423. ##
  424. # Passes if the block throws +expected_object+
  425. #
  426. # Example:
  427. # assert_throw(:done) do
  428. # throw(:done)
  429. # end
  430. public
  431. def assert_throw(expected_object, message="", &proc)
  432. _wrap_assertion do
  433. begin
  434. catch([]) {}
  435. rescue TypeError
  436. assert_instance_of(Symbol, expected_object,
  437. "assert_throws expects the symbol that should be thrown for its first argument")
  438. end
  439. assert_block("Should have passed a block to assert_throw.") do
  440. block_given?
  441. end
  442. caught = true
  443. begin
  444. catch(expected_object) do
  445. proc.call
  446. caught = false
  447. end
  448. full_message = build_message(message,
  449. "<?> should have been thrown.",
  450. expected_object)
  451. assert_block(full_message) {caught}
  452. rescue NameError, ArgumentError, ThreadError => error
  453. raise unless UncaughtThrow[error.class] =~ error.message
  454. tag = $1
  455. tag = tag[1..-1].intern if tag[0, 1] == ":"
  456. full_message = build_message(message,
  457. "<?> expected to be thrown but\n" +
  458. "<?> was thrown.",
  459. expected_object, tag)
  460. flunk(full_message)
  461. end
  462. end
  463. end
  464. ##
  465. # Alias of assert_throw.
  466. #
  467. # Will be deprecated in 1.9, and removed in 2.0.
  468. def assert_throws(*args, &block)
  469. assert_throw(*args, &block)
  470. end
  471. ##
  472. # Passes if block does not throw anything.
  473. #
  474. # Example:
  475. # assert_nothing_thrown do
  476. # [1, 2].uniq
  477. # end
  478. public
  479. def assert_nothing_thrown(message="", &proc)
  480. _wrap_assertion do
  481. assert(block_given?, "Should have passed a block to assert_nothing_thrown")
  482. begin
  483. proc.call
  484. rescue NameError, ArgumentError, ThreadError => error
  485. raise unless UncaughtThrow[error.class] =~ error.message
  486. tag = $1
  487. tag = tag[1..-1].intern if tag[0, 1] == ":"
  488. full_message = build_message(message,
  489. "<?> was thrown when nothing was expected",
  490. tag)
  491. flunk(full_message)
  492. end
  493. assert(true, "Expected nothing to be thrown")
  494. end
  495. end
  496. ##
  497. # Passes if +expected_float+ and +actual_float+ are equal
  498. # within +delta+ tolerance.
  499. #
  500. # Example:
  501. # assert_in_delta 0.05, (50000.0 / 10**6), 0.00001
  502. public
  503. def assert_in_delta(expected_float, actual_float, delta, message="")
  504. _wrap_assertion do
  505. _assert_in_delta_validate_arguments(expected_float,
  506. actual_float,
  507. delta)
  508. full_message = _assert_in_delta_message(expected_float,
  509. actual_float,
  510. delta,
  511. message)
  512. assert_block(full_message) do
  513. (expected_float.to_f - actual_float.to_f).abs <= delta.to_f
  514. end
  515. end
  516. end
  517. # :stopdoc:
  518. private
  519. def _assert_in_delta_validate_arguments(expected_float,
  520. actual_float,
  521. delta)
  522. {
  523. expected_float => "first float",
  524. actual_float => "second float",
  525. delta => "delta"
  526. }.each do |float, name|
  527. assert_respond_to(float, :to_f,
  528. "The arguments must respond to to_f; " +
  529. "the #{name} did not")
  530. end
  531. assert_operator(delta, :>=, 0.0, "The delta should not be negative")
  532. end
  533. def _assert_in_delta_message(expected_float, actual_float, delta,
  534. message)
  535. format = <<-EOT
  536. <?> expected but was
  537. <?> (tolerance <?>).
  538. EOT
  539. arguments = [expected_float, actual_float, delta]
  540. normalized_expected = expected_float.to_f
  541. normalized_actual = actual_float.to_f
  542. normalized_delta = delta.to_f
  543. relation_format = nil
  544. relation_arguments = nil
  545. if normalized_actual < normalized_expected - normalized_delta
  546. relation_format = "<<?> < <?>-<?>(?) <= <?>+<?>(?)>"
  547. relation_arguments = [actual_float,
  548. expected_float, delta, expected_float - delta,
  549. expected_float, delta, expected_float + delta]
  550. elsif normalized_expected - normalized_delta < normalized_actual
  551. relation_format = "<<?>-<?>(?) <= <?>+<?>(?) < <?>>"
  552. relation_arguments = [expected_float, delta, expected_float - delta,
  553. expected_float, delta, expected_float + delta,
  554. actual_float]
  555. end
  556. if relation_format
  557. format << <<-EOT
  558. Relation:
  559. #{relation_format}
  560. EOT
  561. arguments.concat(relation_arguments)
  562. end
  563. build_message(message, format, *arguments)
  564. end
  565. public
  566. # :startdoc:
  567. ##
  568. # Passes if the method send returns a true value.
  569. #
  570. # +send_array+ is composed of:
  571. # * A receiver
  572. # * A method
  573. # * Arguments to the method
  574. #
  575. # Example:
  576. # assert_send [[1, 2], :include?, 4]
  577. public
  578. def assert_send(send_array, message="")
  579. _wrap_assertion do
  580. assert_instance_of(Array, send_array, "assert_send requires an array of send information")
  581. assert(send_array.size >= 2, "assert_send requires at least a receiver and a message name")
  582. full_message = build_message(message, <<EOT, send_array[0], AssertionMessage.literal(send_array[1].to_s), send_array[2..-1])
  583. <?> expected to respond to
  584. <?(?)> with a true value.
  585. EOT
  586. assert_block(full_message) { send_array[0].__send__(send_array[1], *send_array[2..-1]) }
  587. end
  588. end
  589. ##
  590. # Passes if +actual+ is a boolean value.
  591. #
  592. # Example:
  593. # assert_boolean(true) # -> pass
  594. # assert_boolean(nil) # -> fail
  595. def assert_boolean(actual, message=nil)
  596. _wrap_assertion do
  597. assert_block(build_message(message,
  598. "<true> or <false> expected but was\n<?>",
  599. actual)) do
  600. [true, false].include?(actual)
  601. end
  602. end
  603. end
  604. ##
  605. # Passes if +actual+ is true.
  606. #
  607. # Example:
  608. # assert_true(true) # -> pass
  609. # assert_true(:true) # -> fail
  610. def assert_true(actual, message=nil)
  611. _wrap_assertion do
  612. assert_block(build_message(message,
  613. "<true> expected but was\n<?>",
  614. actual)) do
  615. actual == true
  616. end
  617. end
  618. end
  619. ##
  620. # Passes if +actual+ is false.
  621. #
  622. # Example:
  623. # assert_false(false) # -> pass
  624. # assert_false(nil) # -> fail
  625. def assert_false(actual, message=nil)
  626. _wrap_assertion do
  627. assert_block(build_message(message,
  628. "<false> expected but was\n<?>",
  629. actual)) do
  630. actual == false
  631. end
  632. end
  633. end
  634. ##
  635. # Passes if expression "+expected+ +operator+
  636. # +actual+" is true.
  637. #
  638. # Example:
  639. # assert_compare(1, "<", 10) # -> pass
  640. # assert_compare(1, ">=", 10) # -> fail
  641. def assert_compare(expected, operator, actual, message=nil)
  642. _wrap_assertion do
  643. assert_send([["<", "<=", ">", ">="], :include?, operator.to_s])
  644. case operator.to_s
  645. when "<"
  646. operator_description = "less than"
  647. when "<="
  648. operator_description = "less than or equal to"
  649. when ">"
  650. operator_description = "greater than"
  651. when ">="
  652. operator_description = "greater than or equal to"
  653. end
  654. template = <<-EOT
  655. <?> #{operator} <?> should be true
  656. <?> expected #{operator_description}
  657. <?>.
  658. EOT
  659. full_message = build_message(message, template,
  660. expected, actual,
  661. expected, actual)
  662. assert_block(full_message) do
  663. expected.send(operator, actual)
  664. end
  665. end
  666. end
  667. ##
  668. # Passes if assertion is failed in block.
  669. #
  670. # Example:
  671. # assert_fail_assertion {assert_equal("A", "B")} # -> pass
  672. # assert_fail_assertion {assert_equal("A", "A")} # -> fail
  673. def assert_fail_assertion(message=nil)
  674. _wrap_assertion do
  675. full_message = build_message(message,
  676. "Failed assertion was expected.")
  677. assert_block(full_message) do
  678. begin
  679. yield
  680. false
  681. rescue AssertionFailedError
  682. true
  683. end
  684. end
  685. end
  686. end
  687. ##
  688. # Passes if an exception is raised in block and its
  689. # message is +expected+.
  690. #
  691. # Example:
  692. # assert_raise_message("exception") {raise "exception"} # -> pass
  693. # assert_raise_message(/exc/i) {raise "exception"} # -> pass
  694. # assert_raise_message("exception") {raise "EXCEPTION"} # -> fail
  695. # assert_raise_message("exception") {} # -> fail
  696. def assert_raise_message(expected, message=nil)
  697. _wrap_assertion do
  698. full_message = build_message(message,
  699. "<?> exception message expected " +
  700. "but none was thrown.",
  701. expected)
  702. exception = nil
  703. assert_block(full_message) do
  704. begin
  705. yield
  706. false
  707. rescue Exception => exception
  708. true
  709. end
  710. end
  711. actual = exception.message
  712. diff = AssertionMessage.delayed_diff(expected, actual)
  713. full_message =
  714. build_message(message,
  715. "<?> exception message expected but was\n" +
  716. "<?>.?", expected, actual, diff)
  717. assert_block(full_message) do
  718. if expected.is_a?(Regexp)
  719. expected =~ actual
  720. else
  721. expected == actual
  722. end
  723. end
  724. end
  725. end
  726. ##
  727. # Passes if +object+.const_defined?(+constant_name+)
  728. #
  729. # Example:
  730. # assert_const_defined(Test, :Unit) # -> pass
  731. # assert_const_defined(Object, :Nonexistent) # -> fail
  732. def assert_const_defined(object, constant_name, message=nil)
  733. _wrap_assertion do
  734. full_message = build_message(message,
  735. "<?>.const_defined\\?(<?>) expected.",
  736. object, constant_name)
  737. assert_block(full_message) do
  738. object.const_defined?(constant_name)
  739. end
  740. end
  741. end
  742. ##
  743. # Passes if !+object+.const_defined?(+constant_name+)
  744. #
  745. # Example:
  746. # assert_not_const_defined(Object, :Nonexistent) # -> pass
  747. # assert_not_const_defined(Test, :Unit) # -> fail
  748. def assert_not_const_defined(object, constant_name, message=nil)
  749. _wrap_assertion do
  750. full_message = build_message(message,
  751. "!<?>.const_defined\\?(<?>) expected.",
  752. object, constant_name)
  753. assert_block(full_message) do
  754. !object.const_defined?(constant_name)
  755. end
  756. end
  757. end
  758. ##
  759. # Passes if +object+.+predicate+
  760. #
  761. # Example:
  762. # assert_predicate([], :empty?) # -> pass
  763. # assert_predicate([1], :empty?) # -> fail
  764. def assert_predicate(object, predicate, message=nil)
  765. _wrap_assertion do
  766. assert_respond_to(object, predicate, message)
  767. actual = object.send(predicate)
  768. full_message = build_message(message,
  769. "<?>.? is true value expected but was\n" +
  770. "<?>",
  771. object,
  772. AssertionMessage.literal(predicate),
  773. actual)
  774. assert_block(full_message) do
  775. actual
  776. end
  777. end
  778. end
  779. ##
  780. # Passes if +object+.+predicate+
  781. #
  782. # Example:
  783. # assert_not_predicate([1], :empty?) # -> pass
  784. # assert_not_predicate([], :empty?) # -> fail
  785. def assert_not_predicate(object, predicate, message=nil)
  786. _wrap_assertion do
  787. assert_respond_to(object, predicate, message)
  788. actual = object.send(predicate)
  789. full_message = build_message(message,
  790. "<?>.? is false value expected but was\n" +
  791. "<?>",
  792. object,
  793. AssertionMessage.literal(predicate),
  794. actual)
  795. assert_block(full_message) do
  796. not actual
  797. end
  798. end
  799. end
  800. ##
  801. # Passes if +object+#+alias_name+ is an alias method of
  802. # +object+#+original_name+.
  803. #
  804. # Example:
  805. # assert_alias_method([], :length, :size) # -> pass
  806. # assert_alias_method([], :size, :length) # -> pass
  807. # assert_alias_method([], :each, :size) # -> fail
  808. def assert_alias_method(object, alias_name, original_name, message=nil)
  809. _wrap_assertion do
  810. find_method_failure_message = Proc.new do |method_name|
  811. build_message(message,
  812. "<?>.? doesn't exist\n" +
  813. "(Class: <?>)",
  814. object,
  815. AssertionMessage.literal(method_name),
  816. object.class)
  817. end
  818. alias_method = original_method = nil
  819. assert_block(find_method_failure_message.call(alias_name)) do
  820. begin
  821. alias_method = object.method(alias_name)
  822. true
  823. rescue NameError
  824. false
  825. end
  826. end
  827. assert_block(find_method_failure_message.call(original_name)) do
  828. begin
  829. original_method = object.method(original_name)
  830. true
  831. rescue NameError
  832. false
  833. end
  834. end
  835. full_message = build_message(message,
  836. "<?> is alias of\n" +
  837. "<?> expected",
  838. alias_method,
  839. original_method)
  840. assert_block(full_message) do
  841. alias_method == original_method
  842. end
  843. end
  844. end
  845. ##
  846. # Passes if +path+ exists.
  847. #
  848. # Example:
  849. # assert_path_exist("/tmp") # -> pass
  850. # assert_path_exist("/bin/sh") # -> pass
  851. # assert_path_exist("/nonexistent") # -> fail
  852. def assert_path_exist(path, message=nil)
  853. _wrap_assertion do
  854. failure_message = build_message(message,
  855. "<?> expected to exist",
  856. path)
  857. assert_block(failure_message) do
  858. File.exist?(path)
  859. end
  860. end
  861. end
  862. ##
  863. # Passes if +path+ doesn't exist.
  864. #
  865. # Example:
  866. # assert_path_not_exist("/nonexistent") # -> pass
  867. # assert_path_not_exist("/tmp") # -> fail
  868. # assert_path_not_exist("/bin/sh") # -> fail
  869. def assert_path_not_exist(path, message=nil)
  870. _wrap_assertion do
  871. failure_message = build_message(message,
  872. "<?> expected to not exist",
  873. path)
  874. assert_block(failure_message) do
  875. not File.exist?(path)
  876. end
  877. end
  878. end
  879. ##
  880. # Builds a failure message. +head+ is added before the +template+ and
  881. # +arguments+ replaces the '?'s positionally in the template.
  882. public
  883. def build_message(head, template=nil, *arguments)
  884. template &&= template.chomp
  885. return AssertionMessage.new(head, template, arguments)
  886. end
  887. private
  888. def _wrap_assertion
  889. @_assertion_wrapped ||= false
  890. unless (@_assertion_wrapped)
  891. @_assertion_wrapped = true
  892. begin
  893. add_assertion
  894. return yield
  895. ensure
  896. @_assertion_wrapped = false
  897. end
  898. else
  899. return yield
  900. end
  901. end
  902. ##
  903. # Called whenever an assertion is made. Define this in classes that
  904. # include Test::Unit::Assertions to record assertion counts.
  905. private
  906. def add_assertion
  907. end
  908. ##
  909. # Select whether or not to use the pretty-printer. If this option is set
  910. # to false before any assertions are made, pp.rb will not be required.
  911. public
  912. def self.use_pp=(value)
  913. AssertionMessage.use_pp = value
  914. end
  915. # :stopdoc:
  916. private
  917. def _assert_raise(assert_expected_exception, *args, &block)
  918. _wrap_assertion do
  919. if args.last.is_a?(String)
  920. message = args.pop
  921. else
  922. message = ""
  923. end
  924. assert_exception_helper = AssertExceptionHelper.new(self, args)
  925. expected = assert_exception_helper.expected_exceptions
  926. actual_exception = nil
  927. full_message = build_message(message,
  928. "<?> exception expected " +
  929. "but none was thrown.",
  930. expected)
  931. assert_block(full_message) do
  932. begin
  933. yield
  934. false
  935. rescue Exception => actual_exception
  936. true
  937. end
  938. end
  939. assert_expected_exception.call(message, assert_exception_helper,
  940. actual_exception)
  941. actual_exception
  942. end
  943. end
  944. class AssertionMessage
  945. @use_pp = true
  946. class << self
  947. attr_accessor :use_pp
  948. def literal(value)
  949. Literal.new(value)
  950. end
  951. def delayed_literal(&block)
  952. DelayedLiteral.new(block)
  953. end
  954. def maybe_container(value, &formatter)
  955. MaybeContainer.new(value, &formatter)
  956. end
  957. MAX_DIFF_TARGET_STRING_SIZE = 1000
  958. def max_diff_target_string_size
  959. size = ENV["TEST_UNIT_MAX_DIFF_TARGET_STRING_SIZE"]
  960. if size
  961. begin
  962. size = Integer(size)
  963. rescue ArgumentError
  964. size = nil
  965. end
  966. end
  967. size || MAX_DIFF_TARGET_STRING_SIZE
  968. end
  969. def diff_target_string?(string)
  970. if string.respond_to?(:bytesize)
  971. string.bytesize < max_diff_target_string_size
  972. else
  973. string.size < max_diff_target_string_size
  974. end
  975. end
  976. def prepare_for_diff(from, to)
  977. if !from.is_a?(String) or !to.is_a?(String)
  978. from = convert(from)
  979. to = convert(to)
  980. end
  981. if diff_target_string?(from) and diff_target_string?(to)
  982. [from, to]
  983. else
  984. [nil, nil]
  985. end
  986. end
  987. def delayed_diff(from, to)
  988. delayed_literal do
  989. from, to = prepare_for_diff(from, to)
  990. diff = "" if from.nil? or to.nil?
  991. diff ||= Diff.readable(from, to)
  992. if /^[-+]/ !~ diff
  993. diff = ""
  994. elsif /^[ ?]/ =~ diff or /(?:.*\n){2,}/ =~ diff
  995. diff = "\n\ndiff:\n#{diff}"
  996. else
  997. diff = ""
  998. end
  999. if Diff.need_fold?(diff)
  1000. folded_diff = Diff.folded_readable(from, to)
  1001. diff << "\n\nfolded diff:\n#{folded_diff}"
  1002. end
  1003. diff
  1004. end
  1005. end
  1006. def convert(object)
  1007. case object
  1008. when Exception
  1009. <<EOM.chop
  1010. Class: <#{convert(object.class)}>
  1011. Message: <#{convert(object.message)}>
  1012. ---Backtrace---
  1013. #{Util::BacktraceFilter.filter_backtrace(object.backtrace).join("\n")}
  1014. ---------------
  1015. EOM
  1016. else
  1017. if use_pp
  1018. begin
  1019. require 'pp' unless defined?(PP)
  1020. begin
  1021. return PP.pp(object, '').chomp
  1022. rescue NameError
  1023. end
  1024. rescue LoadError
  1025. self.use_pp = false
  1026. end
  1027. end
  1028. object.inspect
  1029. end
  1030. end
  1031. end
  1032. class Literal
  1033. def initialize(value)
  1034. @value = value
  1035. end
  1036. def inspect
  1037. @value.to_s
  1038. end
  1039. end
  1040. class DelayedLiteral
  1041. def initialize(value)
  1042. @value = value
  1043. end
  1044. def inspect
  1045. @value.call.to_s
  1046. end
  1047. end
  1048. class MaybeContainer
  1049. def initialize(value, &formatter)
  1050. @value = value
  1051. @formatter = formatter
  1052. end
  1053. def inspect
  1054. if @value.is_a?(Array)
  1055. values = @value.collect do |value|
  1056. @formatter.call(AssertionMessage.convert(value))
  1057. end
  1058. "[#{values.join(', ')}]"
  1059. else
  1060. @formatter.call(AssertionMessage.convert(@value))
  1061. end
  1062. end
  1063. end
  1064. class Template
  1065. def self.create(string)
  1066. parts = (string ? string.scan(/(?=[^\\])\?|(?:\\\?|[^\?])+/m) : [])
  1067. self.new(parts)
  1068. end
  1069. attr_reader :count
  1070. def initialize(parts)
  1071. @parts = parts
  1072. @count = parts.find_all{|e| e == '?'}.size
  1073. end
  1074. def result(parameters)
  1075. raise "The number of parameters does not match the number of substitutions." if(parameters.size != count)
  1076. params = parameters.dup
  1077. @parts.collect{|e| e == '?' ? params.shift : e.gsub(/\\\?/m, '?')}.join('')
  1078. end
  1079. end
  1080. include Util::BacktraceFilter
  1081. def initialize(head, template_string, parameters)
  1082. @head = head
  1083. @template_string = template_string
  1084. @parameters = parameters
  1085. end
  1086. def convert(object)
  1087. self.class.convert(object)
  1088. end
  1089. def template
  1090. @template ||= Template.create(@template_string)
  1091. end
  1092. def add_period(string)
  1093. (string =~ /\.\Z/ ? string : string + '.')
  1094. end
  1095. def to_s
  1096. message_parts = []
  1097. if (@head)
  1098. head = @head.to_s
  1099. unless(head.empty?)
  1100. message_parts << add_period(head)
  1101. end
  1102. end
  1103. tail = template.result(@parameters.collect{|e| convert(e)})
  1104. message_parts << tail unless(tail.empty?)
  1105. message_parts.join("\n")
  1106. end
  1107. end
  1108. class AssertExceptionHelper
  1109. class WrappedException
  1110. def initialize(exception)
  1111. @exception = exception
  1112. end
  1113. def inspect
  1114. if default_inspect?
  1115. "#{@exception.class.inspect}(#{@exception.message.inspect})"
  1116. else
  1117. @exception.inspect
  1118. end
  1119. end
  1120. def method_missing(name, *args, &block)
  1121. @exception.send(name, *args, &block)
  1122. end
  1123. private
  1124. def default_inspect?
  1125. inspect_method = @exception.method(:inspect)
  1126. if inspect_method.respond_to?(:owner) and
  1127. inspect_method.owner == Exception
  1128. true
  1129. else
  1130. default_inspect_method = Exception.instance_method(:inspect)
  1131. default_inspect_method.bind(@exception).call == @exception.inspect
  1132. end
  1133. end
  1134. end
  1135. def initialize(test_case, expected_exceptions)
  1136. @test_case = test_case
  1137. @expected_exceptions = expected_exceptions
  1138. @expected_classes, @expected_modules, @expected_objects =
  1139. split_expected_exceptions(expected_exceptions)
  1140. end
  1141. def expected_exceptions
  1142. exceptions = @expected_exceptions.collect do |exception|
  1143. if exception.is_a?(Exception)
  1144. WrappedException.new(exception)
  1145. else
  1146. exception
  1147. end
  1148. end
  1149. if exceptions.size == 1
  1150. exceptions[0]
  1151. else
  1152. exceptions
  1153. end
  1154. end
  1155. def expected?(actual_exception, equality=nil)
  1156. equality ||= :instance_of?
  1157. expected_class?(actual_exception, equality) or
  1158. expected_module?(actual_exception) or
  1159. expected_object?(actual_exception)
  1160. end
  1161. private
  1162. def split_expected_exceptions(expected_exceptions)
  1163. exception_modules = []
  1164. exception_objects = []
  1165. exception_classes = []
  1166. expected_exceptions.each do |exception_type|
  1167. if exception_type.instance_of?(Module)
  1168. exception_modules << exception_type
  1169. elsif exception_type.is_a?(Exception)
  1170. exception_objects << exception_type
  1171. else
  1172. @test_case.send(:assert,
  1173. Exception >= exception_type,
  1174. "Should expect a class of exception, " +
  1175. "#{exception_type}")
  1176. exception_classes << exception_type
  1177. end
  1178. end
  1179. [exception_classes, exception_modules, exception_objects]
  1180. end
  1181. def expected_class?(actual_exception, equality)
  1182. @expected_classes.any? do |expected_class|
  1183. actual_exception.send(equality, expected_class)
  1184. end
  1185. end
  1186. def expected_module?(actual_exception)
  1187. @expected_modules.any? do |expected_module|
  1188. actual_exception.is_a?(expected_module)
  1189. end
  1190. end
  1191. def expected_object?(actual_exception)
  1192. @expected_objects.any? do |expected_object|
  1193. expected_object == actual_exception or
  1194. fallback_exception_object_equal(expected_object, actual_exception)
  1195. end
  1196. end
  1197. def fallback_exception_object_equal(expected_object, actual_exception)
  1198. owner = Util::MethodOwnerFinder.find(expected_object, :==)
  1199. if owner == Kernel or owner == Exception
  1200. expected_object.class == actual_exception.class and
  1201. expected_object.message == actual_exception.message
  1202. else
  1203. false
  1204. end
  1205. end
  1206. end
  1207. # :startdoc:
  1208. end
  1209. end
  1210. end