python-aspects-1.3/0000755000175000017500000000000011074124621012452 5ustar askaskpython-aspects-1.3/PKG-INFO0000644000175000017500000000037611074124621013555 0ustar askaskMetadata-Version: 1.0 Name: python-aspects Version: 1.3 Summary: Lightweight AOP extension Home-page: http://www.cs.tut.fi/~ask/aspects/index.html Author: Antti Kervinen Author-email: ask@cs.tut.fi License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN python-aspects-1.3/GNUmakefile0000644000175000017500000000143111074117432014525 0ustar askask.PHONY: help test check clean dist install VERSION = $(shell $(PYTHON) -c "import aspects; print \".\".join(str(s) for s in aspects.version_info)") PYTHON ?= python help: @echo "make check - run unit tests" @echo "make clean - remove unnecessary files" @echo "make dist - create dist/aspects-$(VERSION).tar.gz*" @echo "make install - install to the system's site-packages*" @echo "*) runs $(PYTHON) setup.py" @echo "" @echo "Define Python version with the PYTHON environment variable." @echo "Example: PYTHON=python2.6 make install" check: @for f in test/test_*.py; do \ echo "---- $$f"; \ PYTHONPATH=`pwd` $(PYTHON) $$f || exit $?; \ done dist: $(PYTHON) setup.py sdist install: $(PYTHON) setup.py install clean: $(RM) *.pyc *~ */*.pyc */*~ $(RM) -r build distpython-aspects-1.3/examples/0000755000175000017500000000000011074124621014270 5ustar askaskpython-aspects-1.3/examples/timeout_example.py0000644000175000017500000000157011003174254020045 0ustar askaskimport aspects import timeout_advice import time class Example: def __init__( self ): self.all_waits = 0 def wait( self, time_to_wait, throw_exception = 0 ): myname = "Example.wait("+str(time_to_wait)+","+str(throw_exception)+")" print myname, "falls sleep." time.sleep( time_to_wait ) self.all_waits = self.all_waits + time_to_wait if throw_exception: print "Suddenly", myname, "raises exception" raise myname else: print myname, "wakes up. Total sleep:",self.all_waits return self.all_waits e = Example() adv = timeout_advice.create_timeout_advice( timeout=1.0, catch_exceptions=1 ) aspects.wrap_around( Example.wait, adv ) t = time.time() print e.wait( time_to_wait=1.6, throw_exception=1 ) print e.wait(0.2) print e.wait(0.3) print e.wait(0.4) print time.time()-t python-aspects-1.3/examples/httpget_example.py0000644000175000017500000000116611003174254020037 0ustar askaskimport urllib import aspects import timeout_advice import sys import time if len(sys.argv)<2: print "Usage: httpget URL [URL ...]" aspects.wrap_around( urllib.URLopener.open, timeout_advice.create_timeout_advice(1,1) ) for url in sys.argv[1:]: start_time = time.time() ufile = urllib.urlopen(url) elapsed_time = time.time() - start_time if ufile: print ufile.read() ufile.close sys.stderr.write(url + " arrived in " + str(elapsed_time) + " seconds\n") else: sys.stderr.write(url + " could not be retrieved, tried " + str(elapsed_time) + " seconds\n") python-aspects-1.3/examples/typecheck_advice.py0000644000175000017500000000611611003174254020137 0ustar askask# Copyright (C) 2004-2007 Antti Kervinen # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # Changes: # # -> aspects-0.3, added support for type checking keyword arguments def argtypecheck(self,*args,**kwargs): """Check that the types of the arguments satisfy the specification given in class variable __argtypes. __argtype is a dictionary where method's name is a key to the list of allowed types of arguments of the method. This function should be wrapped around the methods whose argument types are checked.""" method=self.__proceed_stack()[-1].method type_list=self.__argtypes[ method.__name__ ] # Check normal arguments. If the type of an argument is not # spesified in the type_list (there are more arguments than types # for them), any type is allowed. try: for i,arg in enumerate(args): if not True in [isinstance(arg,argt) for argt in type_list[i] ]: raise TypeError("The type of the "+str(i+1)+". argument of "+ self.__proceed_stack[-1].name+ " was "+str(type(arg))+ ". Allowed types are: "+ ", ".join([str(t) for t in type_list[i]])+ ".") except IndexError: pass # there were more arguments than specified types # Check keyword arguments. If the keyword is not mentioned in the # parameter list, or , allow any type. argnames=list(method.func_code.co_varnames[:method.func_code.co_argcount]) for kwarg in kwargs: try: # -1 is because type of the first argument (self) is not # spesified in type_list' kwargnum=argnames.index(kwarg)-1 except ValueError: continue # keyword kwarg does not appear in the argument list # skip type check if there is no type spec for this argument if kwargnum>=len(type_list): continue if not True in [isinstance(kwargs[kwarg],kwargt) for kwargt in type_list[kwargnum]]: raise TypeError( "The type of the keyword argument '"+kwarg+"' was "+ str(type(kwargs[kwarg]))+" when calling "+ self.__proceed_stack[-1].name+ ". Allowed types are: "+ ", ".join([str(t) for t in type_list[kwargnum]])+ ".") return self.__proceed(*args,**kwargs) python-aspects-1.3/examples/timeout_advice.py0000644000175000017500000000450011003174254017641 0ustar askaskfrom thread import start_new_thread, allocate_lock import time class _Thread_return_stop_holder: pass def timeout_2s_catch(self, *args, **keyw): """ This function implements 2 second timeout advice that catches exceptions raised by the thread. The advice equals to the one you get by a = create_timeout_advice( 2.0, 1 ) """ # Initialise tflock that is locked until thread # finishes execution tflock = allocate_lock() tflock.acquire() ret = _Thread_return_stop_holder() ret.value = None def save_retval( ret ): try: ret.value = self.__proceed(*args, **keyw) except: pass tflock.release() start_new_thread( save_retval, (ret,) ) if _wait_timeout( 2.0, tflock ): return None return ret.value _num_of_advices = 0 def create_timeout_advice( timeout = 1.0, catch_exceptions = 1 ): global _num_of_advices _num_of_advices = _num_of_advices + 1 py = "def timeout_advice" + str( _num_of_advices ) + \ "(self, *args, **keyw):\n" + \ " tflock = allocate_lock()\n" + \ " tflock.acquire()\n" + \ " ret = _Thread_return_stop_holder()\n" + \ " ret.value = None\n" + \ " def save_retval( ret ):\n" if catch_exceptions: py = py + " try: ret.value = self.__proceed(*args,**keyw)\n" + \ " except: pass\n" else: py = py + " ret.value = self.__proceed(*args,**keyw)\n" py = py + " tflock.release()\n" + \ " start_new_thread( save_retval, (ret,) )\n" + \ " if _wait_timeout( "+str(timeout)+", tflock):\n" + \ " return None\n" + \ " return ret.value\n" return _create_function( py, "timeout_advice"+str(_num_of_advices) ) def _create_function( function_code, function_name ): # compile code codeobj = compile( function_code, "", "exec" ) # execute code, new function is added to local name space exec( codeobj ) return eval( function_name ) def _wait_timeout( max_time, lock ): """ Return 1 if lock is not released before max_time seconds have elapsed. """ start_time = time.time() while time.time() - start_time < max_time: time.sleep( 0.01 ) if lock.acquire(0): return 0 return 1 python-aspects-1.3/examples/typecheck_example.py0000644000175000017500000000300611003174254020332 0ustar askask# # Copyright (C) 2004 Antti Kervinen # # # Changes: # 2006-05-05 Pedro Emanuel de Castro Faria Salgado # - added a new method (x) # - added examples # # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # from aspects import wrap_around from typecheck_advice import argtypecheck class b: pass class d(b): pass class c: def m(self,integer,string): print "c.m called with",integer,string def n(self,object): print "c.n called with object",object def x(self, arg1, opt1=None, opt2=None): print "c.x called with ", arg1, opt1, opt2 c.__argtypes={ 'm':[[int,long],[str]], 'n':[[b]], 'x':[[int], [int, type(None)], [int, type(None)]] } wrap_around(c.m,argtypecheck) wrap_around(c.n,argtypecheck) wrap_around(c.x,argtypecheck) o=c() o.m(2L,"a") o.n( d() ) o.x(1) o.x(1, 2) o.x(1, 2, 3) o.x(1, opt2=3) python-aspects-1.3/examples/tracer_advice.py0000644000175000017500000000034511003174254017436 0ustar askaskdef tracer_advice( self, *args, **keyw ): stack_entry = self.__proceed_stack()[-1] print "Call:", stack_entry.name, \ "by an instance of", stack_entry.method.im_class return self.__proceed( *args, **keyw ) python-aspects-1.3/examples/tracer_example.py0000644000175000017500000000103711003174254017635 0ustar askaskfrom aspects import wrap_around from tracer_advice import tracer_advice class B1: def foo(self): print "B1.foo" class B2: def foo(self): print "B2.foo" def bar(self): print "B2.bar" class B3: def bar(self): print "B3.bar" class D1(B1,B2): pass class DD1(D1,B3): pass wrap_around( B1.foo, tracer_advice ) wrap_around( B2.foo, tracer_advice ) wrap_around( B2.bar, tracer_advice ) wrap_around( B3.bar, tracer_advice ) wrap_around( DD1.bar, tracer_advice ) o = DD1() o.foo() o.bar() python-aspects-1.3/MANIFEST0000644000175000017500000000052511003176016013602 0ustar askaskaspects.py setup.py LICENSE.txt README.txt INSTALL.txt MANIFEST examples/httpget_example.py examples/timeout_advice.py examples/timeout_example.py examples/tracer_advice.py examples/tracer_example.py examples/typecheck_example.py examples/typecheck_advice.py test/testlib_with_wrap.py test/test_aspects.py test/test_with_wrap.py GNUmakefile python-aspects-1.3/aspects.py0000644000175000017500000006344611074115425014505 0ustar askask# aspects.py - Tools for AOP in Python # Version 1.3 # # Copyright (C) 2003-2008 Antti Kervinen (ask@cs.tut.fi) # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Aspects library allows wrapping and removing wraps on methods and functions. Wraps are functions which are called before the wrapped functions. A wrap may or may not call the wrapped function at some point of their execution. There are two kinds of wraps: new-style and old-style. New-style wraps can be used in Python 2.5 and later, old-style wraps work in Python 2.1 and later. Support for old-style wraps is continued for compatibility reasons, but they will be deprecated when stable Python 2.5 compatible Jython is released. For instance, arbitrary old-style wraps cannot be removed. 1. Wrapping a method or function: new-style: wrap_ids = aspects.with_wrap(new_style_wrap, func1, ...) funcs can be in module-level or in class-level (that is, a method) old-style: wrap_id = aspects.wrap_around(method, old_style_wrap) method cannot be a module-level function In both cases, adding 'instances=[obj1, obj2, ...]' keyword argument causes the wrap to be executed only in the case that it is called through objects obj1, obj2, etc. wrap_around and with_wrap return identifiers for the added wraps (or a list of identifiers if many functions are wrapped at once in with_wrap). The identifiers can be used in enabling and disabling the wrap. There can be a number of wraps on the same function. When it is called, the topmost wrap is executed first and the wrap below is executed when the wrap above tries to call the original function. There can be both old-style and new-style wraps on the same function. 2. Removing a wrap: removed_wrap = aspects.without_wrap(new_style_wrap, method) or removed_wrap = aspects.without_wrap(wrap_id, method) Removed wraps can be rewrapped to the same or other methods. For compatibility, there is the peel_around method for removing the topmost wrap. It should not be used anymore. topmost_wrap = aspects.peel_around(func) 3. Enabling / disabling a wrap: both styles: enable_wrap(func, wrap_id) enables the wrap disable_wrap(func, wrap_id) disables the wrap wrap_is_enabled(func, wrap_id) returns the status Only enabled wraps are executed when the function is called. 4. New-style wraps New-style wraps are generators. Inside a wrap, the original function can be called with the original call arguments: orig_retval = yield aspects.proceed or with new arguments: orig_retval = yield aspects.proceed(args_here) If wanted, the original function can be called many times. Exceptions raised by the original method can be caught in the wrap if the yield statement is inside a try-except block. The wrap passes the original return value by default (if it does not yield anything but aspects.proceed), or by yielding yield aspects.return_stop The return value can be changed by yielding yield aspects.return_stop(value_here) Yielding return_stop with a new return value before the original method is executed causes skipping the execution. If the value is returned by either of the above ways, the execution of the wrap is restarted when the wrapped function is called next time. However, the value can also be returned with return_cont. In that case, the execution of the wrap is not restarted, which results in remarkably faster execution. (args, kw_args) = yield aspects.return_cont returns the original return value, and (args, kw_args) = yield aspects.return_cont(value_here) returns the given value. When the wrapped function is called next time, the call arguments are stored to args and kw_args, and the execution of the wrap is continued from the yield point. The wrap can access the wrapped method by yielding get_wrapped class. wrapped_method = yield get_wrapped """ version_info=(1,3) import re import thread import types import inspect import sys _python_version=sys.version_info[:2] _permission_to_touch_wraps=thread.allocate_lock() class AspectsException(Exception): pass if _python_version < (2,3): class object: pass class proceed(object): """ Yielding a proceed object from a generator advice causes (re)invokation of the wrapped function with the given arguments. """ def __init__(self,*args,**kwargs): self.args=args self.kwargs=kwargs class return_stop(object): """ Yielding a return_stop object from a generator advice causes passing the given argument as a return value to the caller of the wrapped function. """ def __init__(self,retval): self.retval=retval class return_cont(object): """ Yielding a return_cont object from a generator advice causes passing the given argument as a return value of the original method to the caller. The execution of the advice will be continued from the yield point when the wrapped function is called next time. """ def __init__(self,retval): self.retval=retval class get_wrapped(object): """ Yielding a get_wrapped_function class from a generator advice causes the wrapped function object to be sent to the advice. """ pass def wrap_around_re(aClass, wildcard, advice): """ Same as wrap_around but works with regular expression based wildcards to map which methods are going to be used. """ matcher = re.compile(wildcard) for aMember in dir(aClass): realMember = getattr(aClass, aMember) if callable(realMember) and aMember[:6]!="__wrap" and \ aMember[:9]!="__proceed" and \ matcher.match(aMember): wrap_around(realMember, advice) def with_wrap(advice, *methods, **kwargs): insts = kwargs.get('instances', []) retval = [] for m in methods: if getattr(m, 'im_self', None) != None: # Method m is a bound method. It will be wrapped equally # to the corresponding unbound method with argument # instances=[m.im_self]. try: unbound_m = getattr(m.im_class, m.im_func.func_name) except: raise AspectsException("Could not find the unbound version of method %s" % (m,)) retval.append(_with_wrap(advice, unbound_m, instances=[m.im_self])) else: # Method m is a function or an unbound method. retval.append(_with_wrap(advice, m, instances=insts)) if len(retval) == 1: return retval[0] else: return retval _next_wrap_id = 0 def _with_wrap(advice, method, instances=[]): """ with_wrap wraps the execution of method inside given generator. When the method is called, the generator is invoked with the parameters the method call contains. If the generator yields, the yielded values define the new parameters to the method. The return value of the method is sent to the generator with .send method. If then generator yields again, the yielded value is passed as a return value that the caller of the method sees. If it does not, the return value is passed to the caller as is. If the first yield returns None instead of a pair of new arguments, the arguments are given to the original method. Usage: >>> def g_adv(*args,**kwargs): ... print 'g_adv received arguments',args,kwargs ... retval = yield aspects.proceed ... print 'method returned',retval ... yield aspects.return_stop(retval + 1) ... >>> class c: ... def inc(number): ... return number+1 ... >>> aspects.with_wrap(c.inc, g_adv) >>> o=c() >>> o.inc(41) g_adv received arguments ((41,), {}) method returned 42 43 """ global _next_wrap_id _permission_to_touch_wraps.acquire() wrap_id = _next_wrap_id _next_wrap_id += 1 methods_name = method.__name__ orig_method = method # Information on the original method and the advice will be # plugged to the new method (that is, the new middleman) later on. new_method = _create_middleman() try: # Older Pythons do not accept try-except-finally, so there is # outer try-finally here just to make sure that # _permission_to_touch_wraps lock will be released try: # Already wrapped method's namespace can be found from # aspects-orig-method-namespace replace_method = getattr(method, '__aspects_rmf') except AttributeError: if hasattr(method, 'im_class'): # is this a method of a class? replace_method = \ lambda orig, new: setattr(method.im_class, orig, new) elif hasattr(method, 'func_globals'): # is this a normal function? replace_method = \ lambda orig, new: method.func_globals.__setitem__(orig, new) else: m = inspect.getmodule(method.__module__) if m == None: if method.__module__ in ['nt', 'posix']: # os module has funny names, but we need to # modify the dict of os module, not nt's or posix's. m = __import__('os', [], [], '') else: # sometimes inspect fails to return a module m = __import__(method.__module__, [], [], '') if not type(m) == types.ModuleType: raise AspectsException("Module of %s not found" % (method,)) replace_method = \ lambda orig, new: m.__dict__.__setitem__(orig, new) replace_method(methods_name, new_method) new_method.__name__ = method.__name__ new_method.__aspects_wrapid = wrap_id new_method.__aspects_rmf = replace_method new_method.__aspects_cont = None # generator to be continued new_method.__aspects_instances = set([id(i) for i in instances]) new_method.__aspects_enabled = 1 new_method.__aspects_orig = orig_method new_method.__aspects_adv = advice return wrap_id finally: _permission_to_touch_wraps.release() def _create_middleman(): def generator_middleman(*args,**kwargs): # Generator_advice is not executed if the advice is not # enabled or if we are dealing with an incorrect instance method = generator_middleman.__aspects_orig if generator_middleman.__aspects_enabled==0 or \ (generator_middleman.__aspects_instances and not id(args[0]) in generator_middleman.__aspects_instances): return method(*args,**kwargs) generator_advice = generator_middleman.__aspects_adv # If a generator is waiting for call, continue its execution # with send(). Otherwise, create a new generator advice. if generator_middleman.__aspects_cont==None: g=generator_advice(*args,**kwargs) if type(g)!=types.GeneratorType: raise AspectsException("Advice is not a generator") try: rv=g.next() except StopIteration: return None else: g=generator_middleman.__aspects_cont generator_middleman.__aspects_cont=None try: rv=g.send((args,kwargs)) except StopIteration: return None # Continue execution in the generator to the first yield. # yielded value => affect # proceed (class) => wrapped method is called with orig # parameters, may raise exceptions # proceed (object) => wrapped method is called with given # parameters, may raise exceptions # return_stop (class) => the return value of the original # method is passed to the caller. Execution of the generator # advice starts from the beginning when the method is called # next time. # return_stop (object) => the given return value is passed to # the caller. Execution of the generator advice starts from # the beginning when the method is called next time. # return_cont (class) => the return value of the original # method is passed to the caller. Execution of the generator # advice continues from the yielding row when the method is # called next time. # return_cont (object) => the given return value is passed to # the caller. Execution of the generator advice continues from # the yielding row when the method is called next time. # get_wrapped (class) => sends the lower level wrap to the current wrap # FUTURE DEVELOPMENT # getorig (class) => sends the original method to the wrap orig_retval_available=0 while 1: # Reset the arguments for the original method, if new ones are # given with yield if rv==proceed: pass # args and kwargs are as they are elif type(rv)==proceed: args,kwargs=rv.args,rv.kwargs elif rv==return_stop: if orig_retval_available==0: raise AspectsException("Original return value not available.") return method_rv elif type(rv)==return_stop: return rv.retval elif rv==return_cont: if orig_retval_available==0: raise AspectsException("Original return value not available.") generator_middleman.__aspects_cont=g return method_rv elif type(rv)==return_cont: generator_middleman.__aspects_cont=g return rv.retval elif rv==get_wrapped: try: rv=g.send(method) except StopIteration: return None continue else: raise AspectsException("Advice yielded an illegal value: '%s'" % str(rv)) # Call the original method. Its return value will be sent to # the generator. If the method raises an exception, the same # exception is raised in the generator. method_rv=None try: method_rv=method(*args,**kwargs) orig_retval_available=1 raised_exception=None except Exception,e: raised_exception=e # last orig method call did not return a value: orig_retval_available=0 # Continue execution in the generator advice by sending it the # return value or raising the catched exception. try: if not raised_exception: rv=g.send(method_rv) else: rv=g.throw(e) except StopIteration: return method_rv # end of generator_middleman return generator_middleman def wrap_around(method, advice, instances=[]): """ This function will be deprecated. wrap_around wraps an unbound method (the first argument) inside an advice (function given as the second argument). When the method is called, the code of the advice is executed to the point of 'self.__proceed(*args,**keyw)'. Then the original method is executed after which the control returns to the advice. Keyword parameter instances is a container. When it is not empty, it specifies a set of id:s of instances with which the advice is executed. If the wrapped method is bound to an instance not in the set, the advice is omitted. Returns the number of the added wrap. The number can be used later on for enabling and disabling the wrap. """ _permission_to_touch_wraps.acquire() try: methods_name, methods_class, _ = _names_mce(method) if methods_name[:2]=="__" and not hasattr(methods_class,methods_name): methods_name="_"+methods_class.__name__+methods_name # Check if __proceed method is implemented in the class try: getattr(methods_class,'__proceed') except: setattr(methods_class, '__proceed_stack', _proceed_stack_method) setattr(methods_class,'__proceed', _proceed_method) # Check how many times this method has been wrapped methodwrapcount = wrap_count(method) # Rename the original method: it will be __wrapped/n/origmethodname # where /n/ is the number of wraps around it wrapped_method_name = "__wrapped" + str(methodwrapcount) + methods_name orig_method = getattr( methods_class, methods_name) setattr(methods_class, wrapped_method_name, orig_method) # Add the wrap (that is, the advice) as a new method wrapper_method_name = "__wrap" + str(methodwrapcount) + methods_name setattr(methods_class, wrapper_method_name, advice) # Add __wrap_enabled/n/methodname attribute that is used for # enabling and disabling the wrap on the fly. By default the wrap # is enabled. enabled_attr_name = "__wrap_enabled" + str(methodwrapcount) + methods_name setattr(methods_class, enabled_attr_name, 1) # Generate condition: should this wrap be executed when the method is called cond_execute_wrap="self." + enabled_attr_name if len(instances)>0: instanceids_attr_name="__wrap_instanceids"+str(methodwrapcount)+methods_name if _python_version >= (2,4): setattr(methods_class,instanceids_attr_name,set([id(i) for i in instances])) else: # slower implementation for older pythons setattr(methods_class,instanceids_attr_name,[id(i) for i in instances]) cond_execute_wrap="("+cond_execute_wrap+")" + \ "and (id(self) in self."+instanceids_attr_name+")" # Replace the original method by a method that # 1) sets which method should be executed in the next proceed call # 2) calls the wrap (advice) new_code = "def " + methods_name + "(self,*args,**keyw):\n" +\ "\tif not (" + cond_execute_wrap + "):\n" +\ "\t\treturn self." + wrapped_method_name + "(*args,**keyw)\n" +\ "\tstack=self.__proceed_stack()\n" +\ "\tstack.append( _Proceed_stack_entry(self." + wrapped_method_name + ",'" + methods_class.__name__ + "." + methods_name + "'))\n" +\ "\ttry: retval = self." + wrapper_method_name + "(*args,**keyw)\n" +\ "\tfinally:\n" +\ "\t\tstack.pop()\n" +\ "\t\tif len(stack)==0: _remove_proceed_stack(self)\n" +\ "\treturn retval\n" new_method = _create_function(new_code, methods_name) new_method.__aspects_wrapid=methodwrapcount new_method.__aspects_orig=orig_method # setattr(new_method,'__aspects_enabled',1) # new_method.__name__=methods_name setattr(methods_class, methods_name, new_method) return methodwrapcount finally: _permission_to_touch_wraps.release() def without_wrap(advice_or_wrapid, method): _permission_to_touch_wraps.acquire() # 1. Search the wrap to be removed in the wrap stack # and store it to the middleman variable if isinstance(advice_or_wrapid, int): # wrap is referenced by id # cannot use _find_wrap, because prev_middleman is needed, too wrapid = advice_or_wrapid prev_middleman = None middleman = method try: while middleman.__aspects_wrapid != wrapid: prev_middleman = middleman middleman = middleman.__aspects_orig except AttributeError: _permission_to_touch_wraps.release() raise AspectsException("Method '%s' has no wrap '%s'" % (method, wrapid)) else: # removed wrap is referenced the advice function advice = advice_or_wrapid prev_middleman = None middleman = method try: while middleman.__aspects_adv != advice: prev_middleman = middleman middleman = middleman.__aspects_orig except AttributeError: _permission_to_touch_wraps.release() raise AspectsException("Method '%s' has no wrap '%s'" % (method, advice)) retval = middleman.__aspects_adv # 2. Remove the current middleman if prev_middleman == None: # Must replace the method. This may be a poor solution, # because it may not change callbacks. A better solution might # be to switch the advice code between middlemen, keep the # topmost middleman the same, and remove the next middleman # from the chain. middleman.__aspects_rmf(middleman.__aspects_orig.__name__, middleman.__aspects_orig) else: # Drop the middleman from the list. prev_middleman.__aspects_orig = middleman.__aspects_orig _permission_to_touch_wraps.release() return retval def peel_around(method): """ This function will be deprecated. Removes one wrap around the method (given as a parameter) and returns the wrap. If the method is not wrapped, returns None. """ _permission_to_touch_wraps.acquire() # released in finally part try: if hasattr(method,'__aspects_enabled'): # new-style aspect, easy! method.__aspects_rmf(method.__name__,method.__aspects_orig) return method.__aspects_adv methods_name = method.__name__ methods_class = method.im_class wc = wrap_count(method)-1 if wc==-1: return None wrapped = getattr(methods_class, '__wrapped' + str(wc) + methods_name) setattr(methods_class, methods_name, wrapped) removed_adv = getattr(methods_class, '__wrap'+str(wc)+methods_name) del methods_class.__dict__['__wrapped'+str(wc)+methods_name] del methods_class.__dict__['__wrap'+str(wc)+methods_name] return removed_adv finally: _permission_to_touch_wraps.release() def _find_wrap(method, wrap_number): wrapid = getattr(method, '__aspects_wrapid', None) while wrapid != wrap_number: if wrapid == None: raise AspectsException("Wrap %s on method %s not found." % (wrap_number, method.__name__)) method = method.__aspects_orig wrapid = getattr(method, '__aspects_wrapid', None) return method def enable_wrap(method, wrap_number): wrap=_find_wrap(method, wrap_number) if hasattr(wrap,'__aspects_enabled'): setattr(wrap,'__aspects_enabled',1) else: _, methods_class, enabled_attr_name = _names_mce(method, wrap_number) setattr(methods_class, enabled_attr_name, 1) def disable_wrap(method, wrap_number): wrap=_find_wrap(method, wrap_number) if hasattr(wrap,'__aspects_enabled'): setattr(wrap,'__aspects_enabled',0) else: _, methods_class, enabled_attr_name = _names_mce(method, wrap_number) setattr(methods_class, enabled_attr_name, 0) def wrap_is_enabled(method, wrap_number): wrap=_find_wrap(method, wrap_number) if hasattr(wrap,'__aspects_enabled'): return getattr(wrap,'__aspects_enabled') else: _, methods_class, enabled_attr_name = _names_mce(method, wrap_number) return getattr(methods_class, enabled_attr_name) def wrap_count(method): """ Returns number of wraps around given method. """ number = 0 while hasattr(method, '__aspects_orig'): number += 1 method = method.__aspects_orig return number def _names_mce(method, wrap_number=None): """ Returns triplet of names: Method, it's Class and wrap's Enabled attr name. If enabled attr name does not exist (that is, there is no wrap wrap_number on the method), AspectsException is raised. """ methods_name = method.__name__ methods_class = method.im_class if wrap_number!=None: enabled_attr_name = "__wrap_enabled" + str(wrap_number) + methods_name if not hasattr(methods_class, enabled_attr_name): raise AspectsException("Method %s does not have wrap with number %s" % (methods_name, wrap_number)) else: enabled_attr_name=None return methods_name, methods_class, enabled_attr_name def _proceed_method(self, *args, **keyw): method=self.__proceed_stack()[-1].method return method(*args, **keyw) def _remove_proceed_stack(self): stackname='__proceed_stack' + str(thread.get_ident()) delattr(self,stackname) def _proceed_stack_method(self): stackname='__proceed_stack' + str(thread.get_ident()) try: return getattr(self,stackname) except: setattr(self,stackname,[]) return getattr(self,stackname) def _create_function(function_code, function_name, thread_lib=1): # import thread if it is required # if thread_lib and not 'thread' in globals(): import thread codeobj = compile(function_code, "", "exec") gl = {'_Proceed_stack_entry':_Proceed_stack_entry, '_remove_proceed_stack': _remove_proceed_stack} lo = {} exec(codeobj,gl,lo) return eval(function_name,gl,lo) class _Proceed_stack_entry: def __init__(self, method, name): self.method = method self.name = name python-aspects-1.3/test/0000755000175000017500000000000011074124621013431 5ustar askaskpython-aspects-1.3/test/test_with_wrap.py0000644000175000017500000000047411003174321017045 0ustar askask""" This is a wrapper to the real generator advice unit test. The tests cannot be run without Python 2.5 or later. """ import sys _python_version=sys.version_info[:2] if _python_version < (2,5): print "SKIP","Python 2.5 or later required, you have",_python_version sys.exit(127) import testlib_with_wrap python-aspects-1.3/test/testlib_with_wrap.py0000644000175000017500000004010011074117220017525 0ustar askaskPASS,FAIL="PASS","FAIL" import aspects import os test,verdict = "wrap a module function inside very simple g_adv",FAIL try: g_adv_executed=0 def _test_mod_function(x): return x+42 def g_adv(x): global g_adv_executed g_adv_executed=1 yield aspects.proceed rv=aspects.with_wrap(g_adv,_test_mod_function) r=_test_mod_function(42) if rv==0 and r==84 and g_adv_executed: verdict=PASS finally: print verdict,test test,verdict = "change the arguments",FAIL try: def __test_mod_function(x): return x+42 def g_adv(x): yield aspects.proceed(x+1) aspects.with_wrap(g_adv,__test_mod_function) if __test_mod_function(0)==43: verdict=PASS finally: print verdict,test test,verdict = "change the return value",FAIL try: def __test_mod_function(x): return x+42 def g_adv(x): retval=yield aspects.proceed(x+1) yield aspects.return_stop(retval+10) aspects.with_wrap(g_adv,__test_mod_function) if __test_mod_function(0)==53: verdict=PASS finally: print verdict,test test,verdict = "reinvoking wrapped method",FAIL try: argsum=0 def __test_mod_function(x): global argsum argsum+=x return argsum def g_adv(x): yield aspects.proceed(1) yield aspects.proceed(1) yield aspects.proceed(1) aspects.with_wrap(g_adv,__test_mod_function) if __test_mod_function(0)==3: verdict=PASS finally: print verdict,test test,verdict = "non-yielding advice blocks the method call and returns None",FAIL try: def __test_mod_function(x): return x+42 def g_adv(x): if 1==0: yield aspects.proceed(15) aspects.with_wrap(g_adv,__test_mod_function) if __test_mod_function(0)==None: verdict=PASS finally: print verdict,test test,verdict = "unhandled exception passes through advice",FAIL try: # Wrapped function throws exception that is not handled in # the wrap. It should be caught by the caller. def __test_mod_function(x): raise Exception("test exception") def g_adv(x): retval=yield aspects.proceed(x+1) yield aspects.return_stop(retval+10) aspects.with_wrap(g_adv,__test_mod_function) try: __test_mod_function(0) except Exception,e: if str(e)=="test exception": verdict=PASS finally: print verdict,test test,verdict = "advice catches an exception",FAIL try: # Wrapped function throws exception but the wrap catches it and # sets new return value def __test_mod_function(x): raise Exception("test exception2") def g_adv(x): retval=0 try: retval=yield aspects.proceed(x+1) except Exception, e: if str(e)=="test exception2": yield aspects.return_stop(retval+10) aspects.with_wrap(g_adv,__test_mod_function) if __test_mod_function(0)==10: verdict=PASS finally: print verdict,test test,verdict = "two advices on a method, new-style class",FAIL try: class c(object): def sq(self,x=1): return x*x def g_adv1(self,x=3): retval=yield aspects.proceed yield aspects.return_stop(retval+1) def g_adv2(self,x=5): yield aspects.proceed(self,x=x) rv1=aspects.with_wrap(g_adv1,c.sq) rv2=aspects.with_wrap(g_adv2,c.sq) o=c() assert o.sq()==26, "o.sq()!=26" assert aspects.wrap_count(c.sq) == 2, "wrap_count fails!" verdict=PASS finally: print verdict,test test,verdict = "two advices on a function",FAIL try: def sq(*args): return args def g_adv1(*args): yield aspects.proceed(*args+(1,)) def g_adv2(*args): rv = yield aspects.proceed(*args+(2,)) yield aspects.return_stop("-".join(str(s) for s in rv)) rv1=aspects.with_wrap(g_adv1,sq) rv2=aspects.with_wrap(g_adv2,sq) if sq(0)=="0-2-1": verdict=PASS else: print sq(0) finally: print verdict,test test,verdict = "two advices and catching exceptions",FAIL try: class c: def sq(self,x=2): return x*x def g_adv1(self,x=3): retval=yield aspects.proceed self.g_adv1_saw_rv=retval def g_adv2(self,x=5): try: yield aspects.proceed except Exception,e: self.g_adv2_saw_ex=e yield aspects.return_stop(11) aspects.with_wrap(g_adv1,c.sq) aspects.with_wrap(g_adv2,c.sq) o=c() if o.sq('a')!=11: raise Exception("o.sq('a')!=11") if not hasattr(o,'g_adv1_saw_rv') and type(o.g_adv2_saw_ex)==TypeError: verdict=PASS finally: print verdict,test test,verdict = "recursive function wrapped",FAIL try: def fib(x): if x<2: return 1 else: return fib(x-1)+fib(x-2) def g_adv(x): r = yield aspects.proceed(x) yield aspects.return_stop(r+1) aspects.with_wrap(g_adv,fib) if fib(4)==14: verdict=PASS else: print fib(4) finally: print verdict,test test,verdict = "wrap calls another wrapped method",FAIL try: class c: def sq(self,x): return self.mul(x,x+1) def mul(self,x,y): # this multiplier has an off-by-one bug if y>=1: return x+self.mul(x,y-1) else: return x def g_adv_fixsq(self,x): yield aspects.return_stop(self.mul(x,x)) def g_adv_fixmul(self,x,y): if y<1: yield aspects.return_stop(0) else: yield aspects.proceed rv1=aspects.with_wrap(g_adv_fixsq,c.sq) rv2=aspects.with_wrap(g_adv_fixmul,c.mul) o=c() if o.sq(5)==25: verdict=PASS finally: print verdict,test test,verdict = "advices with state",FAIL try: def fun42(x): return x+42 def fun32(x): return x+32 def adv(x): args, kwargs = yield aspects.return_cont(22) x=args[0] yield aspects.proceed(x) # Note that calling different methods calls different instances of # the advice. Therefore, initially, fun42(1)==22 and fun32(1)==22 # and not fun42(1)==22 and fun32(1)==33. aspects.with_wrap(adv,fun42,fun32) if fun42(1)==22 and fun42(1)==43 and fun42(1)==22 \ and fun32(1)==22 and fun32(1)==33: verdict=PASS else: print fun42(1),fun32(1),fun32(1) finally: print verdict,test test,verdict = "enable_wrap, disable_wrap, wrap_is_enabled",FAIL try: def succ(x): return x+1 def add2(*a,**kw): rv = yield aspects.proceed yield aspects.return_stop(rv+2) def add4(*a,**kw): rv = yield aspects.proceed yield aspects.return_stop(rv+4) a2=aspects.with_wrap(add2,succ) a4=aspects.with_wrap(add4,succ) wis=aspects.wrap_is_enabled if wis(succ,a2)!=1 or wis(succ,a4)!=1: raise Exception("wis1") aspects.disable_wrap(succ,a4) if wis(succ,a2)!=1 or wis(succ,a4)!=0: raise Exception("wis2") if succ(0)!=3: raise Exception("succ(0)==%s!=3" % succ(0)) aspects.disable_wrap(succ,a2) if wis(succ,a2)!=0 or wis(succ,a4)!=0: raise Exception("wis3") if succ(0)!=1: raise Exception("succ(0)==%s!=1" % succ(0)) aspects.enable_wrap(succ,a4) if wis(succ,a2)!=0 or wis(succ,a4)!=1: raise Exception("wis4") if succ(0)!=5: raise Exception("succ(0)==%s!=5" % succ(0)) aspects.enable_wrap(succ,a2) if wis(succ,a2)!=1 or wis(succ,a4)!=1: raise Exception("wis5") if succ(0)!=7: raise Exception("succ(0)==%s!=7" % succ(0)) verdict=PASS finally: print verdict,test test,verdict = "instance-specific aspects",FAIL try: class c: def foo(self): return 'foo' def bar(self): return 'bar' def adv1(self): yield aspects.return_stop('adv1') def adv2(self): yield aspects.return_stop('adv2') o1=c() o2=c() o3=c() aspects.with_wrap(adv1,c.foo,c.bar,instances=[o1]) aspects.with_wrap(adv2,c.foo,instances=[o1,o2]) if o3.foo()!='foo' or o3.bar()!='bar': raise Exception("o3") if o2.foo()!='adv2' or o2.bar()!='bar': raise Exception("o2") if o1.foo()!='adv2' or o1.bar()!='adv1': raise Exception("o1") verdict=PASS finally: print verdict,test test,verdict = "peel_around a function and a method",FAIL try: def foo(x): return x+1 class c: def foo(self,x): return x+2 class newc(object): def foo(self,x): return x+3 def adv(*a): yield aspects.return_stop(42) def adv2(*a): yield aspects.return_stop(52) aspects.with_wrap(adv,foo,c.foo,newc.foo) o=c() newo=newc() if not (foo(0)==o.foo(1)==newo.foo(2)==42): raise Exception("first wrapping failed already") aspects.with_wrap(adv2,foo,c.foo,newc.foo) if not (foo(0)==o.foo(1)==newo.foo(2)==52): raise Exception("second wrapping failed already") w1=aspects.peel_around(foo) w2=aspects.peel_around(c.foo) w3=aspects.peel_around(newc.foo) if not (foo(0)==o.foo(1)==newo.foo(2)==42): raise Exception("first peeling failed") aspects.peel_around(foo) aspects.peel_around(c.foo) aspects.peel_around(newc.foo) if not (foo(0)==1 and o.foo(0)==2 and newo.foo(0)==3): raise Exception("second peeling failed") aspects.with_wrap(w1,foo) aspects.with_wrap(w2,c.foo) aspects.with_wrap(w3,newc.foo) if not (foo(0)==o.foo(1)==newo.foo(2)==52): raise Exception("peels could not be put back") verdict=PASS finally: print verdict,test test,verdict = "asking for a wrapped function",FAIL try: def wf(): pass def wrap(*a): wrapped_func = yield aspects.get_wrapped if wrapped_func.__name__=="wf": yield aspects.return_stop(PASS) else: yield aspects.return_stop(FAIL) aspects.with_wrap(wrap,wf) verdict=wf() finally: print verdict,test test,verdict = "wrapping a built-in operator",FAIL try: import operator def offbyone(*a): real_output = yield aspects.proceed if type(real_output)==int: yield aspects.return_stop(real_output+1) aspects.with_wrap(offbyone, operator.add) if operator.add(1, 1) == 3: verdict = PASS finally: print verdict,test test,verdict = "wrapping a built-in function from the os library",FAIL try: def w(*a): yield aspects.return_stop("WRAPPED %s" % (yield aspects.proceed)) aspects.with_wrap(w, os.getcwd) if os.getcwd()[:8] == "WRAPPED ": verdict = PASS finally: print verdict,test test,verdict = "without wrap: removing arbitrary wraps",FAIL try: def wrapme(x): return "wrapme" + x def w1(x): yield aspects.proceed("w1" + x) def w2(x): yield aspects.proceed("w2" + x) def w3(x): yield aspects.proceed("w3" + x) def w4(x): yield aspects.proceed("w4" + x) for w in (w1, w2, w4, w3, w4): aspects.with_wrap(w, wrapme) # check that everything is fine assert wrapme("") == "wrapmew1w2w4w3w4", "preparation failed" # remove the topmost wrap aspects.without_wrap(w4, wrapme) assert wrapme("") == "wrapmew1w2w4w3", "topmost" # remove the wrap in the middle aspects.without_wrap(w4, wrapme) assert wrapme("") == "wrapmew1w2w3", "middle" # remove the wrap on the bottom aspects.without_wrap(w1, wrapme) assert wrapme("") == "wrapmew2w3", "bottom" # remove the rest wraps aspects.without_wrap(w2, wrapme) aspects.without_wrap(w3, wrapme) assert wrapme("") == "wrapme", "rest" # test removing by wrap id wid1 = aspects.with_wrap(w1, wrapme) wid2 = aspects.with_wrap(w2, wrapme) wid3 = aspects.with_wrap(w1, wrapme) wid4 = aspects.with_wrap(w3, wrapme) wid5 = aspects.with_wrap(w1, wrapme) wid6 = aspects.with_wrap(w4, wrapme) wid7 = aspects.with_wrap(w1, wrapme) assert wrapme("") == "wrapmew1w2w1w3w1w4w1", "preparation 2 failed" aspects.without_wrap(wid1, wrapme) aspects.without_wrap(wid7, wrapme) assert wrapme("") == "wrapmew2w1w3w1w4", "first and last removed" aspects.without_wrap(wid4, wrapme) assert wrapme("") == "wrapmew2w1w1w4", "middle removed" aspects.without_wrap(wid3, wrapme) aspects.without_wrap(wid2, wrapme) aspects.without_wrap(wid5, wrapme) assert wrapme("") == "wrapmew4", "one left" aspects.without_wrap(wid6, wrapme) assert wrapme("") == "wrapme", "all gone" verdict = PASS finally: print verdict,test test, verdict = "bound methods", FAIL try: class co: def m_co(self): return self.x_co class do(co): def m_do(self): return self.m_co() def w_do(self_do, self_co, *args): rv = yield aspects.proceed yield aspects.return_stop(rv+1) o1 = do() o2 = do() o3 = co() aspects.with_wrap(o1.w_do, o1.m_co) # executes only when called through o1 aspects.with_wrap(o1.w_do, do.m_co) # executes always o1.x_co = 1 o2.x_co = 1 o3.x_co = 1 assert o1.m_do() == 3 assert o2.m_do() == 2 assert o3.m_co() == 1 # no wraps in the base class # Exactly the same, this time for new-style classes class co(object): def m_co(self): return self.x_co class do(co): def m_do(self): return self.m_co() def w_do(self_do, self_co, *args): rv = yield aspects.proceed yield aspects.return_stop(rv+1) o1 = do() o2 = do() o3 = co() aspects.with_wrap(o1.w_do, o1.m_co) # executes only when called through o1 aspects.with_wrap(o1.w_do, do.m_co) # executes always o1.x_co = 5 o2.x_co = 5 o3.x_co = 5 assert o1.m_do() == 7 assert o2.m_do() == 6 assert o3.m_co() == 5 # no wraps in the base class verdict = PASS finally: print verdict, test ######################################################################## # # TESTING ILLEGAL BEHAVIOUR # ######################################################################## test,verdict = "without wrap: erroneous use",FAIL try: def wrapme(x): return "wrapme" + x def wrapme2(x): return "wrapme2" + x def w1(x): yield aspects.proceed("w1" + x) def w2(x): yield aspects.proceed("w2" + x) def w3(): rv = yield aspects.proceed yield aspects.return_stop("w3" + str(rv)) w1id = aspects.with_wrap(w1, wrapme) w2id = aspects.with_wrap(w2, wrapme) # Try to remove a wrap from a non-wrapped function ok = 0 try: aspects.without_wrap(w1, wrapme2) except aspects.AspectsException: ok = 1 assert ok == 1, "unwrapping non-wrapped function" # Try to remove a wrap (wrap id) from a non-wrapped function ok = 0 try: aspects.without_wrap(w1id, wrapme2) except aspects.AspectsException: ok = 1 assert ok == 1, "unwrapping according to wrap_id non-wrapped function" w3id = aspects.with_wrap(w3, os.getpid) # Try to remove a wrap from a wrapped function ok = 0 try: aspects.without_wrap(w3, wrapme) except aspects.AspectsException: ok = 1 assert ok == 1, "unwrapping wrapped function" # Try to remove a wrap (wrap id) from a wrapped function ok = 0 try: aspects.without_wrap(w1id, os.getpid) except aspects.AspectsException: ok = 1 assert ok == 1, "unwrapping according to wrap_id a wrapped function" # Making sure that the wraps still work and clean them up assert os.getpid().startswith("w3"), "os.gitpid wrap does not work" assert wrapme("") == "wrapmew1w2", "wrapme wrap does not work" aspects.without_wrap(w2id, wrapme) aspects.without_wrap(w1, wrapme) aspects.without_wrap(w3id, os.getpid) assert int(os.getpid()) > 0, "os.gitpid could not be cleaned" assert wrapme("") == "wrapme", "wrapme could not be cleaned" verdict = PASS finally: print verdict,test test,verdict = "non-generator advice wrapped with with_wrap",FAIL try: def __test_mod_function(x): return x+42 def adv(x): return 144 aspects.with_wrap(adv,__test_mod_function) try: __test_mod_function(0) except aspects.AspectsException: verdict=PASS finally: print verdict,test test,verdict = "returning and yielding without proceeding", FAIL try: def fun1(x): return x def fun2(x): return x def return_early(x): aspects.return_stop def yield_early(x): aspects.return_cont aspects.with_wrap(return_early,fun1) aspects.with_wrap(yield_early,fun2) try: fun1(0) except aspects.AspectsException: try: fun2(0) except aspects.AspectsException: verdict=PASS finally: print verdict,test python-aspects-1.3/test/test_aspects.py0000644000175000017500000001362711074117243016517 0ustar askask#!/usr/bin/env python PASS,FAIL="PASS","FAIL" import thread import time test,verdict="importing aspects library",FAIL try: import aspects verdict=PASS finally: print verdict,test test,verdict="checking version_info",FAIL try: if aspects.version_info==(1,3): verdict=PASS test+=", returned: %s" % str(aspects.version_info) finally: print verdict,test # Some test data class C: def __foo0(self,num): return num def foo1(self,num): return self.__foo0(num)+1 def foo2(self,num): return self.__foo0(num)+2 def bar1(self,num): return self.__foo0(num)+4 def adv1(self,*args): return self.__proceed(args[0]+100) def adv2(self,*args,**keyw): return self.__proceed(keyw['num']+400) o=C() test,verdict="using wrap_count when no wraps",FAIL try: if aspects.wrap_count(C.foo1)==0: verdict=PASS finally: print verdict,test test,verdict="wrap_around a public method, keyword argument",FAIL try: n=aspects.wrap_around(C.foo1,adv2) if o.foo1(num=0)==401 and n==0: verdict=PASS finally: print verdict,test test,verdict="using wrap_count when one wrap",FAIL try: if aspects.wrap_count(C.foo1)==1: verdict=PASS else: print "wrap_count returned",aspects.wrap_count(C.foo1) finally: print verdict,test test,verdict="wrap_around a private method (called by a public method)",FAIL try: aspects.wrap_around(C._C__foo0,adv1) if o.foo1(num=0)==501: verdict=PASS finally: print verdict,test test,verdict="using wrap_count on private method",FAIL try: if aspects.wrap_count(C._C__foo0)==1: verdict=PASS finally: print verdict,test test,verdict="peel_around clear advices",FAIL try: try: aspects.peel_around(C.foo1) aspects.peel_around(C._C__foo0) if o.foo1(num=0)==1: verdict=PASS except: pass finally: print verdict,test test,verdict="using wrap_count on peeled methods",FAIL try: if aspects.wrap_count(C.foo1)==0 and \ aspects.wrap_count(C._C__foo0)==0: verdict=PASS finally: print verdict,test test,verdict="wrap_around_re, wrap_around, normal arguments",FAIL try: aspects.wrap_around_re(C,'foo[0-9]',adv1) if o.foo1(0)==101 and o.foo2(0)==102: verdict=PASS finally: print verdict,test test,verdict="peel_around 1/2: remove advice",FAIL try: peel=aspects.peel_around(C.foo1) # peel=adv1 if o.foo1(0)==1: verdict=PASS finally: print verdict,test test,verdict="peel_around 2/2: rewrap peeled method. One method wrapped twice.",FAIL try: aspects.wrap_around_re(C,'.*',peel) # peel=adv1 if o.foo1(0)==201 and o.foo2(0)==302 and o.bar1(0)==204: verdict=PASS finally: print verdict,test test,verdict="keyword arguments, two different wraps on one method",FAIL try: surface_wrapnum=aspects.wrap_around(C.bar1,adv2) # bar1 is has now wraps adv2/adv1, it calls _foo0 which has wrap adv1 if o.bar1(num=8)==612: verdict=PASS finally: print verdict,test test,verdict="using wrap_count when two wraps",FAIL try: if aspects.wrap_count(C.bar1)==2: verdict=PASS else: print aspects.wrap_count(C.bar1) finally: print verdict,test test,verdict="disabling the deeper wrap",FAIL try: aspects.disable_wrap(C.bar1,0) # adv1 disabled if o.bar1(num=8)==512: verdict=PASS finally: print verdict,test test,verdict="testing wrap_is_enabled",FAIL try: if aspects.wrap_is_enabled(C.bar1,0)==0 and \ aspects.wrap_is_enabled(C.bar1,surface_wrapnum)==1: verdict=PASS finally: print verdict,test test,verdict="disabling the shallower wrap",FAIL try: aspects.disable_wrap(C.bar1,surface_wrapnum) # adv2 disabled if o.bar1(8)==112: verdict=PASS finally: print verdict,test test,verdict="enabling all wraps",FAIL try: for i in range(aspects.wrap_count(C.bar1)): aspects.enable_wrap(C.bar1,i) if o.bar1(num=8)==612: verdict=PASS finally: print verdict,test test,verdict="enabling, disabling and testing non-existing wraps",FAIL try: try: aspects.disable_wrap(C.bar1,42) except aspects.AspectsException: try: aspects.disable_wrap(C.bar1,-1) except aspects.AspectsException: try: aspects.wrap_is_enabled(C.bar1,55) except aspects.AspectsException: verdict=PASS finally: print verdict,test test,verdict="wrap methods of certain instances",FAIL try: class D: def addone(self,x): self.y=x+1 return self.y def const(self): return 42 def extra(self,x): return self.__proceed(x+1)+1 o1,o2,o3=D(),D(),D() aspects.wrap_around(D.addone,extra,instances=[o1,o2]) retvals=[o1.addone(0), o2.addone(0), o3.addone(0)] if o1.const()==42 and o1.y==o2.y==2 and o3.y==1 and \ retvals==[3,3,1]: verdict=PASS finally: print verdict,test test,verdict="wrapping bound methods of certain instances",FAIL try: class D: def addone(self,x): self.y=x+1 return self.y def const(self): return 42 def extra_noarg(self): return self.__proceed()+1 o1,o2,o3=D(),D(),D() aspects.wrap_around(o1.const,extra_noarg,instances=[o2,o3]) retvals=[o1.const(), o2.const(), o3.const()] if o1.addone(0)==1 and o2.addone(0)==1 and \ retvals==[42,43,43]: verdict=PASS finally: print verdict,test test,verdict="threads use separate proceed stacks",FAIL try: # If all __proceed uses the same stack in all threads, # self.__proceed() in function aa calls method b, although it # should call method a, because aa is wrapped around it. class T: def a(self): self.last_called="a" def b(self): self.last_called="b" def aa(self): time.sleep(0.2) self.__proceed() def bb(self): time.sleep(0.2) self.__proceed() aspects.wrap_around(T.a,aa) aspects.wrap_around(T.b,bb) o=T() thread.start_new_thread(o.a,()) time.sleep(0.1) thread.start_new_thread(o.b,()) time.sleep(0.4) if o.last_called=="b": verdict=PASS finally: print verdict,test python-aspects-1.3/INSTALL.txt0000644000175000017500000000024511003174254014321 0ustar askaskTo install the aspects library to your system, run python setup.py install To use the aspects library in your project, add aspects.py to your project's libraries. python-aspects-1.3/setup.py0000644000175000017500000000052511073177461014177 0ustar askaskfrom distutils.core import setup import aspects setup(name="python-aspects", version=".".join(str(s) for s in aspects.version_info), description="Lightweight AOP extension", author="Antti Kervinen", author_email="ask@cs.tut.fi", url="http://www.cs.tut.fi/~ask/aspects/index.html", py_modules=["aspects"]) python-aspects-1.3/README.txt0000644000175000017500000000000010670326411014140 0ustar askaskpython-aspects-1.3/LICENSE.txt0000644000175000017500000006347611003174254014314 0ustar askask GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. 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 not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the 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 specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it!