diff --git a/HISTORY.md b/HISTORY.md index 2f1afe3..0394e07 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, and Bang joins them. Assay needs Ruby 2.7 or newer. +back, each loaded on its own, and Bang and AE join them. Assay needs Ruby 2.7 or newer. Changes: @@ -17,6 +17,11 @@ Changes: * 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`. +* Add `assay/ae`, the notation of the AE gem (`x.assert == y`, + `expect`, and optionally `should`, `must` and `ok`/`no`), built on + Assay's classes: a failure is of the Assay class for the method + where there is one. Its module is `Assay::AE`. The AE gem itself + carries on unchanged. * 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. @@ -27,6 +32,13 @@ Changes: * Fix `assert(false)` passing silently once `assay/fluidity/assert` was loaded. Worse, Assay itself called that `assert`, so no assay could fail either. +* Fix fluent assertions that used a method every object has, such as + `x.should.be.kind_of?(String)`, `x.assert.nil?` or `x.assert != y`. + The grammar object answered them itself, so they never failed. This + goes back to the Fluidity gem. Likewise `expect(x).to.kind_of?(String)` + in the RSpec notation, which is now a NoMethodError. +* The fluent notation passes keyword arguments on to an object's own + query method. * Fix the fluent fallback to an object's own query method ignoring negation: `x.should_not.be.no` now fails when `x.no?` is true. * Fix `will_not` and `wont`. They were never defined, and loading the diff --git a/README.md b/README.md index 96690e7..56cd6cb 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/ae` | AE's functor: `x.assert == y`, `a.assert.include?(e)` | | `assay/bang` | Query methods as assertions: `x.equal!(y)`, `x.empty!` | Whichever you choose, a failure is an instance of the same assay class, @@ -120,6 +121,42 @@ 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`). +#### AE + +The AE notation, from the [AE](https://github.com/rubyworks/ae) gem, +needs no vocabulary of its own: call any method of the object under +test through `assert`, and its result is asserted. + + require 'assay/ae' + + x.assert == y + a.assert.include?(e) + x.refute.nil? + "Daffy Duck".assert.start_with?("Daffy") + +Where Assay has a class for the method, as it does for the first three, +that class is the failure raised; otherwise it is a plain `Assertion`. +`assert` still takes a truth value, or a block, as it does in Test::Unit. + + assert(x > 3, "too small") + assert{ x > 3 } + +`expect` tests a block's result by case equality, or that it raises. + + expect ArgumentError do + Integer("x") + end + +The subjunctive verbs and the `ok`/`no` checks are loaded separately. + + require 'assay/ae/should' # x.should == y, x.should.be.a String + require 'assay/ae/must' # x.must == y + require 'assay/ae/check' # check{ |a, b| a == b }; ok 1, 1 + +AE and Fluidity both define `assert`, `should` and `must` on every +object, so load one or the other. Likewise load `assay/ae` or the AE +gem, not both: the gem stands on its own and raises only `Assertion`. + #### Bang Bang turns a query method into an assertion: call it with `!` in place @@ -227,6 +264,11 @@ Bang's failures are now assay classes where there is one, not `Assay::Assertions`, `Assay::Matchers` and `Assay::Extensions` are as they were. +The AE gem is not retired. `assay/ae` is the same notation built on +Assay's classes, under `Assay::AE` rather than `AE`. It leaves out +`ae/legacy` (use `assay/testunit`), `ae/pry` and AE's framework +adapters (Assay has its own, above). + ### Learning More There is more to learn about Assay, mainly the variety of assay classes diff --git a/Rakefile b/Rakefile index a3d2bcd..297c4f9 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 bang] +DEMOS = %w[core minitest testunit rspec fluidity ae bang] desc "Run the QED demos" task :demo do diff --git a/demo/ae/01_overview.md b/demo/ae/01_overview.md new file mode 100644 index 0000000..3f8d087 --- /dev/null +++ b/demo/ae/01_overview.md @@ -0,0 +1,98 @@ +# The AE Notation + +AE (Assertive Expressive) is a notation designed around the concept of +an Assertor. The Assertor is an Assertion Functor, or Higher-Order +Function, which reroutes method calls while monitoring them for failing +conditions. It began as a library of its own, the AE gem, and is here +built on Assay's assertion classes. + + +## What It Provides + +Requiring the notation + + require 'assay/ae' + +loads the +Assertor+ class, the method +assert+ and its antonyms ++assert!+ and +refute+, the method +expect+, and a set of core +extensions that make writing certain types of assertions easier. + + +## Assertion and Assertor Classes + +The +Assertion+ class is at the heart of it. The +Assertion+ class +is a subclass of Exception. When an assertion is made and fails, it +is an Assertion that is raised: either an instance of Assertion +itself, or of the Assay class for the method used, each of which is +a subclass of Assertion. + + expect Assertion do + msg = "my failure message" + assert false, msg + end + +Like any raised exception, the last Assertion message is available +via `$!`. + +(FYI, in Test::Unit the equivalent class was called +AssertionFailedError+.) + +Assertions themselves are not generally used in creating tests or +behavior specifications. Rather they are used to create additional +types of assertion methods. + +As mentioned above the +Assertor+ class is a type of Higher-Order +function, or Functor, which intercedes with a normal message +invocation to monitor for failed conditions, upon which is raises +Assertion exceptions. + + +## Assertion Methods + +The three methods, +assert+, assert! and +refute+ all +return an Assertor instance when used fluidly, i.e. magic-dot +notation, higher-order notation, functor notation, whatever you +prefer to call it. + + assert(Assay::AE::Assertor === assert) + +Through the use of +method_missing+, the Assertor allows us to write +statements like: + + 1.assert == 1 + +If the operation evaluates to false or nil, then an Assertion error +is raised. + + expect Assertion do + 1.assert == 2 + end + +Assay has a class for `==`, so more exactly it is an EqualAssay. + + expect EqualAssay do + 1.assert == 2 + end + +The methods assert! and +refute+ are just like +assert+ +expect they purport the negative condition. Patterned after Ruby's +own use of "!" as meaning +not+, assert! should be +read "assert not". While +refute+ exists for the sake of those who +find the use of a bang method for this purpose unsuited to them. + + +## How It Works + +An Assertor essentially sits in wait for a method call (via +method_missing). When that happens it applies the method to the +original receiver, but wrapped in a clause that raises an +Assertion should the statement fail. If we wanted to be +pedantic, we could write our assertions like: + + raise Assertion.new("1 != 1") unless 1 == 1 + +Instead of + + 1.assert == 1 + +Obviously using Assertor methods are whole lot more concise. + diff --git a/demo/ae/03_assert.md b/demo/ae/03_assert.md new file mode 100644 index 0000000..f22a06f --- /dev/null +++ b/demo/ae/03_assert.md @@ -0,0 +1,398 @@ +# Assert Method + +## Compatible with Test::Unit + +The `assert` method is designed to be backward compatible +with the same method in `Test::Unit`. + +Using an argument, `assert` will check that an argument evaluates +to true. Optionally one can send along a meaningful message should +the assertion fail. + + assert(true, "Not true!") + + expect Assertion do + assert(false, "Not true!") + end + + +## Assert with a Block + +In addition +assert+ has been extended to accept a block. Like the case of the +argument, the block is expected to return something that evaluates as true. + + assert do + true + end + + Assertion.assert.raised? do + assert do + false + end + end + +We should also mention that, while probably not very useful, since +the arity of a block can be checked, one can also pass the receiver +into the block as a block argument. + + "hi".assert do |s| + /h/ =~ s + end + +Given an argument as well, `assert` compares it to the block's result +using `#==`. Any argument counts, even `false` or `nil`. + + assert(5) { 2 + 3 } + assert(nil) { nil } + + Assertion.assert.raised? do + assert(false) { true } + end + + +## Antonyms for Assert + +We can state the opposite assertion using `assert!`. + + 10.assert! == 9 + +Or, because some people do not like the use of a bang method, +refute+. + + 10.refute == 9 + +These terms can be used just as +assert+ is used in all examples, +but with the opposite inference. + +Another way to get the opposite inference, is to use +not+. + + 10.assert.not == 9 + +## Lambda Assertions + +Passing +assert+ a `Proc` object, or any object that responds to `#call`, +will be used as if it were a block. This allows for a simple way to quickly +create reusable assertions. + + palindrome = lambda{ |word| word == word.reverse } + + "abracarba".assert palindrome + +A lambda that takes no arguments is called without the receiver. + + "abracarba".assert lambda { true } + +The message for a failed assertion will come from calling `#to_s` on the +object. + +A Hash or a Symbol is a value like any other, even though each has +`#to_proc`, so here `assert` and `refute` check only that it is truthy. + + assert({a: 1}) + + Assertion.assert.raised? do + refute({a: 1}) + end + +## RSpec-style Assertion Matchers + +If an object passed to assert responds to `#matches?` then AE will handle +the object as an RSpec-style mather, the receiver will be passed to the +`#matches?` method to determine if the assertion passes and RSpec matcher +message methods will be used if they are defined. + + palindrome = Object.new + + def palindrome.matches?(word) + word == word.reverse + end + + "abracarba".assert palindrome + + +## Identity Assertions + +Rather then the general form. + + x = 10 + x.object_id.assert == x.object_id + +We can use Ruby's own `equal?`> method. + + x.assert.equal?(x) + +It fails for an equal but separate object. + + Assertion.assert.raised? do + "abc".assert.equal?("abc".dup) + end + +And the opposite. + + x.refute.equal?(11) + + Assertion.assert.raised? do + x.refute.equal?(x) + end + +AE provides `identical?`> method as an alternative +to make it a bit more clear. + + x.assert.identical?(x) + + +## Equality Assertions + +The most common assertion is that of value equality (`==`), +as we have seen throughout this document. But other forms of +equality can be verified as easily. We have already mentioned +identity. In addition there is *type equality*. + + 17.assert.eql? 17 + + Assertion.assert.raised? do + 17.assert.eql? 17.0 + end + +And there is *case equality*. + + Numeric.assert === 3 + + +## Checking Equality with a Block + +Because operators can not take blocks, and at times blocks can +be convenient means of supplying a value to an assertion, +AE has defined alternate renditions of the equality methods. +For equal? and eql?, the method names are the same, they simply +can take a block in place of an argument if need be. + +For *value equality* (`==`), the method is called *eq?*. + + 10.assert.eq? do + 10.0 + end + +And should it fail, + + Assertion.assert.raised? do + 10.assert.eq? do + 20 + end + end + + +## Case Equality + +For *case equality* (`===`), it is `case?`. + + Numeric.assert.case? do + "3".to_i + end + + Assertion.assert.raised? do + Numeric.assert.case? do + "3" + end + end + + +## Regular Expressions + +Regular Expressions can be used to make assertions in much the same way as equality. + + /i/.assert =~ "i" + + Assertion.assert.raised? do + /i/.assert =~ "g" + end + +Conversely the String class recognizes the #=~ method as well. + + "i".assert =~ /i/ + + Assertion.assert.raised? do + "i".assert =~ /g/ + end + + +## Exception Assertions + +Validating errors is easy too, as has already been shown +in the document to verify assertion failures. + + StandardError.assert.raised? do + unknown_method + end + + +## Assertions on Object State + +While testing or specifying the internal state of an object is +generally considered poor form, there are times when it is +necessary. Assert combined with +instance_eval+ makes it easy too. + + class X + attr :a + def initialize(a); @a = a; end + end + + x = X.new(1) + + x.assert.instance_eval do + @a == 1 + end + + Assertion.assert.raised? do + x.assert.instance_eval do + @a == 2 + end + end + + +## Catch/Try Assertions + +Catch/Try throws can be tested via `Symbol#thrown?`. + + :hookme.assert.thrown? do + throw :hookme + end + +Alternatively, a lambda containing the potential throw +can be the receiver using `throws?`. + + hook = lambda{ throw :hookme } + + hook.assert.throws?(:hookme) + + +## Assertions on Proc Changes + +I have to admit I'm not sure how this is useful, +but I found it in the Bacon API and ported it over +just for sake of thoroughness. + + a = 0 + + l = lambda{ a } + + l.assert.change?{ a +=1 } + + +## Assertion on literal True, False and Nil + +Ruby already provides the #nil? method. + + nil.assert.nil? + +AE adds `true?` and `false?` which acts accordingly. + + true.assert.true? + false.assert.false? + + +## Keyword Arguments + +Keyword arguments are passed on to the method as keywords. + + class Gate + def open?(strict: false) + !strict + end + end + + Gate.new.assert.open?(strict: false) + Gate.new.refute.open?(strict: true) + + +## Comparing a Method's Result + +A method called on `assert` makes the assertion itself, so its result +can't be compared afterwards. Here `size` returns 2, which is truthy, so +the assertion passes. The comparison with 3 is then made with the +assertion's own result, and checks nothing. + + require 'stringio' + $stderr, stderr = StringIO.new, $stderr + + [1, 2].assert.size == 3 + + warning, $stderr = $stderr.string, stderr + +To compare a result, call the method first. + + [1, 2].size.assert == 2 + +Because this is an easy mistake to make, AE warns when a method called +without arguments returns something other than true, false or nil. + + warning.assert.include?("`size` returned 2") + + +## Flunk + +`flunk` always fails, negated or not. + + Assertion.assert.raised? do + flunk "not done yet" + end + + Assertion.assert.raised? do + 10.refute.flunk + end + + +## Send Assertions + +Assert that a method can be successfully called. + + "STRING".assert.send?(:upcase) + + +## Numeric Delta and Epsilon + +You may wish to assert that a numeric value is with some +range. + + 3.assert.in_delta?(1,5) + +Or minimum range, relative to the smaller of the two magnitudes. + + 3.assert.in_epsilon?(3,5) + -100.0.assert.in_epsilon?(-100.05, 0.01) + + Assertion.assert.raised? do + -100.0.assert.in_epsilon?(-101.5, 0.01) + end + + +## Verifying Object State + +Not surprisingly if underlying object state needs to be verified, +instance_eval+ +can be used in conjunction with +assert+. + + class X + attr :a + def initialize(a); @a = a; end + end + + x = X.new(4) + + x.instance_eval do + @a.assert == 4 + end + +Calling #instance_eval on #assert works too, as shown under "Assertions +on Object State" above: the block runs in the object, and its result +is the assertion. + + Assertion.assert.raised? do + x.assert.instance_eval do + @a == "obviously wrong" + end + end + +For some testing underlying implementation might be considered poor +form. You will get no argument here. It should be used thoughtfully, +but I would not bet against there being occasions when such validations +might be needed. + diff --git a/demo/ae/04_subjunctive.md b/demo/ae/04_subjunctive.md new file mode 100644 index 0000000..8ffec5a --- /dev/null +++ b/demo/ae/04_subjunctive.md @@ -0,0 +1,100 @@ +# Subjunctives + +Okay. I can hear the BDDers rumbling, "where's the *should?*" +AE has nothing against "should", but there are different +approaches for utilizing should nomenclature in specifications, +and AE wants to be open to these techniques. One of which +is how Shoulda (http://shoulda.rubyforge.org) utilizes +`should` in a way analogous to RSpec's use of `it`. + +Even so, AE provides an optional mixin called `Subjunctive` which +can be used to create assertor methods with English subjunctive +terms, such as `should`, or `must`, `shall` and `will`. +To load this library use: + + require 'assay/ae/subjunctive' + +Then all that is required it to define a subjunctive method for all +objects. For example: + + def will(*args, &block) + Assay::AE::Assertor.new(self, :backtrace=>caller).be(*args,&block) + end + +It's that easy. Because of their commonality AE provides two such terms, +`should` and +must+ as optional add-ons out-of-the-box. + + require 'assay/ae/should' + require 'assay/ae/must' + +We will use these two methods interchangeable for the rest of this +demonstration, but to be clear they both work exactly the same way, +and almost exactly like `assert`. + +Keep in mind, AE "conical" functionality does not entail the subjunctive +forms. These are simply options you can load via your `test_helper.rb`, +or similar script, if you prefer these nomenclatures. + + +## Fluent Notation and Antonyms + +Like `assert`, `should` and `must` can be used as higher order functions. + + 4.should == 4 + 4.must == 4 + +Antonyms provided for +should+ as `should!` (read "should not") and `shouldnt`. +For `must`, they are `must!` and +wont+. + + 4.should! == 5 + 4.shouldnt == 5 + + 4.must! == 5 + 4.wont == 5 + + +## To Be + +On occasions where the English readability of a specification is hindered, +`be` can be used. + + StandardError.must.be.raised? do + unknown_method + end + +The `be` method is the same as `assert` with the single exception +that it will compare a lone argument to the receiver using `equate?`, +unlike `assert` which simply checks to see that the argument evaluates +as true. + + 10.should.be 10 + 10.should.be 10.0 + 10.should.be Numeric + + Assertion.assert.raised? do + 10.should.be "40" + end + + +## Indefinite Articles + +Additional English forms are `a` and `an`, equivalent to `be` except +that they use `case?` (same as `#===`) instead of `equate?` when +acting on a single argument. + + "hi".must.be.a String + + Assertion.assert.raised? do + /x/.must.be.a /x/ + end + +Otherwise they are interchangeable. + + "hi".must.be.an.instance_of?(String) + +The indefinite articles work well when a noun follows as an arguments. + + palindrome = lambda{ |x| x == x.reverse } + + "abracarba".must.be.a palindrome + diff --git a/demo/ae/05_expect.md b/demo/ae/05_expect.md new file mode 100644 index 0000000..71495cb --- /dev/null +++ b/demo/ae/05_expect.md @@ -0,0 +1,136 @@ +# Expect Method + +Expect is another assertion nomenclature available for use in your +tests or specifications. Inspired by Jay Fields' Expectations library, +it provides convenient syntax for creating exception and case equality +assertions. + + require 'assay/ae/expect' + + +## Underlying Comparison + +Expect uses `#===` for comparison. So providing an argument and a block +to #expect we can test for a somewhat broader range of compassion +than #assert. For example we can test for a subclass. + + expect Numeric do + 3 + end + + Assertion.assert.raised? do + expect Numeric do + "3" + end + end + +Any expected value counts, even `nil` or `false`. + + expect nil do + nil + end + + Assertion.assert.raised? do + "abc".expect nil do + "abc" + end + end + +A block that takes an argument is given the receiver. + + "abc".expect(3) { |s| s.size } + + +## Exception Expectation + +If the comparator is an Exception class or a instance of an Exception class, +then #expect will check to see if the block raises that kind of exception. + + expect StandardError do + some_undefined_method + end + + expect Assertion do + expect(nil) + end + +An instance of an Exception class stands for its class. + + expect ArgumentError.new do + raise ArgumentError + end + +An exception of another kind fails the expectation, but an interrupt or +an exit is never caught, so it isn't mistaken for a failure, or for +a pass when negated. + + expect SystemExit do + expect! ArgumentError do + exit + end + end + +This is an important distinction to note because it means `#expect` can not be used +if verify instances of Exception classes. + + Assertion.assert.raised? do + expect Exception do + Exception.new + end + end + + +## Regex Expectations + +That #expect entails `#===` also means we can check for Regexp matches. + + expect /x/ do + "oooxooo" + end + + +## Expected Method + +We can use #expected to make the receiver the object of expectation. + + x = "dummy" + + /x/.expected do + "x" + end + + +## Without Block + +Without a block, the receiver is compared to the argument. + + x.expect String + + +## Negative Forms + +Like #assert, `#expect` has a negated form called #expect! + + expect! /x/ do + "o" + end + +The pure word form for those who do not like the clever use of the +explimation mark is #forbid. + + forbid /x/ do + "o" + end + + +## Functor, or Higher Order Function + +Like #assert, #expect can be used used as a *fluid* notation. + + 10.expect == 10 + +In which case it works just like `#assert`, including negative forms. + + 10.expect! == 11 + 10.forbid == 11 + diff --git a/demo/ae/06_counts.md b/demo/ae/06_counts.md new file mode 100644 index 0000000..b895e2b --- /dev/null +++ b/demo/ae/06_counts.md @@ -0,0 +1,33 @@ +# Assertion Counts + +AE tracks the number of assertions made and the number that failed to pass. +We can reset the count using the +recount+ class method. + + old_counts = Assay::AE::Assertor.recount + +For example if we have one assertion pass and another fail. + + assert(true) + + expect Assertion do + assert(false) + end + +We will see that AE counted three assertions and one failure. + + counts = Assay::AE::Assertor.counts.dup + + counts[:total].assert == 3 + counts[:pass].assert == 2 + counts[:fail].assert == 1 + +The #expect call is an assertion too, which is why the total count is 3 +rather than 2. + +Now that we are done checking counts we will restore them so that +any other demos being run with this will tally correctly. + + Assay::AE::Assertor.recount(old_counts) + Assay::AE::Assertor.counts[:total] += 3 + Assay::AE::Assertor.counts[:pass] += 3 + diff --git a/demo/ae/07_matchers.md b/demo/ae/07_matchers.md new file mode 100644 index 0000000..db37a53 --- /dev/null +++ b/demo/ae/07_matchers.md @@ -0,0 +1,34 @@ +# Matchers + +Matchers are simply Procs or objects with the proper interface that can be +passed to #assert or #refute (or other Assertor) as an ecapsulated test. + +## Proc or #call + +Passing a Proc object, or any object that responds to `#call`, will use it +as if it were a block of the method. This allows for a simple way to quickly +create reusable assertions. + + palindrome = lambda{ |word| word == word.reverse } + + "abracarba".assert palindrome + +## #matches? + +Additionally if an object responds to #matches? then the receiver +will be passed to this method to determine if the assertion passes. + + palindrome = Object.new + + def palindrome.matches?(word) + word == word.reverse + end + + "abracarba".assert palindrome + +## RSpec, Shoulda and other 3rd-Party Matchers + +With tha addition of #matches?, AE supports the same interface for matchers +as RSpec. Any matcher library designed for use with RSpec should therefore +be usable with AE as well. This includes RSpecs own matchers and Shoulda's +excellent Rails matchers. diff --git a/demo/ae/08_check.md b/demo/ae/08_check.md new file mode 100644 index 0000000..133d6a8 --- /dev/null +++ b/demo/ae/08_check.md @@ -0,0 +1,61 @@ +## Check Ok/No + +The Check library is an optional library that can be used +to conveniently speed-up construction of reptitive assertions. + +To use it, first require the library, then include the mixin +into the namespace in which you will utilize it. + + require 'assay/ae/check' + + include Assay::AE::Check + +Now we can define ok/no check procedures. A one-off procedure is +defined with a block only. + + check do |x, y| + x == y + end + + ok 1,1 + no 1,2 + +To define reusable check procedures, give the procedure a name. + + check :palindrome do |x| + x.reverse == x + end + +This will also cause the current check method to be set. +Later in the code, the check procedure can be reset to this +by just passing the name. + + check :palindrome + + ok 'abracarba' + no 'foolishness' + +The Check mixin comes preloaded with a few standard checks. +By default the `:equality` procedure is used. + + check :equality + + ok 1=>1.0 + +Notice the use of the hash argument here. This is a useful construct for +many check procedures becuase it it akin to the `#=>` pattern we often +see in code examples and it also allows for multiple assertions in one call. +For instance, in the case of `:equality`, multiple entries convey a +meaning of logical-or. + + ok 1=>2, 1.0=>1 + +This would pass because the second assertion of equality is true. + +Another built in check is `:case_equality` which uses `#===` instead of `#==` +to make the comparison. + + check :case_equality + + ok 1=>Integer + diff --git a/demo/ae/09_assay.md b/demo/ae/09_assay.md new file mode 100644 index 0000000..38fd1ef --- /dev/null +++ b/demo/ae/09_assay.md @@ -0,0 +1,124 @@ +# Assay Classes + +The AE notation asserts the result of whatever method is called on the +object under test. Assay adds two things to that. + +## Typed Failures + +When the method is the operator of an Assay class, a failure is raised +as that class. The object's own method still decides the result. + + expect KindAssay do + 10.assert.kind_of?(String) + end + + expect NilAssay do + 10.assert.nil? + end + + expect IncludeAssay do + [1,2,3].assert.include?(4) + end + + expect LessAssay do + 10.assert < 5 + end + + expect UnequalAssay do + 10.assert != 10 + end + +So too when it is negated. + + expect KindAssay do + 10.refute.kind_of?(Integer) + end + +AE's own query methods have classes as well: `eq?` fails with an +EqualAssay, `case?` with a CaseAssay, `equal?` with an IdentityAssay, +`in_delta?` with a WithinAssay, `in_epsilon?` with a CloseAssay, +`raised?` and `raises?` with a RescueAssay, `thrown?` and `throws?` +with a ThrowAssay. + + expect WithinAssay do + 3.assert.in_delta?(10, 1) + end + + expect RescueAssay do + ArgumentError.assert.raised?{ :fine } + end + + expect IdentityAssay do + "abc".assert.equal?("abc".dup) + end + +Since every Assay class is an Assertion, code that rescues Assertion +is none the wiser. + + expect Assertion do + 10.assert.kind_of?(String) + end + +A method Assay has no class for fails with a plain Assertion. + + error = begin + 10.assert.odd? ; nil + rescue Assertion => e + e + end + + error.class.assert == Assertion + + 10.refute.odd? + + error = begin + 10.refute.even? ; nil + rescue Assertion => e + e + end + + error.class.assert == Assertion + +## Assay's Own Words + +If the object has no method by the name, but Assay has an assertion by +that operator or name, the Assay class makes the test. + + "abc".assert.like?("abc") + + 10.assert.kind_of(Integer) + + 10.assert.within?(11, 2) + + expect KindAssay do + 10.assert.kind_of(String) + end + + expect WithinAssay do + 10.assert.within?(20, 2) + end + +Anything else is an error, not an assertion. + + expect NoMethodError do + 10.assert.zork + end + +## Assay Matchers + +An Assay class can be turned into a matcher with `[]`, and `assert` +and `refute` accept one. + + is_ten = EqualAssay[10] + + 10.assert is_ten + 11.refute is_ten + + expect EqualAssay do + 11.assert is_ten + end + + expect EqualAssay do + 10.refute is_ten + end + diff --git a/demo/ae/applique/setup.rb b/demo/ae/applique/setup.rb new file mode 100644 index 0000000..d0a7fe0 --- /dev/null +++ b/demo/ae/applique/setup.rb @@ -0,0 +1,11 @@ +require 'assay/ae' + +# The other demos share a few helper methods (`assert`, `refute`, +# `expect`) that the AE notation has its own versions of. In these +# demos the names mean AE's. +[:assert, :assert!, :refute, :flunk].each do |name| + define_method(name, Assay::AE::Assert.instance_method(name)) +end +[:expect, :expect!, :forbid].each do |name| + define_method(name, Assay::AE::Expect.instance_method(name)) +end diff --git a/demo/fluidity/05_object_methods.md b/demo/fluidity/05_object_methods.md new file mode 100644 index 0000000..f729e36 --- /dev/null +++ b/demo/fluidity/05_object_methods.md @@ -0,0 +1,102 @@ +## Methods Every Object Has + + require 'assay/fluidity' + +Some query methods belong to every object: `kind_of?`, `instance_of?`, +`nil?`, `eql?`, `equal?`, `respond_to?`, `is_a?`, `frozen?`. Used in an +assertion they are still about the object under test, so they pass and +fail like any other. + + 10.assert.kind_of?(Integer) + 10.should.be.kind_of?(Integer) + 10.must.be.an.instance_of?(Integer) + nil.should.be.nil? + 10.assert.eql?(10) + 10.assert.respond_to?(:succ) + 10.assert.is_a?(Numeric) + :a.assert.equal?(:a) + "abc".freeze.assert.frozen? + +Each of these fails when it should. Where an Assay class covers the +method, the failure is of that class. + + RaiseAssay.assert!(KindAssay) do + 10.assert.kind_of?(String) + end + + RaiseAssay.assert!(KindAssay) do + 10.should.be.kind_of?(String) + end + + RaiseAssay.assert!(InstanceAssay) do + 10.must.be.an.instance_of?(Numeric) + end + + RaiseAssay.assert!(NilAssay) do + 10.should.be.nil? + end + + RaiseAssay.assert!(EqualityAssay) do + 10.assert.eql?(10.0) + end + + RaiseAssay.assert!(RespondAssay) do + 10.assert.respond_to?(:upcase) + end + +Where none does, the object's own method decides, and the failure is a +plain Assertion. + + RaiseAssay.assert!(Assertion) do + 10.assert.is_a?(String) + end + + RaiseAssay.assert!(Assertion) do + "abc".assert.equal?("abc".dup) + end + + RaiseAssay.assert!(Assertion) do + "abc".dup.assert.frozen? + end + +The same goes for negation. + + 10.should_not.be.kind_of?(String) + 10.assert.not.nil? + + RaiseAssay.assert!(KindAssay) do + 10.should_not.be.kind_of?(Integer) + end + + RaiseAssay.assert!(NilAssay) do + nil.assert.not.nil? + end + +The `!=` operator is the opposite of `==`. + + 10.assert != 11 + + RaiseAssay.assert!(UnequalAssay) do + 10.assert != 10 + end + +Keyword arguments are passed along to the object's method. + + gate = Class.new do + def open?(strict: false) + !strict + end + end + + gate.new.should.be.open?(strict: false) + + RaiseAssay.assert!(Assertion) do + gate.new.should.be.open?(strict: true) + end + +A method the object doesn't have is an error, not an assertion. + + RaiseAssay.assert!(NoMethodError) do + 10.assert.zork + end + diff --git a/demo/rspec/04_expect.md b/demo/rspec/04_expect.md index 38dd46c..6cf83e6 100644 --- a/demo/rspec/04_expect.md +++ b/demo/rspec/04_expect.md @@ -28,6 +28,13 @@ Any other operator is sent to the object, and has to come back true. expect(10).to <= 5 end +Only operators are delegated. A named method is an error, because +the RSpec notation has matchers for those. + + assert_raises NoMethodError do + expect(10).to.kind_of?(String) + end + ### blocks Given a block instead of a value, `expect` passes the block to the diff --git a/lib/assay/ae.rb b/lib/assay/ae.rb new file mode 100644 index 0000000..3da8bc3 --- /dev/null +++ b/lib/assay/ae.rb @@ -0,0 +1,29 @@ +require_relative '../assay' + +require_relative 'ae/assertor' +require_relative 'ae/assert' +require_relative 'ae/expect' + +# The AE notation, from the Assertive Expressive (AE) gem: any method of +# the object under test becomes an assertion when called through `assert`. +# +# x.assert == y +# a.assert.include?(e) +# x.refute.nil? +# +# expect ArgumentError do +# ... +# end +# +# Where Assay has a class for the method, a failure is of that class; +# otherwise it is a plain Assertion. The subjunctive verbs, and the +# `ok`/`no` checks, are loaded separately: +# +# require 'assay/ae/should' +# require 'assay/ae/must' +# require 'assay/ae/check' +# +class ::Object + include ::Assay::AE::Assert + include ::Assay::AE::Expect +end diff --git a/lib/assay/ae/assert.rb b/lib/assay/ae/assert.rb new file mode 100644 index 0000000..9d0b247 --- /dev/null +++ b/lib/assay/ae/assert.rb @@ -0,0 +1,77 @@ +require_relative 'assertor' + +module Assay::AE + + # The Assert module holds the core extension methods `assert`, `refute` + # and `flunk`. `require 'assay/ae'` includes it in Object. + module Assert + + # Assert a operational relationship. + # + # 4.assert == 3 + # + # If only a single test argument is given then #assert + # simply validates that it evalutate to true. An optional + # message argument can be given in this case which will + # be used instead of the deafult message. + # + # assert(4==3, "not the same thing") + # + # In block form, #assert ensures the block evalutes + # truthfully, i.e. not as nil or false. + # + # assert{ 4==3 } + # + # @return [Assertor] Assertion functor. + def assert(*args, &block) + Assertor.new(self, :backtrace=>caller).assert(*args, &block) + end + + # Same as 'object.assert == other'. + # + # @return [Assertor] Assertion functor. + def assert=(cmp) + Assertor.new(self, :backtrace=>caller).assert == cmp + end + + # Opposite of assert. + # + # 4.refute == 4 #=> Assertion Error + # + # @return [Assertor] Assertion functor. + def refute(*args, &block) + Assertor.new(self, :backtrace=>caller).not.assert(*args, &block) + end + + # Same as 'object.refute == other'. + # + # @return [Assertor] Assertion functor. + def refute=(cmp) + Assertor.new(self, :backtrace=>caller).not.assert == cmp + end + + # Alias for #refute. Read it as "assert not". + # + # 4.assert! == 4 + # + alias_method :assert!, :refute + + # Directly raise an Assertion failure. + # + # @param message [String] + # Error message. + # + # @param backtrace [String] + # Backtrace, used to pass up an error from lower in the stack. + # + # @raise [Assertion] + # Assertion error with given `message`. + def flunk(message=nil, backtrace=nil) + Assertor.assert(false, message, false, backtrace || caller) + end + + end + +end + +# Copyright (c) 2008 Thomas Sawyer diff --git a/lib/assay/ae/assertor.rb b/lib/assay/ae/assertor.rb new file mode 100644 index 0000000..6070c1f --- /dev/null +++ b/lib/assay/ae/assertor.rb @@ -0,0 +1,453 @@ +require_relative '../../assay' +require_relative 'core_ext' + +module Assay; end +module Assay::AE + + # Assertor is the class behind the AE notation. It is an *assertion + # functor*, a higher-order function: it takes whatever method is called + # on it, calls that method on the object under test, and asserts the + # result. + # + # x.assert == y # Assertor.new(x) receives `==` + # + # It is built on BasicObject, so that the methods every object has + # (`kind_of?`, `nil?`, `respond_to?`) are assertions too. + # + # When Assay has a class for the method, by its operator, a failure is + # raised as that class: `x.assert == y` fails with an EqualAssay. Any + # other method fails with a plain Assertion. + # + class Assertor < ::BasicObject + + # Initial settings of assertion counts. + ZERO_COUNTS = {:total=>0, :pass=>0, :fail=>0} + + # AE's own query methods, and the Assay class each one fails with. + # Methods that are an Assay class's operator need no entry. + ASSAYS = { + :eq? => :EqualAssay, + :case? => :CaseAssay, + :match? => :MatchAssay, + :equal? => :IdentityAssay, + :in_delta? => :WithinAssay, + :in_epsilon? => :CloseAssay, + :raises? => :RescueAssay, + :raised? => :RescueAssay, + :throws? => :ThrowAssay, + :thrown? => :ThrowAssay + } + + # Returns the Hash used to track assertion counts. It is the global + # `$ASSERTION_COUNTS`, which every notation adds to. + def self.counts + $ASSERTION_COUNTS + end + + # Reset assertion counts. + # + # reset - Hash which can be used to set counts manually (optional). + # + # Returns the Hash of previous counts. + def self.recount(reset=nil) + old_counts = counts.dup + if reset + reset.each do |type, value| + counts[type.to_sym] = value + end + else + counts.replace(ZERO_COUNTS.dup) + end + return old_counts + end + + # Increment assertion counts. If +pass+ is +true+ then +:total+ + # and +:pass+ are increased. If +pass+ if +false+ then +:total+ + # and +:fail+ are incremented. + def self.increment_counts(pass) + counts[:total] += 1 + if pass + counts[:pass] += 1 + else + counts[:fail] += 1 + end + return counts + end + + # Basic assertion. This method by-passes all the Assertor fluent + # constructs and performs the underlying assertion procedure. It + # is used by Assertor as the end call of an assertion. + # + # The +error+ can be a message, an exception, or a Proc that + # returns either. A Proc is only called if the assertion fails, + # which saves building a message that is never shown. + # + # The +assay+ is the class of exception to raise for a message. It + # defaults to Assertion. + def self.assert(pass, error=nil, negated=nil, backtrace=nil, assay=nil) + pass = !!negated ^ !!pass + increment_counts(pass) + if !pass + backtrace = backtrace || ::Kernel.caller + raise_assertion(error, negated, backtrace, assay) + end + return pass + end + + # Raise an assertion failure. + def self.raise_assertion(error, negated, backtrace=nil, assay=nil) + error = error.call if ::Proc === error + if not ::Exception === error + error = (assay || assertion_error).new(error) + end + error.set_negative(negated) + error.set_backtrace(backtrace || ::Kernel.caller) + error.set_assertion(true) + ::Kernel.raise error + end + + # Returns the Exception class raised when an assertion fails and no + # Assay class covers it. + def self.assertion_error + ::Assertion + end + + # The Assay class for a method name, if there is one. + def self.assay_for(sym) + if name = ASSAYS[sym] + ::Object.const_get(name) + else + ::Assertion.by_operator(sym) + end + end + + # BasicObject has a few public methods of its own, which would + # answer a call themselves instead of making an assertion. Making + # these private sends them through #method_missing like any other + # method, so `x.assert.instance_eval { @a == 1 }` asserts something + # about `x`. Only #__send__ and #__id__ stay public, because Ruby + # relies on them. + private :==, :!, :!=, :equal?, :instance_eval, :instance_exec + + # Methods with no arguments whose result is not true, false or nil + # get a warning, once per line, because the result is probably + # meant to be compared, as in `x.assert.size == 3`. That compares + # the assertion's own result, true, and checks nothing. + def self.chain_warning(where, message) + @chain_warnings ||= {} + return if @chain_warnings[where] + @chain_warnings[where] = true + ::Kernel.warn("#{where}: warning: #{message}") + end + + # Color diffs are skipped when the two strings are this large + # (the product of their lengths), because building one takes + # time and memory in proportion. + DIFF_LIMIT = 1_000_000 + + # New Assertor. + # + def initialize(delegate, opts={}) + @delegate = delegate + @message = opts[:message] + @backtrace = opts[:backtrace] || ::Kernel.caller + @negated = !!opts[:negated] + end + + # Negate the meaning of the assertion. + # + def not(msg=nil) + @negated = !@negated + @message = msg if msg + self + end + + # Internal assert, provides all functionality associated + # with external #assert method. (See Assert#assert) + # + # Returns +true+ or +false+ based on assertions success. + # + def assert(*args, &block) + return self if !block && args.empty? + + # Block + if block + result = block.arity > 0 ? block.call(@delegate) : block.call + if args.empty? + return __assert__(result) { @message || block.inspect } + else + # Any expected value counts, even false or nil. + match = args.shift + return __assert__(match == result) { @message || "#{__inspect__(match)} == #{__inspect__(result)}" } + end + end + + target = args.shift + + # Assay matchers, such as `EqualAssay[10]` + if ::Assay::Assertor === target + return @negated ? (target !~ @delegate) : (target =~ @delegate) + + # Proc-style + elsif proc_assertion?(target) + pass, error = proc_apply(target) + + # RSpec-style matchers + elsif rspec_matcher?(target) + pass, error = rspec_matcher_apply(target) + + # Truthiness + else + pass = target # truthiness + error = args.shift # optional message for TestUnit compatiability + end + + __assert__(pass, error) + end + + # Internal expect, provides all functionality associated + # with external #expect method. (See Expect#expect) + # + def expect(*args, &block) + return self if !block && args.empty? # same as #assert + + pass = false + error = nil + assay = nil + + if block + # Any expected value counts, even false or nil. + match = args.empty? ? @delegate : args.shift + if exception?(match) + # An exception instance stands for its class. + klass = ::Class === match ? match : match.class + assay = ::RescueAssay + $DEBUG, debug = false, $DEBUG # b/c it always spits-out a NameError + begin + block.arity > 0 ? block.call(@delegate) : block.call + pass = false + error = "#{klass} not raised" + rescue klass + pass = true + error = "#{klass} raised" + rescue ::SignalException, ::SystemExit, ::NoMemoryError + ::Kernel.raise + rescue ::Exception => e + pass = false + error = "#{klass} expected but #{e.class} was raised: #{e.message}" + ensure + $DEBUG = debug + end + error = @message || error + else + result = block.arity > 0 ? block.call(@delegate) : block.call + pass = (match === result) + assay = ::CaseAssay + error = ::Kernel.proc { @message || "#{__inspect__(match)} === #{__inspect__(result)}" } + end + + # Case Equality + else + target = args.shift + pass = (target === @delegate) + assay = ::CaseAssay + error = ::Kernel.proc { @message || "#{__inspect__(target)} === #{__inspect__(@delegate)}" } + end + + __assert__(pass, error, assay) + end + + # Fail, whether or not the assertion is negated. + def flunk(message=nil, backtrace=nil) + Assertor.assert(false, message || @message, false, backtrace || @backtrace) + end + + # Without this Ruby skips #method_missing for `=~`. + def =~(match) + method_missing(:"=~", match) + end + + # + def send(op, *a, **kw, &b) + method_missing(op, *a, **kw, &b) + end + + # + def inspect + @delegate.inspect + end + + private + + # Is `target` a Proc, or any other object that responds to #call? + # A Hash or Symbol is a value like any other, even though it has + # #to_proc. + def proc_assertion?(target) + ::Proc === target || target.respond_to?(:call) + end + + # + def proc_apply(target) + arity = (::Proc === target || ::Method === target) ? target.arity : target.method(:call).arity + pass = arity != 0 ? target.call(@delegate) : target.call + error = ::Kernel.proc { + @message || ( + to_s = target.method(:to_s) + to_s.arity == 0 ? to_s.call : to_s.call(@negated) + ) + } + return pass, error + end + + # Is `target` an RSpec-style matcher? + def rspec_matcher?(target) + target.respond_to?(:matches?) + end + + # + def rspec_matcher_apply(matcher) + pass = matcher.matches?(@delegate) + error = ::Kernel.proc { @message || rspec_matcher_message(matcher) } + return pass, error + end + + # + def rspec_matcher_message(matcher) + if @negated + if matcher.respond_to?(:failure_message_when_negated) + return matcher.failure_message_when_negated + end + if matcher.respond_to?(:failure_message_for_should_not) + return matcher.failure_message_for_should_not + end + if matcher.respond_to?(:negative_failure_message) + return matcher.negative_failure_message + end + end + + if matcher.respond_to?(:failure_message) + return matcher.failure_message + end + if matcher.respond_to?(:failure_message_for_should) + return matcher.failure_message_for_should + end + + return matcher.to_s + end + + # Is the +object+ an Exception class or an instance of one? + def exception?(object) + ::Exception === object || (::Class === object && object <= ::Exception) + end + + # Converts a missing method into an assertion: the method is called + # on the object under test and its result asserted. + # + # If the object has no such method but Assay has an assertion by + # that operator or name (`x.assert.like?(y)`, `x.assert.kind_of(K)`), + # the Assay class makes the test. + def method_missing(sym, *args, **kw, &block) + assay = Assertor.assay_for(sym) + + if !__responds__?(sym) && (found = assay || ::Assertion.by_name(sym)) + assay = found + list = kw.empty? ? args : args + [kw] + pass = assay.pass?(@delegate, *list, &block) + else + pass = @delegate.__send__(sym, *args, **kw, &block) + + if args.empty? && kw.empty? && !block + __chain_warning__(sym, pass) + end + end + + __assert__(pass, nil, assay) do + @message || compare_message(sym, *args) || generic_message(sym, *args, **kw) + end + end + + # Does the object under test have the method, public or not? An + # object that can't say is taken to have it. + def __responds__?(sym) + @delegate.respond_to?(sym, true) + rescue ::NoMethodError + true + end + + # Simple assert. The failure message can be given as a block, + # which is only called if the assertion fails. + def __assert__(pass, error=nil, assay=nil, &message) + Assertor.assert(pass, error || message, @negated, @backtrace, assay) + end + + # Warn about `x.assert.size == 3`, which checks only that `size` + # is truthy. See Assertor.chain_warning. + def __chain_warning__(sym, result) + return if ::TrueClass === result || ::FalseClass === result || ::NilClass === result + name = sym.to_s + return unless /\A[a-z_]\w*\z/i.match?(name) + where = @backtrace.first.to_s.sub(/:in .*\z/, '') + value = __inspect__(result) + value = value[0, 40] + '...' if value.size > 43 + Assertor.chain_warning(where, + "`#{name}` returned #{value}, so only its truthiness was checked. " \ + "To compare the result, write `object.#{name}.assert == expected`." + ) + end + + # The object's #inspect, or a plain description of it if #inspect + # is missing or broken. A failure message shouldn't fail itself. + def __inspect__(object) + object.inspect + rescue ::StandardError + ::Kernel.instance_method(:to_s).bind_call(object) + end + + # + COMPARISON_OPERATORS = { :"==" => :"!=" } + + # Message to use when making a comparion assertion. With + # `Assay.color = true`, long values are shown with their differences + # colored. + # + # @param operator [Symbol] operator/method + def compare_message(operator, *args, &blk) + return nil unless COMPARISON_OPERATORS.key?(operator) + a, b = __inspect__(@delegate), __inspect__(args.first) + operator = COMPARISON_OPERATORS[operator] if @negated + if a.size > 13 or b.size > 13 + if defined?($ansi) && $ansi && a.size * b.size <= DIFF_LIMIT + diff = ::ANSI::Diff.new(a,b) + a = diff.diff1 + b = diff.diff2 + end + "a #{operator} b\na) " + a + "\nb) " + b + else + "#{a} #{operator} #{b}" + end + end + + # Puts together a suitable error message. + # + # @param op [Symbol] operator/method + # + # @return [String] message + def generic_message(op, *a, **kw, &b) + inspection = __inspect__(@delegate) + list = a.map { |x| __inspect__(x) } + kw.map { |k, v| "#{k}: #{__inspect__(v)}" } + if @negated + "! #{inspection} #{op} #{list.join(',')}" + else + "#{inspection} #{op} #{list.join(',')}" + end + end + + # @see http://redmine.ruby-lang.org/issues/3768 + def self.const_missing(const) + ::Object.const_get(const) + end + end + +end + +# Copyright (c) 2008 Thomas Sawyer diff --git a/lib/assay/ae/check.rb b/lib/assay/ae/check.rb new file mode 100644 index 0000000..07ce457 --- /dev/null +++ b/lib/assay/ae/check.rb @@ -0,0 +1,154 @@ +require_relative 'assertor' + +module Assay::AE + + # The Ok mixin is a reusable assertion helper that + # makes it easy to construct parameterized assertions + # with an elegant syntax. + # + module Check + + # The Check::Proc class encapsulates a labeled procedure + # for making assertions using the `ok`/`no` methods. + # + class Proc + # Setup new check procedure. + def initialize(options={}, &check) + @name = options[:name] + @message = options[:message] || @name + @check = check + end + + # + def message(&block) + if block + @message = block + end + @message + end + + # + def message=(msg) + @message = msg + end + + # Call check procedure. + def call(*args) + @check.call(*args) + end + + # + def to_s(*args) + case @message + when nil + @name.to_s + when ::Proc + @message.call(*args) + else + # TODO: count %\S and apply `% args.map{|a|a.inspect}[0,count]` + @message.to_s + end + end + + # + def ok!(*args) + check!(args, false, caller) + end + + # + def no!(*args) + check!(args, true, caller) + end + + # Assert the check for the given arguments, negated or not. + # The backtrace says where the failure is reported. + def check!(args, negated, backtrace) + Assertor.assert(call(*args), ::Kernel.proc { to_s(*args) }, negated, backtrace) + end + end + + # TODO: Better way to customize error message so it can have + # arguments in the messages ? + + # Built-in check procedures. + TABLE = { + :equality => Check::Proc.new(:message=>"should be equal"){|h| h.any?{|a,b| b==a}}, + :case_equality => Check::Proc.new(:message=>"should be equal"){|h| h.any?{|a,b| b===a}} + } + + # + def self.table + @table ||= TABLE.dup + end + + # Define a univerally available ok/no check. + # + # Assay::AE::Check.define(:palindrome) do |x| + # x.reverse == x + # end + # + def self.define(name, &block) + table[name] = Check::Proc.new(:name=>name, &block) + end + + # + def check_table + Check.table + end + + # Define an ok/no check procedure. A one-off procedure is defined + # with a block. + # + # check do |x, y| + # x == y + # end + # + # ok 1,1 + # no 1,2 + # + # The check method can also be used to define reusable checks. + # + # check(:palindrome) do |x| + # x.reverse == x + # end + # + # This will also cause the current check to be set. + # Later in the code, the check procedure can be restored + # by just passing the symbolic name. + # + # check :palindrome + # + # ok 'abracarba' + # no 'foolishness' + # + def check(name=nil, &block) + if name + if block + check_table[name] = Check::Proc.new(:name=>name, &block) + end + @__check__ = check_table[name] + else + #raise ArgumentError if block.arity == 0 + @__check__ = Check::Proc.new(&block) + end + end + + # + def ok(*args) + __check__.check!(args, false, caller) + end + + # + def no(*args) + __check__.check!(args, true, caller) + end + + # Returns the current check. + def __check__ + @__check__ || check_table[:equality] + end + + end + +end + diff --git a/lib/assay/ae/core_ext.rb b/lib/assay/ae/core_ext.rb new file mode 100644 index 0000000..cfb3e26 --- /dev/null +++ b/lib/assay/ae/core_ext.rb @@ -0,0 +1,146 @@ +# Query methods the AE notation relies on. Most are also in Ruby Facets. +# Kernel#identical?, #true? and #false? come with Assay itself. + +module Kernel + # Word form of `#==`. Can take a block instead of a value. + def eq?(value=NA) #:yield: + self == (block_given? ? yield : value) + end + + # Word form of `#===`. Can take a block instead of a value. + def case?(value=NA) #:yield: + self === (block_given? ? yield : value) + end + + # Word form of `#=~`. Can take a block instead of a value. An object + # without `#=~` matches nothing, as Object#=~ did before Ruby 3.2. + # + # String, Symbol and Regexp have their own `#match?`. + def match?(value=NA) + value = yield if block_given? + respond_to?(:=~) ? (self =~ value) : nil + end + + # Broad equality: identical, `eql?`, `==` or `===`. + def equate?(x) + equal?(x) || eql?(x) || self == x || self === x + end + + # Can a message be sent to the receiver successfully? Only a missing + # +method+ counts as failure; a NoMethodError raised from inside the + # method is a bug, and is raised as usual. + def send?(method, *args, **kw, &block) + __send__(method, *args, **kw, &block) + true + rescue NoMethodError => error + raise unless error.name == method.to_sym && error.receiver.equal?(self) + false + end +end + +class Object + # Allows `equal?` to take a block. + def equal?(value=NA) #:yield: + block_given? ? super(yield) : super + end + + # Allows `eql?` to take a block. + def eql?(value=NA) #:yield: + block_given? ? super(yield) : super + end +end + +class Numeric + # Is the number within +delta+ of another? + # + # 0.05.in_delta?(50000.0 / 10**6, 0.00001) + # + def in_delta?(orig, delta=0.001) + delta >= (orig - self).abs + end + + # Is the number within +epsilon+ of another, relative to the smaller + # of the two magnitudes? + def in_epsilon?(orig, epsilon=0.001) + in_delta?(orig, [orig.abs, self.abs].min * epsilon) + end +end + +class Module + # Is a given class or module an ancestor of this class or module? + # + # class X ; end + # class Y < X ; end + # + # Y.is?(X) #=> true + # + def is?(base) + Module===base && ancestors.slice(1..-1).include?(base) + end +end + +class Proc + # Does calling the procedure raise the exception, or a kind of it? + def raises?(exception=Exception, *args) + call(*args) + false + rescue exception => error + exception === error + end + + # Does calling the procedure throw +sym+? Throwing another symbol + # counts as no; any error is raised as usual. + def throws?(sym, *args) + catch(sym) do + begin + call(*args) + rescue UncaughtThrowError + end + return false + end + return true + end + + # Does calling the procedure change what the block returns? + def change? + pre_result = yield + call + post_result = yield + pre_result != post_result + end +end + +class Symbol + # Does the block throw this symbol? Throwing another symbol counts + # as no; any error is raised as usual. + def thrown?(*args) + catch(self) do + begin + yield(*args) + rescue UncaughtThrowError + end + return false + end + return true + end +end + +class Exception + # Does the block raise this exception, or a kind of it? + def self.raised? #:yield: + yield + false + rescue self + true + end + + # Was the assertion that raised this exception a negated one? + def negative? + @negative || false + end + + # Set whether the exception came from a negated assertion. + def set_negative(boolean) + @negative = !!boolean + end +end diff --git a/lib/assay/ae/expect.rb b/lib/assay/ae/expect.rb new file mode 100644 index 0000000..45a7716 --- /dev/null +++ b/lib/assay/ae/expect.rb @@ -0,0 +1,72 @@ +require_relative 'assertor' + +module Assay::AE + # = Expect + # + # "When love and skill work together, expect a masterpiece." + # --John Ruskin (1819 - 1900) + # + module Expect + + # The #expect method is a convenient tool for defining + # certain sets of expectations in your specifications. + # + # Expect is used to expect a result from a block of code. + # If the argument to expect is a subclass of Exception + # or instance thereof, then the block is monitored for + # the raising of such an exception. + # + # expect StandardError do + # raise ArgumentError + # end + # + # All other expectations are compared using case equality (#===). + # This allows one to verify matching Regexp. + # + # expect /x/ do + # "x" + # end + # + # As well as checking that an object is an instance of a given Class. + # + # expect String do + # "x" + # end + # + # Like #assert it can be used to designate an expectation + # via a *functor*. + # + # 4.expect == 3 + # + def expect(*args, &block) + Assertor.new(self, :backtrace=>caller).expect(*args, &block) + end + + # Designate a negated expectation. Read this as "expect not". + # + # See #expect. + # + def expect!(*args, &block) + Assertor.new(self, :backtrace=>caller).not.expect(*args, &block) + end + + # Alias for #expect! method. + alias_method :forbid, :expect! + + # Like #expect but uses the reciever as the object + # of expectation. + # + # @example + # /x/.expected do + # "oooxooo" + # end + # + def expected(*args, &block) + expect(self, *args, &block) + end + + end + +end + +# Copyright (c) 2008 Thomas Sawyer diff --git a/lib/assay/ae/must.rb b/lib/assay/ae/must.rb new file mode 100644 index 0000000..8f7a013 --- /dev/null +++ b/lib/assay/ae/must.rb @@ -0,0 +1,64 @@ +require_relative 'subjunctive' + +module Assay::AE + # Must + # + # "It is not enough to succeed. Others must fail." + # --Gore Vidal (1925 - ) + # + module Must + # The #must method is functionaly the same as #should. + # + # @example + # 4.must == 3 #=> Assertion Error + # + # @example + # 4.must do |x| + # x == 4 + # end + # + # @return [Assertor] Assertion functor. + def must(*args, &block) + Assertor.new(self, :backtrace=>caller).be(*args, &block) + end + + # Same as 'object.must == other'. + # + # @return [Assertor] Assertion functor. + def must=(cmp) + Assertor.new(self, :backtrace=>caller) == cmp + end + + # Designate a negated expectation via a *functor*. + # Read this as "must not". + # + # @example + # 4.must! == 4 #=> Assertion Error + # + # @return [Assertor] Assertion functor. + def must!(*args, &block) + Assertor.new(self, :backtrace=>caller).not.be(*args, &block) + end + + # TODO: Are these negation methods needed now, since Ruby 1.9 allows for + # redefining `!` as a method? + + # Perhaps not literally the counter-term to *must* (rather *will*), + # but close enough for our purposes, and conveys the appropriate + # semantics. + alias_method :wont, :must! + + # Alias for #must! method. + alias_method :must_not, :must! + + # Alias for #must! method. + alias_method :mustnt, :must! + end + +end + +class ::Object #:nodoc: + include Assay::AE::Must +end + +# Copyright (c) 2008 Thomas Sawyer diff --git a/lib/assay/ae/should.rb b/lib/assay/ae/should.rb new file mode 100644 index 0000000..a2e1aa3 --- /dev/null +++ b/lib/assay/ae/should.rb @@ -0,0 +1,58 @@ +require_relative 'subjunctive' + +module Assay::AE + + # Should + # + # "Always and never are two words you should always + # remember never to use." + # --Wendell Johnson + # + module Should + # Make an assertion in subjunctive tense. + # + # 4.should == 3 #=> Assertion Error + # + # 4.should do |x| + # x == 4 + # end + # + # @return [Assertor] Assertion functor. + def should(*args, &block) + Assertor.new(self, :backtrace=>caller).be(*args, &block) + end + + # Same as 'object.should == other'. + # + # @return [Assertor] Assertion functor. + def should=(cmp) + Assertor.new(self, :backtrace=>caller).assert == cmp + end + + # Designate a negated expectation via a *functor*. + # Read this as "should not". + # + # 4.should! = 4 #=> Assertion Error + # + # @return [Assertor] Assertion functor. + def should!(*args, &block) + Assertor.new(self, :backtrace=>caller).not.be(*args, &block) + end + + # NOTE: It would be nice if their were a single term that + # meant the opposite of should, rather than a two word compound. + + # Alias for #should! method. + alias_method :should_not, :should! + + # Alias for #should! method. + alias_method :shouldnt, :should! + end + +end + +class ::Object #:nodoc: + include Assay::AE::Should +end + +# Copyright (c) 2008 Thomas Sawyer, Rubyworks diff --git a/lib/assay/ae/subjunctive.rb b/lib/assay/ae/subjunctive.rb new file mode 100644 index 0000000..d64db23 --- /dev/null +++ b/lib/assay/ae/subjunctive.rb @@ -0,0 +1,66 @@ +require_relative 'assertor' + +module Assay::AE + + # Subjunctive + # + # Mixin for Assertor that provides additional English-eque verbage + # such as 'be' and 'an'. This makes it easier to create assertor + # methods of subjunctive terms like 'should'. + # + module Subjunctive + + # Like #assert, except if an argument is provided and no block, + # uses #equate? to compare the argument to the receiver. This + # allows for statements of the form: + # + # 5.should.be Numeric + # + def be(*args, &block) + return self if args.empty? && !block + block = args.shift if !block && ::Proc === args.first + if block + pass = block.arity > 0 ? block.call(@delegate) : block.call #@delegate.instance_eval(&block) + msg = args.shift || @message || block.inspect + else + match = args.shift + pass = match.equate?(@delegate) + msg = args.shift || @message || ::Kernel.proc { "#{'! ' if @negated}#{__inspect__(match)} equate? #{__inspect__(@delegate)}" } + end + __assert__(pass, msg) + end + + # Alias of #be. + # + # 5.assert.is Numeric + # + alias_method :is , :be + alias_method :does, :be + + # The indefinite article is like #be, except that it compares a lone argument + # with #case?, rather than #equate? + # + def a(*args, &block) + return self if args.empty? && !block + block = args.shift if !block && ::Proc === args.first + if block + pass = block.arity > 0 ? block.call(@delegate) : block.call #@delegate.instance_eval(&block) + msg = args.shift || @message || block.inspect + else + match = args.shift + pass = (match === @delegate) # case equality + msg = args.shift || @message || ::Kernel.proc { "#{'! ' if @negated}#{__inspect__(match)} === #{__inspect__(@delegate)}" } + end + __assert__(pass, msg, ::CaseAssay) + end + + alias_method :an, :a + end + +end + +class Assay::AE::Assertor + include ::Assay::AE::Subjunctive +end + +# Copyright (c) 2008 Thomas Sawyer diff --git a/lib/assay/fluidity/grammar.rb b/lib/assay/fluidity/grammar.rb index 3362e53..95c3e5c 100644 --- a/lib/assay/fluidity/grammar.rb +++ b/lib/assay/fluidity/grammar.rb @@ -5,7 +5,14 @@ module Assay::Fluidity module Grammar - class Base + # The grammar classes are built on BasicObject, so that a method every + # object has, such as `kind_of?`, `nil?` or `eql?`, makes an assertion + # about the target rather than being answered by the grammar object. + class Base < ::BasicObject + + # BasicObject has a few public methods of its own. Making them private + # sends them through #method_missing like any other. + private :!, :equal?, :instance_eval, :instance_exec def initialize(target, negate=false) @target = target @@ -15,32 +22,42 @@ def initialize(target, negate=false) # Have to override the ususal `#==` method to support this. def ==(other) if @negate - ::EqualAssay.refute!(@target, other, :backtrace=>caller) + ::EqualAssay.refute!(@target, other, :backtrace=>::Kernel.caller) else - ::EqualAssay.assert!(@target, other, :backtrace=>caller) + ::EqualAssay.assert!(@target, other, :backtrace=>::Kernel.caller) end end - #private + # Likewise for `#!=`. + def !=(other) + if @negate + ::UnequalAssay.refute!(@target, other, :backtrace=>::Kernel.caller) + else + ::UnequalAssay.assert!(@target, other, :backtrace=>::Kernel.caller) + end + end - def method_missing(s, *a, &b) + def method_missing(s, *a, **kw, &b) if assay = (::Assertion.by_name(s) || ::Assertion.by_operator(s)) + a << kw unless kw.empty? if @negate - assay.refute!(@target, *a, {:backtrace=>caller}, &b) + assay.refute!(@target, *a, {:backtrace=>::Kernel.caller}, &b) else - assay.assert!(@target, *a, {:backtrace=>caller}, &b) + assay.assert!(@target, *a, {:backtrace=>::Kernel.caller}, &b) end else q = (s.to_s.end_with?('?') ? s : (s.to_s+'?')) if @target.respond_to?(q) - truth = @target.send(q, *a, &b) + truth = @target.__send__(q, *a, **kw, &b) + args = (a.map{ |x| x.inspect } + kw.map{ |k,v| "#{k}: #{v.inspect}" }).join(', ') + call = "#{@target.inspect}.#{q}" + (args.empty? ? '' : "(#{args})") if @negate - ::Kernel.assert(!truth, ::Assertion, "! #{@target.inspect}.#{q}", caller) + ::Kernel.assert(!truth, ::Assertion, "! #{call}", ::Kernel.caller) else - ::Kernel.assert(truth, ::Assertion, "#{@target.inspect}.#{q}", caller) + ::Kernel.assert(truth, ::Assertion, call, ::Kernel.caller) end else - super(s, *a, &b) + super end end end diff --git a/lib/assay/rspec/operatics.rb b/lib/assay/rspec/operatics.rb index 6c46246..89286c6 100644 --- a/lib/assay/rspec/operatics.rb +++ b/lib/assay/rspec/operatics.rb @@ -2,7 +2,10 @@ module Assay::RSpec # Operatics delegates operator based assertions for execpt.rb. # - class Operatics < Object + # It is built on BasicObject, so that a word method such as `kind_of?` + # is an error rather than being answered by this object. + # + class Operatics < ::BasicObject instance_methods.each{ |m| undef_method m if m.to_s =~ /^\W/ } # @@ -26,19 +29,19 @@ def method_missing(op, *a, &b) # def assert!(op, *a, &b) - if assay = Assertion.by_operator(op) - return assay.assert!(@target, *a, {:backtrace=>caller}, &b) + if assay = ::Assertion.by_operator(op) + return assay.assert!(@target, *a, {:backtrace=>::Kernel.caller}, &b) else - ::Kernel.assert(@target.__send__(op, *a, &b), ::Assertion, "#{@target.inspect} #{op} #{a.map{ |x| x.inspect }.join(', ')}", caller) + ::Kernel.assert(@target.__send__(op, *a, &b), ::Assertion, "#{@target.inspect} #{op} #{a.map{ |x| x.inspect }.join(', ')}", ::Kernel.caller) end end # def refute!(op, *a, &b) - if assay = Assertion.by_operator(op) - return assay.refute!(@target, *a, {:backtrace=>caller}, &b) + if assay = ::Assertion.by_operator(op) + return assay.refute!(@target, *a, {:backtrace=>::Kernel.caller}, &b) else - ::Kernel.refute(@target.__send__(op, *a, &b), ::Assertion, "! #{@target.inspect} #{op} #{a.map{ |x| x.inspect }.join(', ')}", caller) + ::Kernel.refute(@target.__send__(op, *a, &b), ::Assertion, "! #{@target.inspect} #{op} #{a.map{ |x| x.inspect }.join(', ')}", ::Kernel.caller) end end