PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/watchdog/lib/watchdog/third-party/gems/gems/extensions-0.6.0/test/tc_binding.rb

https://bitbucket.org/redricko/pragprog-scripting
Ruby | 92 lines | 60 code | 10 blank | 22 comment | 0 complexity | 8704b84d977d9bf44b0973d607706c7e MD5 | raw file
  1. #---
  2. # Excerpted from "Everyday Scripting in Ruby"
  3. # We make no guarantees that this code is fit for any purpose.
  4. # Visit http://www.pragmaticprogrammer.com/titles/bmsft for more book information.
  5. #---
  6. require 'test/unit'
  7. require 'extensions/binding'
  8. #
  9. # Special test case for Binding#of_caller.
  10. #
  11. class TC_Binding_of_caller < Test::Unit::TestCase
  12. #
  13. # Tests Binding.of_caller
  14. #
  15. def test_of_caller
  16. x = 5
  17. _foo # This will increment x.
  18. assert_equal 6, x
  19. end
  20. #
  21. # Test the exception that should result if Binding.of_caller is used incorrectly.
  22. #
  23. def test_of_caller_exception
  24. x = 10
  25. assert_raises(Exception) do
  26. _bar
  27. puts x
  28. end
  29. end
  30. # Use Binding.of_caller correctly.
  31. def _foo
  32. Binding.of_caller do |b|
  33. eval "x += 1", b
  34. end
  35. end
  36. # Use Binding.of_caller incorrectly (dangling code).
  37. def _bar
  38. Binding.of_caller do |b|
  39. eval "x += 1", b
  40. end
  41. "foo".strip! # This code not allowed to be here.
  42. end
  43. end # class TC_Binding_of_caller
  44. #
  45. # Test case for the other Binding methods.
  46. #
  47. class TC_Binding < Test::Unit::TestCase
  48. # Test all the Binding methods except of_caller.
  49. def test_binding_methods
  50. x = y = 5
  51. b = binding
  52. assert_equal 5, b.eval('x')
  53. assert_equal ['b', 'x', 'y'], b.local_variables.sort
  54. assert_equal 5, b[:x]
  55. assert_equal 7, (b[:y] = 7)
  56. assert_equal 7, y
  57. assert_equal 'local-variable', b.defined?(:y)
  58. end
  59. # Test the Binding methods in the of_caller context.
  60. def test_binding_methods_with_of_caller
  61. x = "foo"
  62. y = 33
  63. _target
  64. assert_equal "FOO", x
  65. assert_equal -33, y
  66. end
  67. # Target method for #test_binding_methods_with_of_caller.
  68. def _target
  69. Binding.of_caller do |b|
  70. assert_equal "foo", b[:x]
  71. assert_equal 33, b[:y]
  72. assert_equal ['x', 'y'], b.local_variables.sort
  73. assert_equal "foo!", b.eval('x + y.chr')
  74. b[:x].upcase!
  75. b[:y] *= -1
  76. assert_equal "FOO", b[:x]
  77. assert_equal -33, b[:y]
  78. assert_equal 'local-variable', b.defined?(:y)
  79. assert_equal nil, b.defined?(:foobar)
  80. end
  81. end
  82. end # class TC_Binding