contract-1.4/0000775000076400007640000000000010666144421012305 5ustar terryterrycontract-1.4/PKG-INFO0000664000076400007640000000175610666144421013413 0ustar terryterryMetadata-Version: 1.0 Name: contract Version: 1.4 Summary: Programming by Contract for Python Home-page: http://www.wayforward.net/pycontract/ Author: Terence Way Author-email: terry@wayforward.net License: Artistic; LPGL; Python Software Foundation License Download-URL: http://www.wayforward.net/pycontract/contract-1.4.tar.gz Description: Annotate function docstrings with pre- and post-conditions, and class/module docstrings with invariants, and this automatically checks the contracts while debugging. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Artistic License Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Software Development :: Testing contract-1.4/test/0000775000076400007640000000000010666144421013264 5ustar terryterrycontract-1.4/test/testdbc3.py0000755000076400007640000003034607674703340015366 0ustar terryterry#!/usr/bin/env python """Basic tests for contracts. This tests CHECK_ALL functionality. See testdbc4 (which should be an exact copy of this module) for CHECK_PRECONDITIONS functionality. inv: a % 2 == 0 # a is even """ a = 4 def _fix(): global a a = 2 def _break(): global a a = 3 try: hasobject = not not object except NameError: hasobject = 0 # 1. modinv01 Module invariants are tested on entry and exit to # public functions. # def modinv01(b): """contract test modinv01 >>> modinv01(2) >>> modinv01(3) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3', 6) >>> _fix() >>> modinv01(4) >>> _break() >>> modinv01(6) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3', 6) >>> _fix() """ global a a = b # 2. modinv02 Module invariants aren't tested on private functions. # def _modinv02(b): """contract test modinv02 >>> _modinv02(7) >>> _modinv02(9) >>> modinv01(4) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3', 6) >>> _fix() """ global a a = b # 3. modpre01 Pre-conditions are tested on entry to all functions, # public or private. # def modpre01a(a, b): """contract test modpre01 pre: (a + b) % 2 == 0 >>> modpre01a(2, 8) >>> modpre01a(2, 7) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.modpre01a', 3) """ pass def _modpre01b(a, b): """contract test modpre01 pre: (a + b) % 2 == 0 >>> _modpre01b(2, 8) >>> _modpre01b(2, 7) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3._modpre01b', 3) """ pass # 4. modpst01 Post-conditions are tested on exit from all functions, # public or private. # def modpst01a(a, b): """contract test modpst01 pre: len(b) > 0 pre: isinstance(b, type([])) post: b[0] == a >>> l = [0] >>> l [0] >>> modpst01a(5, l) >>> modpst01a(-2, l) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.modpst01a', 5) """ if a > 0: b[0] = a def _modpst01b(a, b): """contract test modpst01 pre: len(b) > 0 pre: isinstance(b, type([])) post: b[0] == a >>> l = [0] >>> l [0] >>> _modpst01b(5, l) >>> _modpst01b(-2, l) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3._modpst01b', 5) """ if a > 0: b[0] = a class test: """contract test class inv: self.a == 42 """ # 5. clsinv01 Class invariants are tested on entry and exit to almost # all public methods. # # 6. clsinv02 Class invariants aren't tested on private methods. # def clsinv01(self, b): """contract test clsinv01 >>> t = test() >>> t.clsinv01(42) >>> t.a = 41 >>> t.clsinv01(42) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.test', 3) >>> t.clsinv01(43) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.test', 3) >>> t._clsinv02() >>> t._clsinv02(43) >>> t._clsinv02(41) >>> t.clsinv01(42) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.test', 3) >>> t.a = 42 """ self.a = b def _clsinv02(self, b = 42): self.a = b # 7. clsinv03 Class invariants aren't tested on *entry* to __init__. # def __init__(self, b = 42): """Test >>> t = test() >>> t = test(41) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.test', 3) """ self.a = b # 8. clsinv04 Class invariants aren't tested on *exit* from __del__. # # def __del__(self): # """contract test clsinv04 # # 1>>> t = test() # 1>>> del t # 1>>> t = test() # # 1>>> t.a = 41 # 1>>> del t # """ # #del self.a # pass # 9. clspre01 Pre-conditions are tested on entry to all methods, # public or private. # def clspre01a(self, a): """contract test clspre01 pre: a % 2 == 0 >>> t = test() >>> t.clspre01a(10) >>> t.clspre01a(11) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.test.clspre01a', 3) >>> t._clspre01b(10) >>> t._clspre01b(11) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.test._clspre01b', 3) """ pass def _clspre01b(self, a): """contract test clspre01 pre: a % 2 == 0 """ pass # 10. clspst01 Post-conditions are tested on exit from all methods, # public or private. # def clspst01a(self, a, b): """contract test clspst01 pre: len(b) == 1 post: b[0] == a >>> l = [0] >>> t = test() >>> t.clspst01a(10, l) >>> t.clspst01a(11, l) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.test.clspst01a', 4) >>> t._clspst01b(10, l) >>> t._clspst01b(11, l) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.test._clspst01b', 4) """ if a % 2 == 0: b[0] = a def _clspst01b(self, a, b): """contract test clspst01 pre: len(b) == 1 post: b[0] == a """ if a % 2 == 0: b[0] = a # 11. clsinv05 Invariants for a class include invariants on all super- # classes. # class clsinv05a_base: """contract test clsinv05 inv: self.a == 42 """ def __init__(self): self.a = 42 class clsinv05a_derived(clsinv05a_base): """contract test clsinv05 inv: self.b == 49 >>> d = clsinv05a_derived() >>> d.oops() Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.clsinv05a_base', 3) """ def __init__(self): clsinv05a_base.__init__(self) self.b = 49 def oops(self): self.a = 43 def _fix(self): self.a = 42 self.b = 49 if hasobject: class clsinv05b_base(object): """contract test clsinv05 inv: self.a == 42 """ def __init__(self): self.a = 42 class clsinv05b_derived(clsinv05b_base): """contract test clsinv05 inv: self.b == 49 >>> d = clsinv05b_derived() >>> d.oops() Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.clsinv05b_base', 3) """ def __init__(self): clsinv05b_base.__init__(self) self.b = 49 def oops(self): self.a = 43 def _fix(self): self.a = 42 self.b = 49 # 12. clspre02 Pre-conditions can only be weakened by overridden # methods. # class clspre02a_base: def foo(self, a): "pre: a % 2 == 0" pass class clspre02a_derived(clspre02a_base): """contract test clspre02 >>> b = clspre02a_base() >>> b.foo(2) >>> b.foo(4) >>> b.foo(5) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.clspre02a_base.foo', 1) >>> d = clspre02a_derived() >>> d.foo(2) >>> d.foo(4) >>> d.foo(5) >>> d.foo(-2) Traceback (most recent call last): ... InvalidPreconditionError: ('testdbc3.clspre02a_derived.foo', 1) >>> d.foo(-3) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.clspre02a_base.foo', 1) """ def foo(self, a): "pre: a > 0" pass if hasobject: class clspre02b_base(object): def foo(self, a): "pre: a % 2 == 0" pass class clspre02b_derived(clspre02b_base): """contract test clspre02 >>> b = clspre02b_base() >>> b.foo(2) >>> b.foo(4) >>> b.foo(5) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.clspre02b_base.foo', 1) >>> d = clspre02b_derived() >>> d.foo(2) >>> d.foo(4) >>> d.foo(5) >>> d.foo(-2) Traceback (most recent call last): ... InvalidPreconditionError: ('testdbc3.clspre02b_derived.foo', 1) >>> d.foo(-3) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc3.clspre02b_base.foo', 1) """ def foo(self, a): "pre: a > 0" # 13. clspst02 Post-conditions can be strengthened by overridden # methods. # class clspst02a_base: def foo(self, a, b): """contract test clspst02 post: __return__ % 2 == 0 """ return a * b class clspst02a_derived(clspst02a_base): def foo(self, a, b): """contract test clspst02 post: __return__ % 3 == 0 >>> b = clspst02a_base() >>> b.foo(2, 3) 6 >>> b.foo(2, 1) 2 >>> b.foo(1, 3) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.clspst02a_base.foo', 3) >>> d = clspst02a_derived() >>> d.foo(2, 3) 6 >>> d.foo(2, 1) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.clspst02a_derived.foo', 3) >>> d.foo(1, 3) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.clspst02a_base.foo', 3) """ return a * b if hasobject: class clspst02b_base(object): def foo(self, a, b): """contract test clspst02 post: __return__ % 2 == 0 """ return a * b class clspst02b_derived(clspst02b_base): def foo(self, a, b): """contract test clspst02 post: __return__ % 3 == 0 >>> b = clspst02b_base() >>> b.foo(2, 3) 6 >>> b.foo(2, 1) 2 >>> b.foo(1, 3) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.clspst02b_base.foo', 3) >>> d = clspst02b_derived() >>> d.foo(2, 3) 6 >>> d.foo(2, 1) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.clspst02b_derived.foo', 3) >>> d.foo(1, 3) Traceback (most recent call last): ... PostconditionViolationError: ('testdbc3.clspst02b_base.foo', 3) """ return a * b # 14. clsinv06 class invariants AREN'T tested on constructor exception # class clsinv06a: """Test class invariants. inv:: self.a == 5 >>> i = clsinv06a(5) >>> i = clsinv06a(7) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.clsinv06a', 3) >>> i = clsinv06a(4) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero """ def __init__(self, a): 1 / (a % 2) self.a = a if hasobject: class clsinv06b(object): """Test class invariants. inv:: self.a == 5 >>> i = clsinv06b(5) >>> i = clsinv06b(7) Traceback (most recent call last): ... InvariantViolationError: ('testdbc3.clsinv06b', 3) >>> i = clsinv06b(4) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero """ def __init__(self, a): 1 / (a % 2) self.a = a __test__ = { '_modinv02': _modinv02, '_modpre01b': _modpre01b, '_modpst01b': _modpst01b } def _test(): import contract, doctest, testdbc3 contract.checkmod(testdbc3, contract.CHECK_ALL) return doctest.testmod(testdbc3) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/testdbc7.py0000755000076400007640000000144610422550645015362 0ustar terryterry#!/usr/bin/env python """ >>> c = Checked() >>> c.method() Traceback (most recent call last): ... PostconditionViolationError: ('testdbc7.ToughBase.method', 3) >>> u = Unchecked() >>> u.method() Traceback (most recent call last): ... PostconditionViolationError: ('testdbc7.ToughBase.method', 3) """ class ToughBase: def method(self): """ pre: False post: False """ pass class Checked(ToughBase): def method(self): """pre: True post: True """ return 1 class Unchecked(ToughBase): def method(self): return 1 def _test(): import contract, doctest, testdbc7 contract.checkmod(testdbc7) return doctest.testmod(testdbc7) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/testdbc9d.py0000755000076400007640000000204410630432460015516 0ustar terryterry#!/usr/bin/env python """ Tests tightening preconditions... which should fail with an InvalidPreconditionError >>> b = Base() >>> b.method(10) 90 >>> d = Derived() >>> d.method(20) 200 >>> d.method(10) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc9d.Derived.method', 6) """ from testdbc9b import Base class Derived(Base): def method(self, a): """We cannot tighten preconditions, we must only be able to loosen them. Otherwise, abstract classes cannot work. The client thinks they're calling with a particular contract and Surprise! it doesn't work now. pre: a > 10 """ return a * 10 def _test(): import contract, doctest, testdbc9d contract.checkmod(testdbc9d, contract.CHECK_ALL) return doctest.testmod(testdbc9d) if __name__ == '__main__': t = _test() if t[0]: print "test: %d/%d failures" % t else: print "test: %d successes" % t[1] b = Base() b.method(10) b.method(6) d = Derived() d.method(20) d.method(10) contract-1.4/test/testdbc6.py0000755000076400007640000000114607674666700015375 0ustar terryterry#!/usr/bin/env python """Thanks Dickon Reed... beta 1 broke with itpl Example:: >>> c = C() >>> print c.foo() 2 2 This should work, and not bang out with an exception """ from itpl import itpl import contract class C: def __init__(self, x=2): self.x = x def foo(self): return itpl('$self.x $self.x') def _test(): import contract, doctest, testdbc6 contract.checkmod(testdbc6) return doctest.testmod(testdbc6) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/itpl.py0000644000076400007640000001547607667007231014625 0ustar terryterry"""String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000). This module lets you quickly and conveniently interpolate values into strings (in the flavour of Perl or Tcl, but with less extraneous punctuation). You get a bit more power than in the other languages, because this module allows subscripting, slicing, function calls, attribute lookup, or arbitrary expressions. Variables and expressions are evaluated in the namespace of the caller. The itpl() function returns the result of interpolating a string, and printpl() prints out an interpolated string. Here are some examples: from Itpl import printpl printpl("Here is a $string.") printpl("Here is a $module.member.") printpl("Here is an $object.member.") printpl("Here is a $functioncall(with, arguments).") printpl("Here is an ${arbitrary + expression}.") printpl("Here is an $array[3] member.") printpl("Here is a $dictionary['member'].") The filter() function filters a file object so that output through it is interpolated. This lets you produce the illusion that Python knows how to do interpolation: import Itpl sys.stdout = Itpl.filter() f = "fancy" print "Isn't this $f?" print "Standard output has been replaced with a $sys.stdout object." sys.stdout = Itpl.unfilter() print "Okay, back $to $normal." Under the hood, the Itpl class represents a string that knows how to interpolate values. An instance of the class parses the string once upon initialization; the evaluation and substitution can then be done each time the instance is evaluated with str(instance). For example: from Itpl import Itpl s = Itpl("Here is $foo.") foo = 5 print str(s) foo = "bar" print str(s) """ import sys, string from types import StringType from tokenize import tokenprog class ItplError(ValueError): def __init__(self, text, pos): self.text = text self.pos = pos def __str__(self): return "unfinished expression in %s at char %d" % ( repr(self.text), self.pos) def matchorfail(text, pos): match = tokenprog.match(text, pos) if match is None: raise ItplError(text, pos) return match, match.end() class Itpl: """Class representing a string with interpolation abilities. Upon creation, an instance works out what parts of the format string are literal and what parts need to be evaluated. The evaluation and substitution happens in the namespace of the caller when str(instance) is called.""" def __init__(self, format): """The single argument to this constructor is a format string. The format string is parsed according to the following rules: 1. A dollar sign and a name, possibly followed by any of: - an open-paren, and anything up to the matching paren - an open-bracket, and anything up to the matching bracket - a period and a name any number of times, is evaluated as a Python expression. 2. A dollar sign immediately followed by an open-brace, and anything up to the matching close-brace, is evaluated as a Python expression. 3. Outside of the expressions described in the above two rules, two dollar signs in a row give you one literal dollar sign.""" if type(format) != StringType: raise TypeError, "needs string initializer" self.format = format namechars = "abcdefghijklmnopqrstuvwxyz" \ "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; chunks = [] pos = 0 while 1: dollar = string.find(format, "$", pos) if dollar < 0: break nextchar = format[dollar+1] if nextchar == "{": chunks.append((0, format[pos:dollar])) pos, level = dollar+2, 1 while level: match, pos = matchorfail(format, pos) tstart, tend = match.regs[3] token = format[tstart:tend] if token == "{": level = level+1 elif token == "}": level = level-1 chunks.append((1, format[dollar+2:pos-1])) elif nextchar in namechars: chunks.append((0, format[pos:dollar])) match, pos = matchorfail(format, dollar+1) while pos < len(format): if format[pos] == "." and \ pos+1 < len(format) and format[pos+1] in namechars: match, pos = matchorfail(format, pos+1) elif format[pos] in "([": pos, level = pos+1, 1 while level: match, pos = matchorfail(format, pos) tstart, tend = match.regs[3] token = format[tstart:tend] if token[0] in "([": level = level+1 elif token[0] in ")]": level = level-1 else: break chunks.append((1, format[dollar+1:pos])) else: chunks.append((0, format[pos:dollar+1])) pos = dollar + 1 + (nextchar == "$") if pos < len(format): chunks.append((0, format[pos:])) self.chunks = chunks def __repr__(self): return "" def __str__(self): """Evaluate and substitute the appropriate parts of the string.""" try: 1/0 except: frame = sys.exc_traceback.tb_frame while frame.f_globals["__name__"] == __name__: frame = frame.f_back loc, glob = frame.f_locals, frame.f_globals result = [] for live, chunk in self.chunks: if live: result.append(str(eval(chunk, loc, glob))) else: result.append(chunk) return string.join(result, "") def itpl(text): return str(Itpl(text)) def printpl(text): print itpl(text) class ItplFile: """A file object that filters each write() through an interpolator.""" def __init__(self, file): self.file = file def __repr__(self): return "" def __getattr__(self, attr): return getattr(self.file, attr) def write(self, text): self.file.write(str(Itpl(text))) def filter(file=sys.stdout): """Return an ItplFile that filters writes to the given file object. 'file = filter(file)' replaces 'file' with a filtered object that has a write() method. When called with no argument, this creates a filter to sys.stdout.""" return ItplFile(file) def unfilter(ifile=None): """Return the original file that corresponds to the given ItplFile. 'file = unfilter(file)' undoes the effect of 'file = filter(file)'. 'sys.stdout = unfilter()' undoes the effect of 'sys.stdout = filter()'.""" return ifile and ifile.file or sys.stdout.file contract-1.4/test/testdbc4.py0000755000076400007640000002614207675220510015360 0ustar terryterry#!/usr/bin/env python """Basic tests for contracts. This tests CHECK_PRECONDITIONS functionality. See testdbc3 (which should be an exact copy of this module) for CHECK_ALL functionality. inv: a % 2 == 0 # a is even """ a = 4 def _fix(): global a a = 2 def _break(): global a a = 3 try: hasobject = not not object except NameError: hasobject = 0 # 1. modinv01 Module invariants are tested on entry and exit to # public functions. # def modinv01(b): """contract test modinv01 >>> modinv01(2) >>> modinv01(3) >>> modinv01(3) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4', 6) >>> _fix() >>> modinv01(4) >>> _break() >>> modinv01(6) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4', 6) >>> _fix() """ global a a = b # 2. modinv02 Module invariants aren't tested on private functions. # def _modinv02(b): """contract test modinv02 >>> _modinv02(7) >>> _modinv02(9) >>> modinv01(4) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4', 6) >>> _fix() """ global a a = b # 3. modpre01 Pre-conditions are tested on entry to all functions, # public or private. # def modpre01a(a, b): """contract test modpre01 pre: (a + b) % 2 == 0 >>> modpre01a(2, 8) >>> modpre01a(2, 7) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.modpre01a', 3) """ pass def _modpre01b(a, b): """contract test modpre01 pre: (a + b) % 2 == 0 >>> _modpre01b(2, 8) >>> _modpre01b(2, 7) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4._modpre01b', 3) """ pass # 4. modpst01 Post-conditions are tested on exit from all functions, # public or private. # def modpst01a(a, b): """contract test modpst01 pre: len(b) > 0 pre: isinstance(b, type([])) post: b[0] == a >>> l = [0] >>> l [0] >>> modpst01a(5, l) >>> modpst01a(-2, l) """ if a > 0: b[0] = a def _modpst01b(a, b): """contract test modpst01 pre: len(b) > 0 pre: isinstance(b, type([])) post: b[0] == a >>> l = [0] >>> l [0] >>> _modpst01b(5, l) >>> _modpst01b(-2, l) """ if a > 0: b[0] = a class test: """contract test class inv: self.a == 42 """ # 5. clsinv01 Class invariants are tested on entry and exit to almost # all public methods. # # 6. clsinv02 Class invariants aren't tested on private methods. # def clsinv01(self, b): """contract test clsinv01 >>> t = test() >>> t.clsinv01(42) >>> t.a = 41 >>> t.clsinv01(42) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.test', 3) >>> t.clsinv01(43) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.test', 3) >>> t._clsinv02() >>> t._clsinv02(43) >>> t._clsinv02(41) >>> t.clsinv01(42) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.test', 3) >>> t.a = 42 """ self.a = b def _clsinv02(self, b = 42): self.a = b # 7. clsinv03 Class invariants aren't tested on *entry* to __init__. # def __init__(self, b = 42): """Test >>> t = test() >>> t = test(41) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.test', 3) """ self.a = b # 8. clsinv04 Class invariants aren't tested on *exit* from __del__. # # def __del__(self): # """contract test clsinv04 # # 1>>> t = test() # 1>>> del t # 1>>> t = test() # # 1>>> t.a = 41 # 1>>> del t # """ # #del self.a # pass # 9. clspre01 Pre-conditions are tested on entry to all methods, # public or private. # def clspre01a(self, a): """contract test clspre01 pre: a % 2 == 0 >>> t = test() >>> t.clspre01a(10) >>> t.clspre01a(11) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.test.clspre01a', 3) >>> t._clspre01b(10) >>> t._clspre01b(11) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.test._clspre01b', 3) """ pass def _clspre01b(self, a): """contract test clspre01 pre: a % 2 == 0 """ pass # 10. clspst01 Post-conditions are tested on exit from all methods, # public or private. # def clspst01a(self, a, b): """contract test clspst01 pre: len(b) == 1 post: b[0] == a >>> l = [0] >>> t = test() >>> t.clspst01a(10, l) >>> t.clspst01a(11, l) >>> t._clspst01b(10, l) >>> t._clspst01b(11, l) """ if a % 2 == 0: b[0] = a def _clspst01b(self, a, b): """contract test clspst01 pre: len(b) == 1 post: b[0] == a """ if a % 2 == 0: b[0] = a # 11. clsinv05 Invariants for a class include invariants on all super- # classes. # class clsinv05a_base: """contract test clsinv05 inv: self.a == 42 """ def __init__(self): self.a = 42 class clsinv05a_derived(clsinv05a_base): """contract test clsinv05 inv: self.b == 49 >>> d = clsinv05a_derived() >>> d.oops() >>> d.oops() Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.clsinv05a_base', 3) """ def __init__(self): clsinv05a_base.__init__(self) self.b = 49 def oops(self): self.a = 43 def _fix(self): self.a = 42 self.b = 49 if hasobject: class clsinv05b_base(object): """contract test clsinv05 inv: self.a == 42 """ def __init__(self): self.a = 42 class clsinv05b_derived(clsinv05b_base): """contract test clsinv05 inv: self.b == 49 >>> d = clsinv05b_derived() >>> d.oops() >>> d.oops() Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.clsinv05b_base', 3) """ def __init__(self): clsinv05b_base.__init__(self) self.b = 49 def oops(self): self.a = 43 def _fix(self): self.a = 42 self.b = 49 # 12. clspre02 Pre-conditions can only be weakened by overridden # methods. # class clspre02a_base: def foo(self, a): "pre: a % 2 == 0" pass class clspre02a_derived(clspre02a_base): """contract test clspre02 >>> b = clspre02a_base() >>> b.foo(2) >>> b.foo(4) >>> b.foo(5) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.clspre02a_base.foo', 1) >>> d = clspre02a_derived() >>> d.foo(2) >>> d.foo(4) >>> d.foo(5) >>> d.foo(-2) Traceback (most recent call last): ... InvalidPreconditionError: ('testdbc4.clspre02a_derived.foo', 1) >>> d.foo(-3) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.clspre02a_base.foo', 1) """ def foo(self, a): "pre: a > 0" pass if hasobject: class clspre02b_base(object): def foo(self, a): "pre: a % 2 == 0" pass class clspre02b_derived(clspre02b_base): """contract test clspre02 >>> b = clspre02b_base() >>> b.foo(2) >>> b.foo(4) >>> b.foo(5) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.clspre02b_base.foo', 1) >>> d = clspre02b_derived() >>> d.foo(2) >>> d.foo(4) >>> d.foo(5) >>> d.foo(-2) Traceback (most recent call last): ... InvalidPreconditionError: ('testdbc4.clspre02b_derived.foo', 1) >>> d.foo(-3) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc4.clspre02b_base.foo', 1) """ def foo(self, a): "pre: a > 0" # 13. clspst02 Post-conditions can be strengthened by overridden # methods. # class clspst02a_base: def foo(self, a, b): """contract test clspst02 post: __return__ % 2 == 0 """ return a * b class clspst02a_derived(clspst02a_base): def foo(self, a, b): """contract test clspst02 post: __return__ % 3 == 0 >>> b = clspst02a_base() >>> b.foo(2, 3) 6 >>> b.foo(2, 1) 2 >>> b.foo(1, 3) 3 >>> d = clspst02a_derived() >>> d.foo(2, 3) 6 >>> d.foo(2, 1) 2 >>> d.foo(1, 3) 3 """ return a * b if hasobject: class clspst02b_base(object): def foo(self, a, b): """contract test clspst02 post: __return__ % 2 == 0 """ return a * b class clspst02b_derived(clspst02b_base): def foo(self, a, b): """contract test clspst02 post: __return__ % 3 == 0 >>> b = clspst02b_base() >>> b.foo(2, 3) 6 >>> b.foo(2, 1) 2 >>> b.foo(1, 3) 3 >>> d = clspst02b_derived() >>> d.foo(2, 3) 6 >>> d.foo(2, 1) 2 >>> d.foo(1, 3) 3 """ return a * b # 14. clsinv06 class invariants AREN'T tested on constructor exception # class clsinv06a: """Test class invariants. inv:: self.a == 5 >>> i = clsinv06a(5) >>> i = clsinv06a(7) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.clsinv06a', 3) >>> i = clsinv06a(4) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero """ def __init__(self, a): 1 / (a % 2) self.a = a if hasobject: class clsinv06b(object): """Test class invariants. inv:: self.a == 5 >>> i = clsinv06b(5) >>> i = clsinv06b(7) Traceback (most recent call last): ... InvariantViolationError: ('testdbc4.clsinv06b', 3) >>> i = clsinv06b(4) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero """ def __init__(self, a): 1 / (a % 2) self.a = a __test__ = { '_modinv02': _modinv02, '_modpre01b': _modpre01b, '_modpst01b': _modpst01b } def _test(): import contract, doctest, testdbc4 contract.checkmod(testdbc4, contract.CHECK_PRECONDITIONS) return doctest.testmod(testdbc4) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/testdbc5.py0000755000076400007640000000354507674666701015402 0ustar terryterry#!/usr/bin/env python # Tests various ways of specifying docstring contracts # contract is at beginning of docstring # contract is at end of docstring # multi-line # single line # ReST # comments in middle of expression # line continuations """Test contract docstring parsing >>> strs(parse_docstring(test1, CODE_CONTRACTS)) [['a > 5', 'b < 6'], ['d > 7', 'e < 8']] >>> strs(parse_docstring(test2, CODE_CONTRACTS)) [['a > 5', 'b < 6'], ['d > 7', 'e < 8']] >>> strs(parse_docstring(test3, CODE_CONTRACTS)) [['a > 5', 'b < 6'], ['d > 7', 'e < 8']] >>> strs(parse_docstring(test4, CODE_CONTRACTS)) [['a > 5', 'b < 6'], ['d > 7', 'e < 8']] >>> strs(parse_docstring(test5, CODE_CONTRACTS)) [['a > 5', 'b < 6'], ['d > 7', 'e < 8']] >>> strs(parse_docstring(test6, CODE_CONTRACTS)) [['state in [ test1 , test2 , test3 , test4 ]'], ['True']] """ from contract import parse_docstring, CODE_CONTRACTS def strs(contracts): """Filter out everything except contract expressions from a docstring. """ return [[b[0] for b in a[2]] for a in contracts] test1 = """Silly function. pre: a > 5 b < 6 post[]: d > 7 e < 8 That is all. """ test2 = """pre: a > 5 b < 6 post[]: d > 7 e < 8 That is all. """ test3 = """pre: a > 5 b < 6 post[]: d > 7 e < 8""" test4 = """pre: a > 5 pre: b < 6 post[]: d > 7 post[]: e < 8""" test5 = """Sample function. pre:: # Eiffel-style pre-conditions a > \ 5 # more comments #comments b < 6 post[]: d > 7 e < 8 """ test6 = """Another function. pre:: state in [test1, test2, # comment test3, test4] post[]: True """ def _test(): import doctest, testdbc5 return doctest.testmod(testdbc5) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/testdbca.py0000775000076400007640000000204210666136700015431 0ustar terryterry#!/usr/bin/env python """ Tests undefined preconditions on superclasses. >>> b = B() >>> b.method(4) 4 >>> b.method(6) Traceback (most recent call last): ... PreconditionViolationError: ('testdbca.B.method', 3) >>> d1 = D1() >>> d1.method(4) 8 >>> d1.method(6) Traceback (most recent call last): ... PreconditionViolationError: ('testdbca.B.method', 3) >>> d2 = D2() >>> d2.method(4) 12 >>> d2.method(6) 18 """ G = 5 class B: def method(self, a): """Contracts pre: a < 5 post: a <= G """ global G G = a return a class D1(B): def method(self, a): """ pre: a < 6 B.method.__assert_pre(self, a) """ global G G = a * 2 return a * 2 class D2(B): def method(self, a): global G G = a * 3 return a * 3 def _test(): import contract, doctest, testdbca contract.checkmod(testdbca) return doctest.testmod(testdbca) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/testdbc2.py0000755000076400007640000000136007674702370015361 0ustar terryterry#!/usr/bin/env python """Test inner/outer classes >>> outer.a 5 >>> o = outer() >>> o.a, o.b (5, 6) >>> o.foo() 5 5 6 """ class outer: a = 5 def __init__(self): self.b = 6 def foo(self): print outer.a, self.a, self.b class inner: """test inner classes. inv: self.c == 7 """ c = 7 def __init__(self): self.d = 8 def foo(self): print outer.a, self.c, self.d def _test(): import contract, doctest, testdbc2 contract.checkmod(testdbc2) return doctest.testmod(testdbc2) if __name__ == '__main__': t = _test() if t[0] == 0: print "test: %d tests succeeded" % t[1] else: print "test: %d/%d tests failed" % t contract-1.4/test/testdbc1.py0000755000076400007640000000732307674666702015375 0ustar terryterry#!/usr/bin/env python """Test namespace resolution. >>> a 5 >>> base.b 6 >>> b0 = base() >>> b0.foo() 5 6 7 Hello! >>> d0 = derived() >>> d0.foo() 5 6 8 7 Guten tag! # to test ':' vs '::' we alternate inv:: a == 5 base.b == 6 derived.b == 8 >>> t1() # public functions can break the invariant Traceback (most recent call last): ... InvariantViolationError: ('testdbc1', 16) >>> _fix() # repair >>> _t1() # private functions don't test invariant >>> _fix() >>> t2(5) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc1.t2', 3) >>> t2(4) Traceback (most recent call last): ... InvariantViolationError: ('testdbc1', 16) >>> _fix() >>> base.dingle(2, 4) 8 >>> base.dingle(-1, 2) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc1.base.dingle', 3) """ a = 5 # examples from the PEP START, CONNECTING, CONNECTED, CLOSING, CLOSED = range(5) class conn: """A network connection inv: self.state in [START, CLOSED, # closed states CONNECTING, CLOSING, # transition states CONNECTED] inv:: 0 <= self.seqno < 256 """ def __init__(self): """Create a connection post: self.state == START and self.seqno == 0 """ self.state = START self.seqno = 0 def send(self, msg): """Send a message. pre:: self.state == CONNECTED post[self.seqno]: self.seqno == (__old__.self.seqno + 1) % 256 """ self.seqno = (self.seqno + 1) % 256 class base: """Test base class. inv:: base.b == 6 self.c == 7 """ b = 6 def __init__(self): """Create a base object. post: self.c == 7 """ self.c = 7 def foo(self): """Foo. pre:: a == 5 and base.b == 6 and self.c == 7 """ print a, base.b, self.c, "Hello!" def impfoo(self): self.foo() def expfoo(self): base.foo(self) def dingle(x, y): """Test static method. pre: x > 0 and y > 0 post:: __return__ == x * y """ return x * y dingle = staticmethod(dingle) class derived(base): b = 8 def foo(self): print a, base.b, derived.b, self.c, "Guten tag!" # even functions without docstrings get invariant checking # def t1(): global a a = 4 # but not private functions def _t1(): global a a = 4 def _fix(): global a a = 5 def t2(arg): """test: should fail pre:: arg != 5 post[a]: a == arg """ global a a = arg def defargs(a, (b, c, d), e = 5, f = 6, *va, **ka): """Test default arguments, keyword arguments, etc. pre:: e >= 5 f <= 6 type(va) == type( () ) type(ka) == type({}) >>> defargs(1, (2, 3, 4)) >>> defargs(3, (4, 5, 6), 7, 4) >>> defargs('', ('', '', ''), 4) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc1.defargs', 4) >>> defargs([], ('42', {}, None), 5, 7) Traceback (most recent call last): ... PreconditionViolationError: ('testdbc1.defargs', 5) >>> defargs(1, (2, 3, 4), foo='bar') """ pass def defargs2(a, fn = int): """Test pre-evaluated default arguments. pre: fn(a) or not fn(a) # just see if function works post:: __return__ == 0 or __return__ == 1 >>> defargs2('42') 0 >>> defargs2('0') 1 """ return not fn(a) def _test(): import contract, doctest, testdbc1 contract.checkmod(testdbc1, contract.CHECK_ALL) return doctest.testmod(testdbc1) if __name__ == '__main__': t = _test() if t[0]: print "test: %d/%d failures" % t else: print "test: %d successes" % t[1] contract-1.4/test/testdbc9b.py0000755000076400007640000000057110630431540015515 0ustar terryterry#!/usr/bin/env python """Tests Ruben Reifenberg's invalid precondition bug. The idea here is that a base class does not have any contract checking, but a base class tightens the (non-existing) preconditions. The full test is in testdbc9d.py """ class Base(object): def method(self, a): """Loose precondition pre: a > 5 """ return a * 9 contract-1.4/test/testdbc8.py0000755000076400007640000000102010422633035015342 0ustar terryterry#!/usr/bin/env python """ Test class-private variables. >>> f = Foo() >>> f.__attr Traceback (most recent call last): ... AttributeError: Foo instance has no attribute '__attr' """ class Foo: """inv: self._Foo__attr > 0""" def __init__(self): self.__attr = 1 def _test(): import contract, doctest, testdbc8 contract.checkmod(testdbc8) return doctest.testmod(testdbc8) if __name__ == '__main__': t = _test() if t[0]: print "test: %d/%d failures" % t else: print "test: %d successes" % t[1] contract-1.4/examples/0000775000076400007640000000000010666144421014123 5ustar terryterrycontract-1.4/examples/sort.py0000644000076400007640000000210207672414102015454 0ustar terryterrydef sort(a): """Sort a list *IN PLACE*. >>> a = [1, 1, 1, 1, 1, 2, 2, 1] >>> sort(a) >>> a [1, 1, 1, 1, 1, 1, 2, 2] >>> a = 'the quick brown fox jumped over the lazy dog'.split() >>> sort(a) >>> a ['brown', 'dog', 'fox', 'jumped', 'lazy', 'over', 'quick', 'the', 'the'] pre: # must be a list isinstance(a, list) # all elements must be comparable with all other items forall(range(len(a)), lambda i: forall(range(len(a)), lambda j: (a[i] < a[j]) ^ (a[i] >= a[j]))) post[a]: # length of array is unchanged len(a) == len(__old__.a) # all elements given are still in the array forall(__old__.a, lambda e: __old__.a.count(e) == a.count(e)) # the array is sorted forall([a[i] >= a[i-1] for i in range(1, len(a))]) """ a.sort() # enable contract checking import contract contract.checkmod(__name__) def _test(): import doctest, sort return doctest.testmod(sort) if __name__ == "__main__": _test() contract-1.4/examples/circbuf.py0000644000076400007640000000600707672413715016123 0ustar terryterryclass circbuf: """A circular buffer of Python values. Examples:: >>> cb = circbuf(3) >>> cb.is_empty() 1 >>> cb.put('first') >>> cb.is_empty() 0 >>> cb.put('second') >>> cb.put('third') >>> cb.is_full() 1 >>> cb.put('fourth') >>> cb.get() 'second' >>> cb.get() 'third' >>> cb.get() 'fourth' >>> cb.is_empty() 1 inv:: # there can be from 0 to max items inclusive on the buffer 0 <= self.len <= len(self.buf) # g is a valid index into buf 0 <= self.g < len(self.buf) # p is also a valid index into buf 0 <= self.p < len(self.buf) # there are len items between get and put (self.p - self.g) % len(self.buf) == self.len % len(self.buf) """ def __init__(self, leng): """Construct an empty circular buffer. pre:: leng > 0 post[self]:: self.is_empty() and len(self.buf) == leng """ self.buf = [None for x in range(leng)] self.len = self.g = self.p = 0 def is_empty(self): """Returns true only if circbuf has no items. post[]:: __return__ == (self.len == 0) """ return self.len == 0 def is_full(self): """Returns true only if circbuf has no space. post[]:: __return__ == (self.len == len(self.buf)) """ return self.len == len(self.buf) def get(self): """Retrieves an item from a non-empty circular buffer. pre:: not self.is_empty() post[self.len, self.g]:: self.len == __old__.self.len - 1 __return__ == self.buf[__old__.self.g] """ result = self.buf[self.g] self.g = (self.g + 1) % len(self.buf) self.len -= 1 return result def put(self, item): """Puts an item onto a circular buffer. post[self.len, self.p, self.g, self.buf]:: # if the circbuf was full on entry, then an entry # was bumped implies(__old__.self.len == len(self.buf), self.len == __old__.self.len, self.len == __old__.self.len + 1 and \ self.g == __old__.self.g) # item is now in the buffer self.buf[__old__.self.p] == item # but no other part of the buffer has changed self.buf[:__old__.self.p] == __old__.self.buf[:__old__.self.p] self.buf[__old__.self.p+1:] == __old__.self.buf[__old__.self.p+1:] __return__ is None """ self.buf[self.p] = item self.p = (self.p + 1) % len(self.buf) if self.len == len(self.buf): self.g = self.p else: self.len += 1 # enable contract checking import contract contract.checkmod(__name__) def _test(): import doctest, circbuf return doctest.testmod(circbuf) if __name__ == '__main__': _test() contract-1.4/COPYING0000664000076400007640000010451310666137474013356 0ustar terryterry GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . contract-1.4/README0000644000076400007640000000501507670156477013203 0ustar terryterryContract Pre-conditions, post-conditions, and invariants for Python code. Quick Start =========== Installation ------------ After unpacking the source distribution, install this in your site- specific Python extension directory:: python setup.py build [sudo] python setup.py install Document your code with contracts --------------------------------- Docstrings for modules and classes can have inv: statements, docstrings for functions and methods can have pre: and post: statements. Example:: class test: """Test class. inv: 0 <= self.len < 512 """ def pop(self, a): """Remove element. pre: self.len > 0 post[self.len]: self.len == __old__.self.len - 1 """ Enable Contract Checking ------------------------ To enable run-time checking of the contracts, use the contract.checkmod function. For example, at the very end of mymodule.py:: import contract, mymodule contract.checkmod(mymodule) Description =========== Contract enforces high-level assertions placed in docstrings. Modules and classes can have invariants: expressions that must be true on entry and exit to public functions. Methods and functions can have pre-conditions, which must be true on entry; and post-conditions, which must be true on exit. Example:: def mid(a, b): """The midpoint between two numbers. pre: operator.isNumberType(a) operator.isNumberType(b) post: __return__ == a/2 + b/2 """ return (a + b) / 2 When Python is running in non-optimized mode (with no -O command line argument) and the module has had contract checking enabled, the two expressions 'operator.isNumberType(a)' and 'operator.isNumberType(b)' are tested every time the mid function is called. These are pre-conditions. If either expression isn't true, an assertion is raised. The expression '__return__ == a/b + b/2' is tested after the function returns. If this expression is false, an assertion is raised. When Python is running in optimized mode, the checks are disabled. To enable contract checking, use the contract.checkmod function. Example:: if __name__ == '__main__': import contract, doctest, mid contract.checkmod(mid) # <-- doctest.testmod(mid) For more information, please see the Python Contract specification pep-0316.txt License: Python Software Foundation License Terence Way terry@wayforward.net http://www.wayforward.net/pycontract/ contract-1.4/contract.py0000644000076400007640000013766010666144414014511 0ustar terryterry#!/usr/bin/env python """Programming-by-contract for Python, based on Eiffel's DBC. Programming by contract documents class and modules with invariants, expressions that must be true during the lifetime of a module or instance; and documents functions and methods with pre- and post- conditions that must be true during entry and return. Copyright (c) 2003, 2006, 2007 Terence Way This program is free software; you can redistribute it and/or modify it under the terms of either: a) GNU Library or Lesser General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version, or b) Python Software Foundation License You may redistribute and/or modify this program under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form, or c) The "Artistic License" which comes with this Kit. You should have received a copy of the Artistic License with this Kit, in the file named "Artistic". If not, I'll be glad to provide one. You should also have received a copy of the GNU Lesser General Public License along with this program in the files named "COPYING" and "COPYING.LESSER". If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307, USA or visit their web page on the internet at http://www.gnu.org/copyleft/lgpl.html. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. """ # Changes: # ttw001 2003-05-26 # Jeff Epler points out we should have separate assertion exception # base class ContractViolationError, then exception classes # PreconditionViolationError, PostconditionViolationError, and # InvariantViolationError inheriting from ContractViolationError. # # ttw002 2003-05-26 # Support restructured text by allowing double colon (::) in # addition to single colon (:) after 'pre' 'inv' 'post' or # post variable declarations. # # ttw003 2003-05-29 # Dickon Reed discovers problem: invariants mustn't be checked after # a constructor throws an exception. # # ttw004 2003-06-02 # Make sure that objects returned in _get_members only include # things defined by that module # # ttw005 2003-06-02 # Save line number information in parse_docstring, _read_block, to # be trapped if a TokenError or ParseError occurs, and to pass along # to any contract exceptions raised. # # ttw006 2003-06-06 # The _read_block internal function past the last line of a docstring # contract. This saves some hackery in parse_docstring, and makes # _read_block more useful for external tools. # # ttw007 2003-06-06 # Phillip Eby points out that OR-ed pre-conditions are worse than # useless. So instead of OR-ing pre-conditions of a method with all # overridden methods, we check if a pre-condition fails whether *any* # overridden pre-condition would succeed, if so we raise an # InvalidPreconditionError # # ttw008 2003-06-13 # Support partial contract enforcement: check preconditions only. # add flag to checkmod to specify checklevel: CHECK_NONE, # CHECK_PRECONDITIONS, or CHECK_ALL # # ttw009 2003-06-13 # String module names can be passed into checkmod as well. # # ttw010 2003-06-20 # Python 2.2.1 has bool, True, False but Python 2.2 doesn't. To # support built-in Python on Mac OS X, define local bool() if not # defined globally # # ttw011 2003-06-21 # Support Jython (Python 2.1). Refactored the tokenize logic in # _read_block() to support older tokenize.tokenize(), backtracked # some 2.2 conveniences (like 'x in {dict}'). # # ttw012 2005-10-19 # From Gintautas Miliauskas: # "I discovered one problem though: you expect __import__(modname) to # return the corresponding module, however, it does not work like # that. For example, if you invoke __import__('a.b.c.d'), the result # will be module , not module . Yes, I think this is dumb too, # but that's how it works. A workaround is to use __import__ to # import the module and then get the actual module from sys.modules." # # ttw013 2006-04-22 # From Aaron Bingham: # "The subclass's method defines no new pre- or postconditions; the # script testunchecked.py thus exits normally, even though the # superclass's contract is violated!" # # All methods need to have checking code installed, even if there # are not any conditions in the method docstring, because the # super-class may have conditions. # # A method without any docstring conditions is implicitly declaring # "pre: True" # # rr001 2007-06-02 # From Ruben Reifenberg # "There is some behaviour in contract.py that might be a bug. # It happened that line 1300 re-raised the AttributeError from 1292 # although a PreconditionVioloation was going on. Changing 1300 to: # 1300: raise args # solved the problem" # # ab001 2007-08-31 # From Aaron Bingham # "Fix handling of constructor preconditions. # # Subclass constructors' parameter lists may be legitimately completely # different from the superclass constructor's parameter list. Thus, for # constructors we only evaluate preconditions of the current class's # constructor and do not follow the mro. See Meyer, Object Oriented # Software Construction, 2nd Edition, p. 466." # # ttw015 2007-08-31 # Avoid building a list of methods for preconditions. # # ttw016 2007-08-31 # All installed checker functions return True, so they can be used # in contracts, ex: "pre: Base.method.__assert_pre(self, a, b)" # __author__ = "Terence Way" __email__ = "terry@wayforward.net" __version__ = "1.4: August 31, 2007" MODULE = 'contract' import new import re import sys import tokenize from cStringIO import StringIO from types import * # Programming-by-contract extends the language to include invariant # expressions for classes, and pre-condition and post-condition # expressions for methods. These are very similar to assertions, # expressions which must be true or the program is stopped. # # Class invariants are expressions which must be true at the end of a # class's constructor, and at the beginning and end of each public # method. # # Pre-conditions must be true at the start of each method. Post- # conditions must be true at the end of each method. Post-condition # logic has access to an 'old' variable which records variable values # before they were changed by the method. # # This implementation tries to fix what I consider a defect in # Eiffel's DBC -- while it is easy to specify what does change after # invoking a method, it is impossible to specify what doesn't change. # This makes it hard to reason about methods, and limits portability # to more formal techniques such as Z. # # A simple fix is to declare what parts change. Simply modify the # line 'post:' to 'post [a]:' to declare that the variable a is the # only thing changed by the sort function. This is modelled after Z # schemas [2]. # # Simply saying 'post:' means anything can be changed: this is the # original semantics of the Eiffel ENSURES statement. Saying 'post # []:' means nothing is changed. # # Python Specifications # --------------------- # The docstring of any module or class can have invariants documented # by having the keyword 'inv' followed by a colon (:) at the start of # a line. Whitespace is ignored. This is either followed by a single # expression on the same line, or a series of expressions on following # lines indented past the 'post' key- word. The normal Python rules # about implicit and explicit line continuations are followed here. # # To support Re-structured text, two colons (::) after the keyword is # supported. # # Module invariants must be true at module load time, and at the entry # and return of every public function within the module. # # Class invariants must be true after the __init__ function returns, # and at the entry and return of every public method of the class. # # The docstring of any function or method can have pre-conditions # documented with the keyword 'pre' following the same rules above, # and can have post-conditions documented with the keyword 'post' # optionally followed by a list of variables. The variables are in # the same scope as the body of the function or method. # # Expressions have access to some additional convenience values. To # make evaluating sequences easier, there are two functions: forall(a) # and exists(a). To make implication easier, there is a # implies(x,a,b=True) function which mirrors C's conditional # expression (x?a:c). # # The expressions in the post-conditions have access to two additional # variables, __old__ which is filled with variables declared in the # 'post' statement bound to shallow copies before the function or # method is called; and __return__ which is bound to the return value # of the function or method. # # Implementation # -------------- # This module is divided into four parts: # # 1 -- Find docstrings and parse them for contract expressions... # # This is accomplished by: # a. recursive enumerating elements in modules, classes using code # lifted from the 'inspect' Python standard module # see: checkmod, _check # b. scanning the docstrings of public functions with a regular # expression looking for lines that matches 'pre:' 'post:' or # 'inv:' at the start # see: parse_docstring # c. Using the 'tokenize' Python tokenizer to build expressions # see: _read_block, _read_decl, _read_token # # 2 -- Construct functions that do contract checking... # This is done by just constructing big strings that are function # definitions. Each function or method gets associated with four # 'helper' functions... to check pre-conditions, to save old # values, to check post-conditions, and of course the saved # original code. These are stored as function attributes. # see: _install_wrapper, _define_checker # # 3 -- Run-time support for call checking # see: call_public_function_*, call_private_function_*, # call_public_method_*, call_private_method_*, # call_constructor_*, call_destructor_* # # 4 -- Declarations for use within contract expressions # includes 'forall' 'exists' 'implies' and exception classes # change the keywords here, if necessary INV = 'inv' PRE = 'pre' POST = 'post' TYPE_CONTRACTS = [INV] CODE_CONTRACTS = [PRE, POST] OLD = '__old__' RETURN = '__return__' PREFIX = '__assert_' # enumeration to pass to checkmod: how extensive checking should be CHECK_DEFAULT, CHECK_NONE, CHECK_PRECONDITIONS, CHECK_ALL = range(4) _ORIG = 'orig' _SAVE = 'save' _CHK = 'chk' _CONTRACTS = tuple(TYPE_CONTRACTS + CODE_CONTRACTS) # look for word+ [expr] space* ':' at the start of a line # _re_start = re.compile(r'^\s*(%s|%s|%s)\s*(\[|:)' % _CONTRACTS, re.MULTILINE) _RE_KEYWORD = 1 # the tokenizer only seems to return OP(50) for any operators like : [ ] . , # we need to do a further lookup to get the operator value, but only for the # tokens we care about # _OPS = {':': tokenize.COLON, '[': tokenize.LSQB, ']': tokenize.RSQB, '.': tokenize.DOT, ',': tokenize.COMMA} _EXCEPTIONS = {PRE: 'PreconditionViolationError', POST: 'PostconditionViolationError', INV: 'InvariantViolationError'} # ttw010 support pre 2.2.1... try: bool, True, False = bool, True, False except NameError: False, True = 0, 1 def bool(x): return not not x # ...ttw010 ############################################################################### # Part 1 -- Find docstrings and parse them for contract expressions... # def checkmod(module, checklevel = CHECK_DEFAULT): """Add invariant, pre- and post-condition checking to a module. pre:: isstring(module) or isinstance(module, ModuleType) checklevel in [CHECK_DEFAULT, CHECK_NONE, CHECK_PRECONDITIONS, CHECK_ALL] """ # ttw009 string module names... if isinstance(module, StringType) or isinstance(module, UnicodeType): # ttw012 imports... __import__(module) module = sys.modules[module] # ...ttw012 # ...ttw009 # ttw008 partial contract enforcement... if checklevel == CHECK_DEFAULT: if __debug__: checklevel = CHECK_ALL else: checklevel = CHECK_PRECONDITIONS # ...ttw008 if checklevel != CHECK_NONE: # get members *before* we start adding stuff to this module path = [module] members = _get_members(module, path) invs = parse_docstring(module.__doc__, TYPE_CONTRACTS)[0] name = PREFIX + INV func = getattr(module, name, None) # should we override if not func or func.__name__.startswith(PREFIX): if invs[2]: func = _define_checker(name, '', invs, path) else: func = __assert_inv module.__assert_inv = func _check_members(members, path, checklevel) # check module invariants now func() def _check_type(code, path, checklevel): """Modify a class to add invariant checking. pre:: isstring(code[0]) type(code[1]) == code[2] isinstance(code[0], MethodType) or isinstance(code[0], FunctionType) isinstance(path[0], ModuleType) forall(path[1:], isclass) """ name, obj = code # get members *before* we start adding stuff to this class path = path + [obj] members = _get_members(obj, path) invs = parse_docstring(obj.__doc__, TYPE_CONTRACTS)[0] if invs[2]: func = _define_checker(_mkname(path, INV), 'self', invs, path) setattr(obj, PREFIX + INV, func) delattr(path[0], func.func_name) _check_members(members, path, checklevel) def _check_proc(code, path, checklevel): """Modify a module or class to add invariant checking. """ name, obj = code _install_wrapper(code, parse_docstring(obj.__doc__, CODE_CONTRACTS), path, is_public = _ispublic(name), checklevel = checklevel) def _get_location(f): """Get function location as tuple (name, filename, lineno). pre:: isinstance(f, MethodType) or isinstance(f, FunctionType) post[]:: isstring(__return__[0]) isstring(__return__[1]) isinstance(__return__[2], int) """ if isinstance(f, MethodType): f = f.im_func c = f.func_code return f.func_name, c.co_filename, c.co_firstlineno def _get_members(obj, path): """Returns two lists (procs, types) where each list contains (name, value) tuples. For classes, only attributes defined by the specific class are returned, i.e. not inherited attributes. Attributes created by this module (prefixed by '__assert_') are skipped as well. Examples: >>> import contract >>> path = [contract] >>> hasattr(contract, '_re_start') 1 >>> '_re_start' in [x[0] for x in _get_members(contract, path)[0]] 0 >>> '_get_members' in [x[0] for x in _get_members(contract, path)[0]] 1 >>> 'checkmod' in [x[0] for x in _get_members(contract, path)[0]] 1 >>> class base: ... def foo(self): pass >>> class derived(base): ... def bar(self): pass hasattr can get inherited attributes: >>> hasattr(derived, 'foo') 1 but we don't: >>> path = [__import__('__main__')] >>> 'foo' in [x[0] for x in _get_members(derived, path)[0]] 0 """ module_name = path[0].__name__ module_dict = path[0].__dict__ parent = path[-1] procs = [] types = [] for key in obj.__dict__.keys(): if not key.startswith(PREFIX): m = getattr(obj, key) # ttw004 only objects that belong to this module... if (isinstance(m, MethodType) and m.im_class is parent) or \ (isinstance(m, FunctionType) and \ m.func_globals is module_dict): procs.append((key, m)) elif isclass(m) and getattr(m, '__module__', None) is module_name: types.append((key, m)) # ...ttw004 return (procs, types) def _check_members((procs, types), path, checklevel): for p in procs: _check_proc(p, path, checklevel) for t in types: _check_type(t, path, checklevel) def _ispublic(name): """Checks if a name is public (starts and ends with '__' or doesn't start with a _ at all). Examples: >>> _ispublic('__init__') 1 >>> _ispublic('foo') 1 >>> _ispublic('_ispublic') 0 """ return not name.startswith('_') or \ (name.startswith('__') and name.endswith('__')) def parse_docstring(docstring, keywords): """Parse a docstring, looking for design-by-contract expressions. Returns a list of tuples: the list is the same length as keywords, and matches each keyword. The tuple is (keyword, [decls], [exprs]), namely the keyword, a list of string declarations, and a list of tuples (string, lineno). Examples:: >>> from pprint import pprint >>> pprint( parse_docstring(parse_docstring.__doc__, ['post', 'pre']) ) [('post', [], [('[ x [ 0 ] for x in __return__ ] == keywords', 22)]), ('pre', [], [('docstring is None or isstring ( docstring )', 18), ('forall ( keywords , isstring )', 19)])] pre:: docstring is None or isstring(docstring) forall(keywords, isstring) post[]:: [x[0] for x in __return__] == keywords """ result = [(x, [], []) for x in keywords] if docstring is None: return result # step 1: scan through docstring looking for keyword input = StringIO(docstring) offset = 0 assert input.tell() == 0 line = input.readline() lineno = 0 # zero-origined because tokenizer keeps 1-origined while line != '': a = _re_start.split(line) if len(a) > _RE_KEYWORD and a[_RE_KEYWORD] in keywords: # step 2: found a keyword, now rewind and scan looking # for either an inline expression or a series of sub- # indented expressions input.seek(offset) # ttw005... get lineno info and add to exception's lineno # if a TokenError occurs... try: l = _read_block(input, lineno) lineno = l[3] # returns (keyword, decls, exprs, lineno) except tokenize.TokenError, ex: # reformat to include new line info raise tokenize.TokenError(ex[0], (lineno + ex[1][0],) + ex[1][1:]) # ...ttw005 # Find the right result index based on keyword r = result[keywords.index(l[0])] r[1].extend(l[1]) r[2].extend(l[2]) else: lineno += 1 if offset == input.tell(): break offset = input.tell() line = input.readline() return result # ttw011 refactor tokenize parser to use older tokenize.tokenize()... # # [INDENT] NAME # [LSQB (NAME (DOT NAME)* (COMMA NAME (DOT NAME)*)*)* RSQB] # COLON [COLON] # (NEWLINE INDENT (not DEDENT)*) | (not NEWLINE)* class Done(Exception): pass class tokenizer: def __init__(self, input, startlineno): self.input = input self.startlineno = startlineno self.endlineno = self.lineno = startlineno + 1 self.state = self.start self.decl, self.decls, self.expr, self.exprs = [], [], [], [] self.keyword, self.offset = '', input.tell() def next(self, token, string, start, end, line): if token != tokenize.COMMENT and token != tokenize.NL: if token == tokenize.OP and _OPS.has_key(string): token = _OPS[string] self.state(token, string) if token == tokenize.NEWLINE or token == tokenize.NL: self.lineno = self.startlineno + start[0] + 1 # all following methods are states in the state machine. # the self.state variable indicates which function/state we're in def start(self, token, string): if token == tokenize.INDENT: self.state = self.indent else: self.indent(token, string) def indent(self, token, string): if token == tokenize.NAME: self.keyword = string self.state = self.name else: raise SyntaxError("expected pre, post, or inv") def name(self, token, string): if token == tokenize.LSQB: self.state = self.decl0 else: self.colon(token, string) def decl0(self, token, string): if token == tokenize.NAME: self.decl.append(string) self.state = self.decl1 elif token == tokenize.RSQB: self.state = self.colon else: raise SyntaxError("expected variable name or ]") def decl1(self, token, string): if token == tokenize.DOT: self.state = self.decln elif token == tokenize.COMMA: self.decls.append(self.decl) self.decl = [] self.state = self.decln elif token == tokenize.RSQB: self.decls.append(self.decl) self.state = self.colon else: raise SyntaxError("expected one of (,.])") def decln(self, token, string): if token == tokenize.NAME: self.decl.append(string) self.state = self.decl1 else: raise SyntaxError("expected name") def colon(self, token, string): if token == tokenize.COLON: self.state = self.colon1 else: raise SyntaxError("expected colon(:)") def colon1(self, token, string): if token == tokenize.COLON: self.state = self.colon2 else: self.colon2(token, string) def colon2(self, token, string): if token == tokenize.NEWLINE: self.state = self.newline else: self.endtoken = tokenize.NEWLINE self.state = self.rest self.rest(token, string) def newline(self, token, string): if token == tokenize.INDENT: self.endtoken = tokenize.DEDENT self.state = self.rest else: raise IndentationError("expected an indented block") def rest(self, token, string): if token == self.endtoken or token == tokenize.ENDMARKER: if self.expr: self.exprs.append( (' '.join(self.expr), self.lineno) ) raise Done() self.offset, self.endlineno = self.input.tell(), self.lineno if token == tokenize.NEWLINE: self.exprs.append( (' '.join(self.expr), self.lineno) ) self.expr = [] else: self.expr.append(string) def _read_block(input, startlineno): r"""Read an indented block of expressions startlineno is *zero* origined line number. pre:: input.readline # must have readline function Examples: #>>> _read_block(StringIO('\tfoo:\n'), 0) #0 >>> _read_block(StringIO('\tpost[]: True\n'), 0) ('post', [], [('True', 1)], 1) >>> _read_block(StringIO('\tpre: 5 + 6 > 10\n'), 0) ('pre', [], [('5 + 6 > 10', 1)], 1) >>> _read_block(StringIO('\tpost:\n\t\t5 + 6 < 12\n\t\t2 + 2 == 4\n'), 0) ('post', [], [('5 + 6 < 12', 2), ('2 + 2 == 4', 3)], 3) >>> _read_block(StringIO('\tpost[foo.bar]: # changes\n' \ ... '\t\tlen(foo.bar) > 0\n'), 0) ('post', [['foo', 'bar']], [('len ( foo . bar ) > 0', 2)], 2) Handles double colons (for re-structured text):: >>> _read_block(StringIO('\tpre:: 5 + 6 > 10\n'), 0) ('pre', [], [('5 + 6 > 10', 1)], 1) """ t = tokenizer(input, startlineno) try: tokenize.tokenize(input.readline, t.next) except Done: pass input.seek(t.offset) return (t.keyword, t.decls, t.exprs, t.endlineno) # ...ttw011 # ...part 1 ############################################################################### ############################################################################### # Part 2 -- Construct functions that do contract checking... # def _install_wrapper(code, contracts, path, is_public, checklevel): """Creates and installs a function/method checker. pre:: contracts[0][0] == PRE and contracts[1][0] == POST isinstance(path[0], ModuleType) forall(path[1:], isclass) """ name, obj = code newpath = path + [obj] ismethod = isinstance(obj, MethodType) if ismethod: func = obj.im_func invs = hasattr(path[-1], PREFIX + INV) else: func = obj invs = hasattr(path[0], PREFIX + INV) # we must create a checker if: # 1. there are any pre-conditions or any post-conditions OR # 2. this is public AND there are invariants # ttw013... # 3. this is a method call, to check any super-class method # conditions # ...ttw003 if ismethod or contracts[0][2] or contracts[1][2] or (is_public and invs): argspec = getargspec(func) args = _format_args(argspec) # argl: argument list suitable for appending at the end of other args if args: argl = ', ' + args else: argl = args output = StringIO() output.write('def %s(%s):\n' % (_mkname(path, name, _CHK), args)) output.write('\timport %s\n' % MODULE) classname = '.'.join([c.__name__ for c in path[1:]]) if isinstance(obj, FunctionType): if is_public: chkname, chkargs = 'call_public_function', '__assert_inv, ' else: chkname, chkargs = 'call_private_function', '' else: if not is_public: chkname = 'call_private_method' elif name == '__init__': chkname = 'call_constructor' elif name == '__del__': chkname = 'call_destructor' else: chkname = 'call_public_method' chkargs = classname + ', ' # ttw008 partial contract enforcement... if checklevel == CHECK_ALL: suffix = '_all' else: suffix = '_pre' # ...ttw008 output.write('\treturn %s.%s%s(%s' % (MODULE, chkname, suffix, chkargs)) if classname: output.write(classname) output.write('.') output.write(name) output.write(argl) output.write(')\n') newfunc = _define(_mkname(path, name, _CHK), output.getvalue(), path[0]) # if there are default arguments if argspec[3]: # install the default arguments... don't try to put them into # our printed function definition, above, as they have already # been evaluated. newfunc = new.function(newfunc.func_code, newfunc.func_globals, newfunc.func_name, argspec[3]) setattr(newfunc, PREFIX + _ORIG, getattr(func, PREFIX + _ORIG, func)) # write preconditions checker if contracts[0][2]: pre = _define_checker(_mkname(path, name, contracts[0][0]), args, contracts[0], newpath) delattr(path[0], pre.func_name) setattr(newfunc, PREFIX + contracts[0][0], pre) if checklevel == CHECK_ALL: # write __old__ saver if contracts[1][1]: saver = _define_saver(_mkname(path, name, _SAVE), OLD + argl, contracts[1][1], path[0]) delattr(path[0], saver.func_name) setattr(newfunc, PREFIX + _SAVE, saver) # write postconditions checker if contracts[1][2]: post = _define_checker(_mkname(path, name, contracts[1][0]), OLD + ', ' + RETURN + argl, contracts[1], newpath) delattr(path[0], post.func_name) setattr(newfunc, PREFIX + contracts[1][0], post) newname = newfunc.func_name newfunc.__doc__ = obj.__doc__ if isclass(path[-1]) and isinstance(obj, FunctionType): # static method newfunc = staticmethod(newfunc) setattr(path[-1], name, newfunc) if name != newname or len(path) > 1: delattr(path[0], newname) # end _install_wrapper def isclass(obj): return isinstance(obj, TypeType) or isinstance(obj, ClassType) def isstring(obj): return isinstance(obj, StringType) or isinstance(obj, UnicodeType) def _define_checker(name, args, contract, path): """Define a function that does contract assertion checking. args is a string argument declaration (ex: 'a, b, c = 1, *va, **ka') contract is an element of the contracts list returned by parse_docstring module is the containing module (not parent class) Returns the newly-defined function. pre:: isstring(name) isstring(args) contract[0] in _CONTRACTS len(contract[2]) > 0 post:: isinstance(__return__, FunctionType) __return__.__name__ == name """ output = StringIO() output.write('def %s(%s):\n' % (name, args)) # ttw001... raise new exception classes ex = _EXCEPTIONS.get(contract[0], 'ContractViolationError') output.write('\tfrom %s import forall, exists, implies, %s\n' % \ (MODULE, ex)) loc = '.'.join([x.__name__ for x in path]) for c in contract[2]: output.write('\tif not (') output.write(c[0]) output.write('): raise %s("%s", %u)\n' % (ex, loc, c[1])) # ...ttw001 # ttw016: return True for superclasses to use in preconditions output.write('\treturn True') # ...ttw016 return _define(name, output.getvalue(), path[0]) def _define_saver(name, args, decls, module): """Create a function that saves values into an __old__ variable. pre:: decls post:: isinstance(__return__, FunctionType) """ output = StringIO() output.write('def %s(%s):\n' % (name, args)) output.write('\timport %s, copy\n' % MODULE) _save_decls(output, '', _decltodict(decls)) return _define(name, output.getvalue(), module) def _define(name, text, module): #print text exec text in vars(module) return getattr(module, name) def _format_args( (arguments, rest, keywords, default_values) ): """Formats an argument desc into a string suitable for both a function/ method declaration or a function call. This does *not* handle default arguments. Default arguments are already evaluated... use new.function() to create a function with pre-evaluated default arguments. Examples: >>> def foo(a, (b, c), d = 1, e = 2, *va, **ka): ... pass >>> a = getargspec(foo) >>> a (['a', '(b, c)', 'd', 'e'], 'va', 'ka', (1, 2)) >>> _format_args(a) 'a, (b, c), d, e, *va, **ka' pre:: isinstance(arguments, list) rest is None or isstring(rest) keywords is None or isstring(keywords) post[]:: True """ if rest is not None: arguments = arguments + ['*' + rest] if keywords is not None: arguments = arguments + ['**' + keywords] return ', '.join(arguments) CO_VARARGS, CO_VARKEYWORDS = 4, 8 try: import inspect def _format_arg(a): """Convert an argument list into a tuple string. >>> _format_arg(['a', 'b', 'c']) '(a, b, c)' >>> _format_arg(['a', ['b', 'c', 'd']]) '(a, (b, c, d))' >>> _format_arg(['a']) '(a,)' >>> _format_arg('a') 'a' """ if isinstance(a, ListType): if len(a) == 1: return '(' + _format_arg(a[0]) + ',)' else: return '(' + ', '.join([_format_arg(z) for z in a]) + ')' else: return a def _getargs(function): t = inspect.getargspec(function) return ([_format_arg(a) for a in t[0]], t[1], t[2], t[3]) getmro = inspect.getmro except ImportError: # inspect module not available, on say Jython 2.1 def _getargs(function): code = function.func_code i = code.co_argcount args = list(code.co_varnames[:i]) if code.co_flags & CO_VARARGS: va = code.co_varnames[i] i += 1 else: va = None if code.co_flags & CO_VARKEYWORDS: ka = code.co_varnames[i] i += 1 else: ka = None return (args, va, ka, function.func_defaults) def _searchbases(cls, accum): # Simulate the "classic class" search order. if cls in accum: return accum.append(cls) for base in cls.__bases__: _searchbases(base, accum) def getmro(cls): """Return tuple of base classes (including cls) in method resolution order.""" if hasattr(cls, "__mro__"): return cls.__mro__ else: result = [] _searchbases(cls, result) return tuple(result) def getargspec(function): """Get argument information about a function. Returns a tuple (args, varargs, keywordvarargs, defaults) where args is a list of strings, varargs is None or the name of the *va argument, keywordvarargs is None or the name of the **ka argument, and defaults is a list of default values. This function is different from the Python-provided inspect.getargspec in that 1) tuple arguments are returned as a string grouping '(a, b, c)' instead of broken out "['a', 'b', 'c']" and 2) it works in Jython, which doesn't support inspect (yet). >>> getargspec(lambda a, b: a * b) (['a', 'b'], None, None, None) >>> getargspec(lambda a, (b, c, d) = (5, 6, 7), *va, **ka: a * b) (['a', '(b, c, d)'], 'va', 'ka', ((5, 6, 7),)) pre:: isinstance(function, FunctionType) post[]:: # tuple of form (args, va, ka, defaults) isinstance(__return__, TupleType) and len(__return__) == 4 # args is a list of strings isinstance(__return__[0], ListType) forall(__return__[0], isstring) # va is None or a string __return__[1] is None or isstring(__return__[1]) # ka is None or a string __return__[2] is None or isstring(__return__[2]) # defaults is None or a tuple __return__[3] is None or isinstance(__return__[3], TupleType) """ return _getargs(function) def _mkname(path, *va): """Define a name combining a path and arbitrary strings. pre:: isinstance(path[0], ModuleType) forall(path[1:], isclass) Examples: >>> import contract >>> _mkname([contract], 'test') '__assert_test' >>> class foo: ... pass >>> _mkname([contract, foo], 'func', 'pre') '__assert_foo_func_pre' """ return PREFIX + '_'.join([c.__name__ for c in path[1:]] + list(va)) def _save_decls(output, name, d): """Recursively output a dictionary into a set of 'old' assignments. The dictionary d is a tree of variable declarations. So, for example, the declaration [self, self.buf, self.obj.a] would turn into the dict {'self': {'buf': {}, 'obj': {'a': {}}}}, and would get output as __old__.self = contract._holder() __old__.self.buf = copy.copy(self.buf) __old__.self.obj = contract._holder() __old__.self.obj.a = copy.copy(self.obj.a) """ for k, v in d.items(): n = name + k output.write('\t%s.%s = ' % (OLD, n)) if v == {}: output.write('copy.copy(%s)\n' % n) else: output.write('%s._holder()\n' % MODULE) _save_decls(output, n + '.', v) def _decltodict(l): """Converts a list of list of names into a hierarchy of dictionaries. Examples: >>> d = _decltodict([['self', 'buf'], ... ['self', 'item', 'a'], ... ['self', 'item', 'b']]) >>> d == {'self': {'buf': {}, 'item': {'a': {}, 'b': {}}}} 1 """ result = {} for i in l: d = result for n in i: # n in d ? d[n] : d[n] = {} d = d.setdefault(n, {}) return result # # ...part 2 ############################################################################### ############################################################################### # Part 3... Run-time support for call checking # ##################################### # ttw001 add new assertion classes... class ContractViolationError(AssertionError): pass class PreconditionViolationError(ContractViolationError): pass class PostconditionViolationError(ContractViolationError): pass class InvariantViolationError(ContractViolationError): pass # ...ttw001 ##################################### # ttw006 correctly weaken pre-conditions... class InvalidPreconditionError(ContractViolationError): """Method pre-conditions can only weaken overridden methods' preconditions. """ pass # ...ttw006 # ttw008 partial contract enforcement # these are 'drivers': functions which check contracts and call the # original wrapped functions. Each driver has two variants: one for # CHECK_PRECONDITIONS and one for CHECK_ALL: the CHECK_ALL checks # preconditions and invariants on entry, and postconditions and # invariants on exit. The CHECK_PRECONDITIONS only checks pre- # conditions and invariants on entry. There needs to be a driver # for public and private functions, public and private methods, and # constructors and destructors. Hence: # call_public_function_pre/call_public_function_all # checks module invariants and function pre[post] conditions # call_private_function_pre/call_private_function_all # checks function pre[post] conditions # call_public_method_pre/call_public_method_all # checks class/type invariants and method pre[post] conditions # call_private_method_pre/call_private_method_all # checks method pre[post] conditions # call_constructor_pre/call_constructor_all # checks method pre-conditions [type/class invariants and post- # conditions on exit] # call_destructor_pre/call_destructor_all # checks method pre-conditions and class/type invariants on entry. def call_public_function_all(inv, func, *va, **ka): """Check the invocation of a public function or static method. Checks module invariants on entry and exit. Checks any pre-conditions and post-conditions. """ inv() try: # ttw015: avoid making a list of functions... return _call_one_all(func, va, ka) # ...ttw015 finally: inv() def call_public_function_pre(inv, func, *va, **ka): """Check the invocation of a public function or static method. Checks module invariants on entry. Checks any pre-conditions. """ inv() # ttw015: avoid making a list of functions... return _call_one_pre(func, va, ka) # ...ttw015 def call_private_function_all(func, *va, **ka): """Check the invocation of a private function or static method. Only checks pre-conditions and post-conditions. """ # ttw015: avoid making a list of functions... return _call_one_all(func, va, ka) # ...ttw015 def call_private_function_pre(func, *va, **ka): """Check the invocation of a private function or static method. Only checks pre-conditions """ # ttw015: avoid making a list of functions... return _call_one_pre(func, va, ka) # ...ttw015 def call_public_method_all(cls, method, *va, **ka): """Check the invocation of a public method. Check this class and all super-classes invariants on entry and exit. Checks all post-conditions of this method and all over- ridden method. """ mro = getmro(cls) _check_class_invariants(mro, va[0]) try: return _method_call_all(mro, method, va, ka) finally: _check_class_invariants(mro, va[0]) def call_public_method_pre(cls, method, *va, **ka): """Check the invocation of a public method. Check this class and all super-classes invariants on entry. exit. """ mro = getmro(cls) _check_class_invariants(mro, va[0]) return _method_call_pre(mro, method, va, ka) def call_constructor_all(cls, method, *va, **ka): """Check the invocation of an __init__ constructor. Checks pre-conditions and post-conditions, and only checks invariants on successful completion. """ # ttw003 invariants mustn't be checked if constructor raises exception... # ab001 fix handling of constructor preconditions... # mro = getmro(cls) # result = _method_call_all(mro, method, va, ka) # _check_class_invariants(mro, va[0]) result = _method_call_all([cls], method, va, ka) _check_class_invariants(getmro(cls), va[0]) # ...ab001 return result # ...ttw003 def call_constructor_pre(cls, method, *va, **ka): """Check the invocation of an __init__ constructor. Checks pre-conditions and post-conditions, and only checks invariants on successful completion. """ # ttw003 invariants mustn't be checked if constructor raises exception... # ab001 fix handling of constructor preconditions... # mro = getmro(cls) # result = _method_call_pre(mro, method, va, ka) # _check_class_invariants(mro, va[0]) result = _method_call_pre([cls], method, va, ka) _check_class_invariants(getmro(cls), va[0]) # ...ab001 return result # ...ttw003 def call_destructor_all(cls, method, *va, **ka): """Check the invocation of a __del__ destructor. Checks pre-conditions and post-conditions, and only checks invariants on entry. """ mro = getmro(cls) _check_class_invariants(mro, va[0]) return _method_call_all(mro, method, va, ka) def call_destructor_pre(cls, method, *va, **ka): """Check the invocation of a __del__ destructor. Checks pre-conditions and post-conditions, and only checks invariants on entry. """ mro = getmro(cls) _check_class_invariants(mro, va[0]) return _method_call_pre(mro, method, va, ka) def call_private_method_all(cls, method, *va, **ka): """Check the invocation of a private method call. Checks pre-conditions and post-conditions. """ return _method_call_all(getmro(cls), method, va, ka) def call_private_method_pre(cls, method, *va, **ka): """Check the invocation of a private method call. Checks pre-conditions. """ return _method_call_pre(getmro(cls), method, va, ka) def _check_class_invariants(mro, instance): """Checks class invariants on an instance. mro - list of classes in method-resolution order instance - object to test pre:: # instance must be an instance of each class in mro forall(mro, lambda x: isinstance(instance, x)) """ # ab002: Avoid generating AttributeError exceptions... for c in mro: if hasattr(c, '__assert_inv'): c.__assert_inv(instance) # ...ab002 def _method_call_all(mro, method, va, ka): """Check the invocation of a method. mro -- list/tuple of class objects in method resolution order """ # NO CONTRACTS... recursion assert isinstance(method, MethodType) func = method.im_func name = func.__assert_orig.__name__ # list of all method functions with name a = [getattr(c, name).im_func for c in mro if _has_method(c, name)] return _call_all(a, func, va, ka) def _method_call_pre(mro, method, va, ka): """Check the invocation of a method. mro -- list/tuple of class objects in method resolution order """ # NO CONTRACTS... recursion func = method.im_func name = func.__assert_orig.__name__ # list of all method functions with name a = [getattr(c, name).im_func for c in mro if _has_method(c, name)] return _call_pre(a, func, va, ka) def _call_one_all(func, va, ka): if hasattr(func, '__assert_pre'): func.__assert_pre(*va, **ka) # save old values old = _holder() if hasattr(func, '__assert_save'): func.__assert_save(old, *va, **ka) result = func.__assert_orig(*va, **ka) # check post-conditions if hasattr(func, '__assert_post'): func.__assert_post(old, result, *va, **ka) return result def _call_one_pre(func, va, ka): if hasattr(func, '__assert_pre'): func.__assert_pre(*va, **ka) return func.__assert_orig(*va, **ka) def _call_all(a, func, va, ka): _check_preconditions(a, func, va, ka) # save old values old = _holder() # ab002: Avoid generating AttributeError exceptions... for f in a: if hasattr(f, '__assert_save'): f.__assert_save(old, *va, **ka) result = func.__assert_orig(*va, **ka) for f in a: # check post-conditions if hasattr(f, '__assert_post'): f.__assert_post(old, result, *va, **ka) # ...ab002 return result def _call_pre(a, func, va, ka): _check_preconditions(a, func, va, ka) return func.__assert_orig(*va, **ka) def _check_preconditions(a, func, va, ka): # ttw006: correctly weaken pre-conditions... # ab002: Avoid generating AttributeError exceptions... if hasattr(func, '__assert_pre'): try: func.__assert_pre(*va, **ka) except PreconditionViolationError, args: # if the pre-conditions fail, *all* super-preconditions # must fail too, otherwise for f in a: if f is not func and hasattr(f, '__assert_pre'): f.__assert_pre(*va, **ka) raise InvalidPreconditionError(args) # rr001: raise original PreconditionViolationError, not # inner AttributeError... # raise raise args # ...rr001 # ...ab002 # ...ttw006 def _has_method(cls, name): """Test if a class has a named method. pre:: isclass(cls) isstring(name) post:: __return__ == (hasattr(cls, name) and \ isinstance(getattr(cls, name), MethodType)) """ return isinstance(getattr(cls, name, None), MethodType) def __assert_inv(): """Empty invariant assertions """ pass # ...part 3 ############################################################################### ############################################################################### # Part 4 -- Declarations for use within contract expressions... # def forall(a, fn = bool): """Checks that all elements in a sequence are true. Returns True(1) if all elements are true. Return False(0) otherwise. Examples: >>> forall([True, True, True]) 1 >>> forall( () ) 1 >>> forall([True, True, False, True]) 0 """ for i in a: if not fn(i): return False return True def exists(a, fn = bool): """Checks that at least one element in a sequence is true. Returns True(1) if at least one element is true. Return False(0) otherwise. Examples: >>> exists([False, False, True]) 1 >>> exists([]) 0 >>> exists([False, 0, '', []]) 0 """ for i in a: if fn(i): return True return False def implies(test, then_val, else_val = True): """Logical implication. implies(x, y) should be read 'x implies y' or 'if x then y' implies(x, a, b) should be read 'if x then a else b' Examples: >>> implies(False, False) 1 >>> implies(False, True) 1 >>> implies(True, False) 0 >>> implies(True, True) 1 """ if test: return then_val else: return else_val class _holder: """Placeholder for arbitrary 'old' values. """ pass # # ...part 4 ############################################################################### __test__ = { '_ispublic': _ispublic, '_get_members': _get_members, '_decltodict': _decltodict, '_read_block': _read_block, '_format_args': _format_args, '_mkname': _mkname} if __name__ == '__main__': import doctest, contract #contract.checkmod(contract) doctest.testmod(contract) contract-1.4/COPYING.LESSER0000664000076400007640000001672710666137523014356 0ustar terryterry GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. contract-1.4/Artistic0000664000076400007640000001373310666143350014021 0ustar terryterry The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End contract-1.4/setup.py0000755000076400007640000000215710666136735014036 0ustar terryterry#!/usr/bin/env python from distutils.core import setup NAME = 'contract' VERSION = '1.4' URL = 'http://www.wayforward.net/pycontract/' DESC = """Annotate function docstrings with pre- and post-conditions, and class/module docstrings with invariants, and this automatically checks the contracts while debugging.""" setup(name = NAME, version = VERSION, description = "Programming by Contract for Python", long_description = DESC, author = 'Terence Way', author_email = 'terry@wayforward.net', url = URL, download_url = URL + 'contract-%s.tar.gz' % VERSION, license = 'Artistic; LPGL; Python Software Foundation License', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Artistic License', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'License :: OSI Approved :: Python Software Foundation License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Testing' ], py_modules = ['contract'])