diff --git a/HISTORY.md b/HISTORY.md index 253a690..2f1afe3 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -4,7 +4,7 @@ Assay is one library again. The notations that were spun off as separate gems in 0.4 (Fluidity, RSpecial, Assay MiniTest and Assay TestUnit) are -back, each loaded on its own. Assay needs Ruby 2.7 or newer. +back, each loaded on its own, and Bang joins them. Assay needs Ruby 2.7 or newer. Changes: @@ -14,6 +14,12 @@ Changes: gem. Its module is `Assay::RSpec`. * Add `assay/minitest` and `assay/testunit`, the assertion methods of those frameworks, from the Assay MiniTest and Assay TestUnit gems. +* Add `assay/bang`, from the Bang gem, rebuilt on Assay's classes: + `x.equal!(y)` fails with an `EqualAssay`. A query method Assay has + no class for still works (`10.even!`) and fails with an `Assertion`. +* Fix a Hash under test being taken for options, which made comparing + two hashes raise ArgumentError in every notation. Only a trailing + Hash whose keys are all `:message` or `:backtrace` is options now. * Rewrite the Minitest and Test::Unit adapters for Minitest 5 and 6 and for test-unit 3. The old ones patched classes those frameworks no longer have. diff --git a/README.md b/README.md index c94ee99..96690e7 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ assertions, each loaded on its own: | `assay/testunit` | Test::Unit's `assert_equal` | | `assay/rspec` | RSpec's `should eq` and `expect(x).to eq` | | `assay/fluidity` | Assay's own: `x.should.equal y`, `x.assert == y` | +| `assay/bang` | Query methods as assertions: `x.equal!(y)`, `x.empty!` | Whichever you choose, a failure is an instance of the same assay class, and any test framework that follows the @@ -119,6 +120,28 @@ And to satisfy the technical aficionados there is `assert`. alone (`assay/fluidity/should`), and `is` and `will` are available the same way (`assay/fluidity/is`, `assay/fluidity/will`). +#### Bang + +Bang turns a query method into an assertion: call it with `!` in place +of `?`, and prefix `not_` to negate it. + + require 'assay/bang' + + 10.kind_of!(Integer) + 10.equal!(5 + 5) + 10.not_equal!(20) + +Where Assay has a class for the assertion, as it does for these, that +class is the failure raised. Any other query method an object has works +too, and fails with a plain `Assertion`. + + 10.even! + 10.between!(1, 20) + +For a procedure there are `raises!`, `rescues!` and `throws!`. + + lambda{ raise ArgumentError }.raises!(ArgumentError) + #### RSpec require 'assay/rspec' @@ -195,8 +218,12 @@ gems are retired: | gem `rspecial`, `require 'rspecial'` | `require 'assay/rspec'` | | gem `assay-minitest` | `require 'assay/minitest'` | | gem `assay-testunit` | `require 'assay/testunit'` | +| gem `bang`, `require 'bang'` | `require 'assay/bang'` | `Fluidity` is now `Assay::Fluidity`, and `RSpecial` is `Assay::RSpec`. +Bang's failures are now assay classes where there is one, not +`Bang::Assertion`, and the query methods it added to Object (such as +`equal_to?` and `raises?`) are gone. `Assay::Assertions`, `Assay::Matchers` and `Assay::Extensions` are as they were. diff --git a/Rakefile b/Rakefile index 53f1a21..a3d2bcd 100644 --- a/Rakefile +++ b/Rakefile @@ -9,7 +9,7 @@ end # Each notation extends Object in its own way, so each set of demos runs # in a process of its own. -DEMOS = %w[core minitest testunit rspec fluidity] +DEMOS = %w[core minitest testunit rspec fluidity bang] desc "Run the QED demos" task :demo do diff --git a/demo/bang/01_bang.md b/demo/bang/01_bang.md new file mode 100644 index 0000000..deff787 --- /dev/null +++ b/demo/bang/01_bang.md @@ -0,0 +1,220 @@ +# Bang + +Bang turns a query method into an assertion: call it with `!` in place +of `?`. Where Assay has a class for the assertion, that is the failure +raised. + + require 'assay/bang' + +## true! + + true.true! + + expect ::TrueAssay do + false.true! + end + + false.not_true! + +## false! + + false.false! + + expect ::FalseAssay do + true.false! + end + + true.not_false! + +## nil! + + nil.nil! + + expect ::NilAssay do + true.nil! + end + + true.not_nil! + +## equal! + + 1.equal!(1) + + expect ::EqualAssay do + 1.equal!(2) + end + + 1.not_equal!(2) + +## eql! + + 1.eql!(1) + + expect ::EqualityAssay do + 1.eql!(1.0) + end + + 1.not_eql!(1.0) + +## identical! + +Ruby's built-in query method for this is `#equal?`, but obviously that conflicts +with our use of `#equal!` to test equality using `#==`. So instead we use `#identical!` +which makes more sense really. + + :a.identical!(:a) + + expect ::IdentityAssay do + "a".identical!("a") + end + + :a.not_identical!('a') + +## instance_of! + + 1.instance_of!(Integer) + + expect ::InstanceAssay do + 1.instance_of!(String) + end + + 1.not_instance_of!(String) + +## kind_of! + + 1.kind_of!(Integer) + + expect ::KindAssay do + 1.kind_of!(String) + end + + 1.not_kind_of!(String) + +## within! + + 1.within!(2, 1.5) + + expect ::WithinAssay do + 1.within!(2, 0.5) + end + + 1.not_within!(2, 0.5) + +## close! + + 1.close!(2, 1.5) + + expect ::CloseAssay do + 1.close!(5, 0.5) + end + + 1.not_close!(5, 0.5) + +## match! + + "abc".match!(/a/) + + expect ::MatchAssay do + "abc".match!(/x/) + end + + "abc".not_match!(/g/) + +## respond_to! + + "string".respond_to!(:upcase) + + expect ::RespondAssay do + "string".respond_to!(:not_a_method) + end + + "string".not_respond_to!(:not_a_method) + +## satisfy! + + 5.satisfy!{ |x| x > 3 } + + expect ::ExecutionAssay do + 5.satisfy!{ |x| x < 3 } + end + + 5.not_satisfy!{ |x| x < 3 } + +## raises! + + ::ArgumentError.raised!{ raise ::ArgumentError } + +An extension to Proc class can also be used. + + procedure = lambda{ raise ::ArgumentError } + + procedure.raises!(::ArgumentError) + + expect ::RaiseAssay do + procedure.raises!(::TypeError) + end + +## rescues! + + ::ArgumentError.rescued!{ raise ::ArgumentError } + +An extension to Proc class can also be used. + + procedure = lambda{ raise ::ArgumentError } + + procedure.rescues!(::StandardError) + + expect ::RescueAssay do + procedure.rescues!(::TypeError) + end + +## throws! + + :foo.thrown!{ throw :foo } + +An extension to Proc class can also be used. + + procedure = lambda{ throw :foo } + + procedure.throws!(:foo) + + expect ::ThrowAssay do + procedure.throws!(:bar) + end + +## Other query methods + +A query method that Assay has no class for works the same way, by +calling the object's own method. It fails with a plain `Assertion`. + + 10.even! + 10.not_odd! + 10.between!(1, 20) + + expect ::Assertion do + 10.odd! + end + + expect ::Assertion do + 10.not_between!(1, 20) + end + +Hashes can be compared like anything else. + + {:a=>1}.equal!({:a=>1}) + + expect ::EqualAssay do + {:a=>1}.equal!({:a=>2}) + end + +A bang method that means nothing is still a NoMethodError, and Ruby's +own bang methods are left alone. + + expect ::NoMethodError do + 10.no_such_thing! + end + + "abc".upcase!.equal!("ABC") + + 10.respond_to?(:even!).true! + 10.respond_to?(:no_such_thing!).false! diff --git a/demo/core/03_assertor.md b/demo/core/03_assertor.md index e63a624..d92b4ad 100644 --- a/demo/core/03_assertor.md +++ b/demo/core/03_assertor.md @@ -97,3 +97,21 @@ Error messages are handle by RSpec by `#failure_message_for_should` and assertor.failure_message_for_should(1) assertor.failure_message_for_should_not(2) + +## Hashes + +A Hash under test is not mistaken for options. Only a trailing Hash +whose keys are all `:message` or `:backtrace` is taken as options. + + EqualAssay.assert!({:a=>1}, {:a=>1}) + EqualAssay.assert!({}, {}) + + expect ::EqualAssay do + EqualAssay.assert!({:a=>1}, {:a=>2}) + end + + EqualAssay[{:a=>1}] =~ {:a=>1} + + expect ::EqualAssay do + EqualAssay.assert!(1, 2, :message=>"my message") + end diff --git a/lib/assay/assertable.rb b/lib/assay/assertable.rb index a9926b4..8011387 100644 --- a/lib/assay/assertable.rb +++ b/lib/assay/assertable.rb @@ -75,7 +75,7 @@ def fail?(subject, *criteria, &block) # Test the assertion, raising the exception if failing. # def assert!(*arguments, &block) - options = (Hash === arguments.last ? arguments.pop : {}) + options = extract_options(arguments) backtrace = options[:backtrace] || caller message = options[:message] || assert_message(*arguments, &block) @@ -98,7 +98,7 @@ def assert!(*arguments, &block) # Test the inverse assertion, raising the exception if not failing. # def refute!(*arguments, &block) - options = (Hash === arguments.last ? arguments.pop : {}) + options = extract_options(arguments) backtrace = options[:backtrace] || caller message = options[:message] || refute_message(*arguments, &block) @@ -138,6 +138,22 @@ def refute_message(*arguments, &block) private + # + # Take the options off the end of an argument list, if there are any. + # A trailing Hash counts as options only if every key is `:message` or + # `:backtrace`, so that a Hash under test isn't mistaken for them. + # To be certain, pass options explicitly, even if empty of use: + # `EqualAssay.assert!(a, b, :backtrace=>caller)`. + # + def extract_options(arguments) + last = arguments.last + if Hash === last && !last.empty? && last.keys.all?{ |k| k == :message || k == :backtrace } + arguments.pop + else + {} + end + end + ## ## Increment global `$ASSERTION_COUNTS` variable. ## diff --git a/lib/assay/assertor.rb b/lib/assay/assertor.rb index 9973da9..0a084f6 100644 --- a/lib/assay/assertor.rb +++ b/lib/assay/assertor.rb @@ -63,9 +63,9 @@ def assert!(subject, &block) arguments, block = complete_criteria(subject, &block) if @not - @assay.refute!(*arguments, &block) + @assay.refute!(*arguments, {:backtrace=>caller}, &block) else - @assay.assert!(*arguments, &block) + @assay.assert!(*arguments, {:backtrace=>caller}, &block) end end @@ -81,9 +81,9 @@ def refute!(subject, &block) arguments, block = complete_criteria(subject, &block) if @not - @assay.assert!(*arguments, &block) + @assay.assert!(*arguments, {:backtrace=>caller}, &block) else - @assay.refute!(*arguments, &block) + @assay.refute!(*arguments, {:backtrace=>caller}, &block) end end diff --git a/lib/assay/bang.rb b/lib/assay/bang.rb new file mode 100644 index 0000000..e52c02c --- /dev/null +++ b/lib/assay/bang.rb @@ -0,0 +1,147 @@ +require_relative '../assay' + +module Assay + + # Bang turns query methods into assertions: call one with `!` in place + # of `?` and it has to hold. + # + # "string".instance_of!(String) + # "string".equal!("string") + # "string".not_equal!("another") + # + # Where Assay has a class for the assertion, a failure is an instance of + # that class, here `InstanceAssay` and `EqualAssay`. Any other query + # method an object has works too, and fails with a plain `Assertion`: + # + # [].empty! # EmptyAssay + # 10.even! # Assertion, by way of Integer#even? + # + # Nothing is defined ahead of time. A bang method that Ruby doesn't know + # is looked up when it is called, so assay classes added later are + # found, and real bang methods such as `String#upcase!` are never + # touched. + # + module Bang + + # Bang names that differ from the assay's own name. + NAMES = { + :satisfy => :executes, + :thrown => :throw + } + + # + # Find the assay class for a bang name (less the `!` and any `not_`), + # by name or by the query method it stands for. Returns nil if Assay + # has none. + # + def self.lookup(name) + name = NAMES[name.to_sym] || name.to_sym + ::Assertion.by_name(name) || ::Assertion.by_operator(:"#{name}?") + end + + # + # Split a method name into the bare name and whether it is negated. + # The name is nil unless it is a bang method. Always returns a pair: + # destructuring a bare nil would ask nil for `to_ary`, and so come + # back through `respond_to_missing?` without end. + # + def self.parse(method_name) + name = method_name.to_s + return [nil, false] unless name.end_with?('!') && name.size > 1 + name = name.chomp('!') + if name.start_with?('not_') && name.size > 4 + [name[4..-1], true] + else + [name, false] + end + end + + # Included into Object. + # + module Methods + + # + # Handle `foo!` and `not_foo!` by way of an assay class or the + # object's own `foo?`. + # + def method_missing(method_name, *args, &block) + name, negate = ::Assay::Bang.parse(method_name) + + return super unless name + + if assay = ::Assay::Bang.lookup(name) + if negate + assay.refute!(self, *args, {:backtrace=>caller}, &block) + else + assay.assert!(self, *args, {:backtrace=>caller}, &block) + end + elsif respond_to?("#{name}?") + truth = __send__("#{name}?", *args, &block) + call = "#{inspect}.#{name}?" + call += "(#{args.map{ |a| a.inspect }.join(', ')})" unless args.empty? + if negate + ::Kernel.refute(truth, ::Assertion, "! #{call}", caller) + else + ::Kernel.assert(truth, ::Assertion, call, caller) + end + else + super + end + end + + # + def respond_to_missing?(method_name, include_private=false) + name, _ = ::Assay::Bang.parse(method_name) + if name && (::Assay::Bang.lookup(name) || respond_to?("#{name}?")) + true + else + super + end + end + + end + + # Included into Proc, for assertions about what calling it does. + # + module ProcMethods + + # Calling the procedure has to raise exactly this exception. + def raises!(*exceptions) + ::RaiseAssay.assert!(*exceptions, {:backtrace=>caller}, &self) + end + + def not_raises!(*exceptions) + ::RaiseAssay.refute!(*exceptions, {:backtrace=>caller}, &self) + end + + # Calling the procedure has to raise this exception or a kind of it. + def rescues!(*exceptions) + ::RescueAssay.assert!(*exceptions, {:backtrace=>caller}, &self) + end + + def not_rescues!(*exceptions) + ::RescueAssay.refute!(*exceptions, {:backtrace=>caller}, &self) + end + + # Calling the procedure has to throw this symbol. + def throws!(symbol) + ::ThrowAssay.assert!(symbol, {:backtrace=>caller}, &self) + end + + def not_throws!(symbol) + ::ThrowAssay.refute!(symbol, {:backtrace=>caller}, &self) + end + + end + + end + +end + +class Object + include Assay::Bang::Methods +end + +class Proc + include Assay::Bang::ProcMethods +end diff --git a/lib/assay/fluidity/grammar.rb b/lib/assay/fluidity/grammar.rb index 61aee61..3362e53 100644 --- a/lib/assay/fluidity/grammar.rb +++ b/lib/assay/fluidity/grammar.rb @@ -26,9 +26,9 @@ def ==(other) def method_missing(s, *a, &b) if assay = (::Assertion.by_name(s) || ::Assertion.by_operator(s)) if @negate - assay.refute!(@target, *a, &b) + assay.refute!(@target, *a, {:backtrace=>caller}, &b) else - assay.assert!(@target, *a, &b) + assay.assert!(@target, *a, {:backtrace=>caller}, &b) end else q = (s.to_s.end_with?('?') ? s : (s.to_s+'?')) diff --git a/lib/assay/minitest/extensions.rb b/lib/assay/minitest/extensions.rb index 7099eaf..bc91f1d 100644 --- a/lib/assay/minitest/extensions.rb +++ b/lib/assay/minitest/extensions.rb @@ -347,7 +347,7 @@ def wont_be_nil(msg=nil) # @raise RaiseAssay # def must_raise(exp, msg=nil, call=nil) - RaiseAssay.assert!(exp, msg=nil, call=nil, &self) + RaiseAssay.assert!(exp, :message=>msg, :backtrace=>(call || caller), &self) end # @@ -358,7 +358,7 @@ def must_raise(exp, msg=nil, call=nil) # @raise RaiseAssay # def wont_raise(exp, msg=nil, call=nil) - RaiseAssay.refute!(exp, msg, call, &self) + RaiseAssay.refute!(exp, :message=>msg, :backtrace=>(call || caller), &self) end # diff --git a/lib/assay/rspec/operatics.rb b/lib/assay/rspec/operatics.rb index cf9c7fb..6c46246 100644 --- a/lib/assay/rspec/operatics.rb +++ b/lib/assay/rspec/operatics.rb @@ -27,7 +27,7 @@ def method_missing(op, *a, &b) # def assert!(op, *a, &b) if assay = Assertion.by_operator(op) - return assay.assert!(@target, *a, &b) + return assay.assert!(@target, *a, {:backtrace=>caller}, &b) else ::Kernel.assert(@target.__send__(op, *a, &b), ::Assertion, "#{@target.inspect} #{op} #{a.map{ |x| x.inspect }.join(', ')}", caller) end @@ -36,7 +36,7 @@ def assert!(op, *a, &b) # def refute!(op, *a, &b) if assay = Assertion.by_operator(op) - return assay.refute!(@target, *a, &b) + return assay.refute!(@target, *a, {:backtrace=>caller}, &b) else ::Kernel.refute(@target.__send__(op, *a, &b), ::Assertion, "! #{@target.inspect} #{op} #{a.map{ |x| x.inspect }.join(', ')}", caller) end diff --git a/lib/assay/rspec/should.rb b/lib/assay/rspec/should.rb index 7a8ea50..e768cb0 100644 --- a/lib/assay/rspec/should.rb +++ b/lib/assay/rspec/should.rb @@ -28,14 +28,14 @@ def should_not(matcher) # # def should=(value) - EqualAssay.assert!(self, value) + EqualAssay.assert!(self, value, :backtrace=>caller) end # # # def should_not=(value) - EqualAssay.refute!(self, value) + EqualAssay.refute!(self, value, :backtrace=>caller) end end