Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 79 lines (49 sloc) 2.9 kb

contracts

A small library to cleanly implement design by contract.

Status: beta

Motivation :

var f = function(a, b) {
    return a + b;
}

var f = f.pre(function(a, b) {
    a.should.be.a("number").and.above(0);
    b.should.be.a("number").and.above(0);
}).post(function(ret, a, b) {
    ret.should.be.equal(a + b);
});

It is recommended you only use contracts as part of unit tests or in development. contracts run at run-time and therefore negatively impact run-time performance.

Examples:

See the examples folder

Documentation:

See the annotated source code

Method invocation:

The contract methods can be invoked in three different ways.

  • f = f.pre(pre_cb);
  • f = contract(f).pre(pre_cb).valueOf();
  • f = contract.pre(pre_cb, f);

contract

options is hash that can be passed various values:

  • "natives" : default is true, if true it will extend Function.prototype

    var contract = require("contract")(options)

contract.pre

pre allows you to assign a pre contract. Here you can assert that the arguments the function is invoked with should pass certain conditions.

The pre contract will be invoked before the function is invoked.

f = contract.pre(function(arg1, arg2, arg3, ...) {
    // assert things about the arguments
}, f)

contract.post

post allows you to assign a post contract. Here you can assert that the return value matches certain conditions.

The post contract will be invoked after the function is invoked

f = contract.post(function(retValue, arg1, arg2, arg3, ...) {
    // assert things about the return value
}, f);

contract.invariant

invariant allows you to assign a invariant contract. Here you can assert that there are no unexpected side effects during the function call.

The invariant contract will be invoked after the function is invoked

o.f = contract.invariant(function(before, arg1, arg2, arg3, ...) {
    // `before` is the state of `this` before the function was called
    // `this` is the current state of `this`
});
Something went wrong with that request. Please try again.