def testSimplePreds(self):

        [dispatch.generic()]
        def classify(age):
            """Stereotype for age"""

        def defmethod(gf,s,func):
            gf.addMethod(gf.parse(s,locals(),globals()),func)

        defmethod(classify,'not not age<2', lambda age:"infant")
        defmethod(classify,'age<13', lambda age:"preteen")
        defmethod(classify,'age<5',  lambda age:"preschooler")
        defmethod(classify,'20>age', lambda age:"teenager")
        defmethod(classify,'not age<20',lambda age:"adult")
        defmethod(classify,'age>=55',lambda age:"senior")
        defmethod(classify,'age==16',lambda age:"sweet sixteen")
        self.assertEqual(classify(25),"adult")
        self.assertEqual(classify(17),"teenager")
        self.assertEqual(classify(13),"teenager")
        self.assertEqual(classify(12.99),"preteen")
        self.assertEqual(classify(0),"infant")
        self.assertEqual(classify(4),"preschooler")
        self.assertEqual(classify(55),"senior")
        self.assertEqual(classify(54.9),"adult")
        self.assertEqual(classify(14.5),"teenager")
        self.assertEqual(classify(16),"sweet sixteen")
        self.assertEqual(classify(16.5),"teenager")
        self.assertEqual(classify(99),"senior")
        self.assertEqual(classify(Min),"infant")
        self.assertEqual(classify(Max),"senior")
 def test_NoApplicableMethods_is_raised(self):
     [dispatch.generic()]
     def demo_func(number):
         pass
     demo_func.when("number < 10")(lambda x: 0)
     self.assertEqual(demo_func(3),0)
     self.assertRaises(dispatch.NoApplicableMethods, demo_func, 33)
    def test_NoApplicableMethods_is_raised(self):
        [dispatch.generic()]

        def demo_func(number):
            pass

        demo_func.when("number < 10")(lambda x: 0)
        self.assertEqual(demo_func(3), 0)
        self.assertRaises(dispatch.NoApplicableMethods, demo_func, 33)
    def testKwArgHandling(self):
        [dispatch.generic()]
        def f(**fiz): """Test of kw handling"""

        [f.when("'x' in fiz")]
        def f(**fiz): return "x"

        [f.when("'y' in fiz")]
        def f(**fiz): return "y"

        self.assertEqual(f(x=1),"x")
        self.assertEqual(f(y=1),"y")
        self.assertRaises(AmbiguousMethod, f, x=1, y=1)
    def testSubclassDispatch(self):
        [dispatch.generic()]
        def gm (t) : pass

        [gm.when(default)]
        def gm (t) : return 'default'

        [gm.when('issubclass(t,int)')]
        def gm2 (t) : return 'int'

        self.assertEqual(gm(int),"int")
        self.assertEqual(gm(object),"default")
        self.assertEqual(gm(float),"default")
    def testVarArgHandling(self):
        [dispatch.generic()]
        def f(*fiz): """Test of vararg handling"""

        [f.when("'x' in fiz")]
        def f(*fiz): return "x"

        [f.when("'y' in fiz")]
        def f(*fiz): return "y"

        self.assertEqual(f("foo","x"),"x")
        self.assertEqual(f("bar","q","y"),"y")
        self.assertEqual(f("bar","q","y"),"y")
        self.assertEqual(f("y","q",),"y")
        self.assertRaises(AmbiguousMethod, f, "x","y")
        class X:
            [dispatch.generic()]

            def s(self, v):
                """X"""

            [s.when("v in LandVehicle")]

            def bar(self, v):
                return "land"

            [s.when("v in WaterVehicle")]

            def s(self, v):
                return "water"
    def initBeforeAfter(self): #{{{
        run_signal = Signal(base_signal)
        run_signal.connect_before(dict(before=[base_before]))
        run_signal.connect_after(dict(after=[base_after]))

        run_deco = decosig(overload=False)(base_signal)
        run_deco.before(base_before)
        run_deco.after(base_after)

        run_rule = dispatch.generic()(lambda l: l)
        run_rule.when('True')(base_signal)
        run_rule.before('True')(base_before)
        run_rule.after('True')(base_after)

        louie.connect(base_before, 'before_after', base_signal)
        louie.connect(base_signal, 'before_after', base_signal)
        louie.connect(base_after, 'before_after', base_signal)

        def run_louie(l): #{{{
            ret = louie.send('before_after', base_signal, l)
            return ret[1][1]
        # End def #}}}

        run_aossi_basesignal = BaseSignal(base_signal)
        run_aossi_basesignal.connect(before=[base_before])
        run_aossi_basesignal.connect(after=[base_after])

        run_aossi_signal = AossiSignal(base_signal)
        run_aossi_signal.connect(before=[base_before])
        run_aossi_signal.connect(after=[base_after])

        run_aossi_deco = aossi_signal()(base_signal)
        run_aossi_deco.before(base_before)
        run_aossi_deco.after(base_after)

        ba = {'base': run_base,
              'signal': run_signal,
              'deco': run_deco,
              'rule': run_rule,
              'louie': run_louie,
              'aossi_basesignal': run_aossi_basesignal,
              'aossi_signal': run_aossi_signal,
              'aossi_deco': run_aossi_deco}
        dpath = op.join('data', 'before_after')
        if not op.exists(dpath):
            os.makedirs(dpath, 0700)
        return ba
    def testSubclassDispatch(self):
        [dispatch.generic()]

        def gm(t):
            pass

        [gm.when(default)]

        def gm(t):
            return 'default'

        [gm.when('issubclass(t,int)')]

        def gm2(t):
            return 'int'

        self.assertEqual(gm(int), "int")
        self.assertEqual(gm(object), "default")
        self.assertEqual(gm(float), "default")
    def testKwArgHandling(self):
        [dispatch.generic()]

        def f(**fiz):
            """Test of kw handling"""

        [f.when("'x' in fiz")]

        def f(**fiz):
            return "x"

        [f.when("'y' in fiz")]

        def f(**fiz):
            return "y"

        self.assertEqual(f(x=1), "x")
        self.assertEqual(f(y=1), "y")
        self.assertRaises(AmbiguousMethod, f, x=1, y=1)
    def testSimpleChaining(self):
        def both_vehicles(ob1, ob2):
            return "They're both vehicles."

        def both_land(next_method, ob1, ob2):
            return next_method(ob1, ob2) + "  They are both land vehicles."

        def both_sea(next_method, ob1, ob2):
            return next_method(ob1, ob2) + "  They are both sea vehicles."

        def mixed_vehicles(next_method, ob1, ob2):
            return next_method(ob1,ob2)+ \
                "  One vehicle is a land vehicle, the other is a sea vehicle."

        [dispatch.generic()]

        def compare(v1, v2):
            pass

        compare.addMethod([(Vehicle, Vehicle)], both_vehicles)
        compare.addMethod([(LandVehicle, LandVehicle)], both_land)
        compare.addMethod([(WaterVehicle, WaterVehicle)], both_sea)

        compare.addMethod([(LandVehicle, WaterVehicle),
                           (WaterVehicle, LandVehicle)], mixed_vehicles)

        land = Bicycle()
        sea = Speedboat()
        self.assertEqual(
            compare(land, land),
            "They're both vehicles.  They are both land vehicles.")

        self.assertEqual(
            compare(sea, sea),
            "They're both vehicles.  They are both sea vehicles.")

        self.assertEqual(
            compare(land, sea), "They're both vehicles.  \
One vehicle is a land vehicle, the other is a sea vehicle.")

        self.assertEqual(
            compare(sea, land), "They're both vehicles.  \
One vehicle is a land vehicle, the other is a sea vehicle.")
示例#12
0
def _build_rules(func):
    [generic(CustomDispatch)]
    def _expose(func, accept, allow_json, *args, **kw):
        pass

    if func._allow_json:
        log.debug("Adding allow_json rule: "
            'allow_json and (kw.get("tg_format", None) == "json"'
            ' or accept in ("application/json", "text/javascript"))')
        _expose.when('allow_json and (kw.get("tg_format", None) == "json"'
            ' or accept in ("application/json", "text/javascript"))')(
            lambda _func, accept, allow_json, *args, **kw:
                _execute_func(_func, "json", "json", "application/json",
                    None, False, args, kw))

    found_default = False
    for ruleinfo in func._ruleinfo:
        found_default = _add_rule(_expose, found_default, **ruleinfo)

    func._expose = _expose
示例#13
0
def _build_rules(func):
    [generic(CustomDispatch)]
    def _expose(func, accept, allow_json, *args, **kw):
        pass

    if func._allow_json:
        log.debug("Adding allow_json rule: "
            'allow_json and (kw.get("tg_format", None) == "json"'
            ' or accept in ("application/json", "text/javascript"))')
        _expose.when('allow_json and (kw.get("tg_format", None) == "json"'
            ' or accept in ("application/json", "text/javascript"))')(
            lambda _func, accept, allow_json, *args, **kw:
                _execute_func(_func, "json", "json", "application/json",
                    None, False, args, kw))

    found_default = False
    for ruleinfo in func._ruleinfo:
        found_default = _add_rule(_expose, found_default, **ruleinfo)

    func._expose = _expose
    def testSimpleChaining(self):

        def both_vehicles(ob1,ob2):
            return "They're both vehicles."

        def both_land(next_method,ob1,ob2):
            return next_method(ob1,ob2)+"  They are both land vehicles."

        def both_sea(next_method,ob1,ob2):
            return next_method(ob1,ob2)+"  They are both sea vehicles."

        def mixed_vehicles(next_method,ob1,ob2):
            return next_method(ob1,ob2)+ \
                "  One vehicle is a land vehicle, the other is a sea vehicle."

        [dispatch.generic()]
        def compare(v1,v2): pass
        compare.addMethod([(Vehicle, Vehicle)], both_vehicles)
        compare.addMethod([(LandVehicle, LandVehicle)],both_land)
        compare.addMethod([(WaterVehicle, WaterVehicle)],both_sea)

        compare.addMethod(
            [(LandVehicle, WaterVehicle),(WaterVehicle, LandVehicle)],
            mixed_vehicles
        )

        land = Bicycle()
        sea = Speedboat()
        self.assertEqual( compare(land, land),
            "They're both vehicles.  They are both land vehicles.")

        self.assertEqual( compare(sea, sea),
            "They're both vehicles.  They are both sea vehicles.")

        self.assertEqual( compare(land, sea), "They're both vehicles.  \
One vehicle is a land vehicle, the other is a sea vehicle.")

        self.assertEqual( compare(sea, land), "They're both vehicles.  \
One vehicle is a land vehicle, the other is a sea vehicle.")
    def testVarArgHandling(self):
        [dispatch.generic()]

        def f(*fiz):
            """Test of vararg handling"""

        [f.when("'x' in fiz")]

        def f(*fiz):
            return "x"

        [f.when("'y' in fiz")]

        def f(*fiz):
            return "y"

        self.assertEqual(f("foo", "x"), "x")
        self.assertEqual(f("bar", "q", "y"), "y")
        self.assertEqual(f("bar", "q", "y"), "y")
        self.assertEqual(f(
            "y",
            "q",
        ), "y")
        self.assertRaises(AmbiguousMethod, f, "x", "y")
示例#16
0
import unittest

from dispatch import generic

from turbogears.genericfunctions import *


mo_state = []

[generic(MultiorderGenericFunction)]
def mo(a):
    pass

[mo.when("a>0", order=2)]
def mo2(next_method, a):
    mo_state.append(2)

[mo.when("a>0")]
def mo0(next_method, a):
    mo_state.append(0)
    return next_method(a)

[mo.when("a>0", order=1)]
def mo1(next_method, a):
    mo_state.append(1)
    return next_method(a)

[mo.around("a<23")]
def moa0(next_method, a):
    mo_state.append("a")
    return next_method(a)
示例#17
0
import unittest

from dispatch import generic

from turbogears.genericfunctions import *


mo_state = []

def mo(a):
    pass
mo = generic(MultiorderGenericFunction)(mo)

def mo2(next_method, a):
    mo_state.append(2)
mo2 = mo.when("a>0", order=2)(mo2)

def mo0(next_method, a):
    mo_state.append(0)
    return next_method(a)
mo0 = mo.when("a>0")(mo0)

def mo1(next_method, a):
    mo_state.append(1)
    return next_method(a)
mo1 = mo.when("a>0", order=1)(mo1)

def moa0(next_method, a):
    mo_state.append("a")
    return next_method(a)
moa0 = mo.around("a<23")(moa0)
示例#18
0
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import dispatch

def create(class_, **kw):
    "Returns a new class_ object created using the keyword arguments."
    raise NotImplementedError
create = dispatch.generic()(create)

def retrieve(class_, **kw):
    """Returns a list of existing class_ objects using the keyword arguments.
    
    Should return an empty list if there are no matching objects.
    If no keywords are provided, should return all class_ objects."""
    raise NotImplementedError
retrieve = dispatch.generic()(retrieve)

def retrieve_one(class_, **kw):
    """Returns a single class_ object using the keyword arguments.
    
    Should return None if there is no matching object.
    Should raise a LookupError when more than one object
    matches."""
示例#19
0
from turbogears.util import inject_args, adapt_call, call_on_stack, has_arg, \
                            remove_keys, Enum, combine_contexts
from turbogears.decorator import func_eq
from turbogears.genericfunctions import MultiorderGenericFunction


default = strategy.default

def dispatch_error(controller, tg_source, tg_errors, tg_exceptions,
                   *args, **kw):
    """Dispatch error.

    Error handler is a function registered via register_handler or if no
    such decorator was applied, the method triggering the error.
    """
dispatch_error = generic(MultiorderGenericFunction)(dispatch_error)

def _register_implicit_errh(controller, tg_source, tg_errors,
                                     tg_exceptions, *args, **kw):
    """Register implicitly declared error handler and re-dispatch.

    Any method declaring tg_errors parameter is considered an implicitly
    declared error handler.
    """
    error_handler(tg_source)(tg_source)
    return dispatch_error(controller, tg_source, tg_errors, tg_exceptions,
                          *args, **kw)
_register_implicit_errh = dispatch_error.when(
    "(tg_errors and has_arg(tg_source, 'tg_errors'))", order=3)(
    _register_implicit_errh)
示例#20
0
        hub.commit()


def rollback_all():
    """Rollback the transactions in all registered hubs (for this thread)."""
    for hub in hub_registry:
        hub.rollback()


def end_all():
    """End the transactions in all registered hubs (for this thread)."""
    for hub in hub_registry:
        hub.end()


[dispatch.generic(MultiorderGenericFunction)]


def run_with_transaction(func, *args, **kw):
    pass


[dispatch.generic(MultiorderGenericFunction)]


def restart_transaction(args):
    pass


def _use_sa(args=None):
    # check to see if sqlalchemy has been imported and configured
示例#21
0
# @@: This is experimental
import warnings
warnings.warn("formencode.formgen is deprecated with no replacement; "
              "if you are using it please maintain your own copy of this "
              "file", DeprecationWarning, 2)

import fields

dispatch = None
try:
    import pkg_resources
    pkg_resources.require('RuleDispatch')
    import dispatch
except ImportError:
    pass

if dispatch:
    #@dispatch.generic()
    def makeform(obj, context):
        """
        Return ``(field_obj, Schema)``.

        Return a field or field container used to edit ``obj`` given the
        context.  Also return a Schema object (or None for no Schema) that
        will be applied before other validation.
        """
        raise NotImplementedError

    makeform = dispatch.generic()(makeform)

示例#22
0
import unittest

from dispatch import generic

from turbogears.genericfunctions import *

mo_state = []

[generic(MultiorderGenericFunction)]


def mo(a):
    pass


[mo.when("a>0", order=2)]


def mo2(next_method, a):
    mo_state.append(2)


[mo.when("a>0")]


def mo0(next_method, a):
    mo_state.append(0)
    return next_method(a)


[mo.when("a>0", order=1)]
示例#23
0
# @@: This is experimental
import warnings
warnings.warn(
    "formencode.formgen is deprecated with no replacement; "
    "if you are using it please maintain your own copy of this "
    "file", DeprecationWarning, 2)

import fields

dispatch = None
try:
    import pkg_resources
    pkg_resources.require('RuleDispatch')
    import dispatch
except ImportError:
    pass

if dispatch:
    #@dispatch.generic()
    def makeform(obj, context):
        """
        Return ``(field_obj, Schema)``.

        Return a field or field container used to edit ``obj`` given the
        context.  Also return a Schema object (or None for no Schema) that
        will be applied before other validation.
        """
        raise NotImplementedError

    makeform = dispatch.generic()(makeform)
示例#24
0
文件: jsonify.py 项目: thraxil/gtreed
    import decimal
except ImportError:
    # Python 2.3
    decimal = None


def jsonify(obj):
    """
    Return an object that can be serialized with JSON, i.e., it
    is made up of only lists, dictionaries (with string keys),
    and strings, ints, and floats.
    """
    raise NotImplementedError


jsonify = dispatch.generic()(jsonify)


def jsonify_datetime(obj):
    return str(obj)


jsonify_datetime = jsonify.when("isinstance(obj, datetime.datetime) or " "isinstance(obj, datetime.date)")(
    jsonify_datetime
)


def jsonify_decimal(obj):
    return float(obj)

示例#25
0
def commit_all():
    "Commits the Transactions in all registered hubs (for this thread)"
    for hub in hub_registry:
        hub.commit()

def rollback_all():
    "Rolls back the Transactions in all registered hubs (for this thread)"
    for hub in hub_registry:
        hub.rollback()

def end_all():
    "Ends the Transactions in all registered hubs (for this thread)"
    for hub in hub_registry:
        hub.end()

[dispatch.generic(MultiorderGenericFunction)]
def run_with_transaction(func, *args, **kw):
    pass

def _use_sa(args=None):
    # check to see if sqlalchemy has been imported and configured
    return _engine is not None

[run_with_transaction.when("not _use_sa(args)")] # include "args" to avoid call being pre-cached
def so_rwt(func, *args, **kw):
    log.debug("Starting SQLObject transaction")
    try:
        try:
            retval = func(*args, **kw)
            commit_all()
            return retval
示例#26
0
import dispatch
from turbogears import config
from turbogears.util import get_model
try:
    from sqlalchemy import MetaData, exceptions, Table, String, Unicode
    from turbogears.database import metadata, get_engine
except ImportError:  # if not available, complain only at run-time
    get_engine = None
else:
    try:
        from sqlalchemy import Text, UnicodeText
    except ImportError:  # SQLAlchemy < 0.4.3
        Text, UnicodeText = String, Unicode

[dispatch.generic()]


def sacommand(command, args):
    pass


[sacommand.around("command and command != 'help' and not get_engine")]


def no_engine(command, args):
    print "Error: SQLAlchemy not installed."


[sacommand.when("command == 'help'")]

示例#27
0
import dispatch
from turbogears import config
from turbogears.util import get_model
try:
    from sqlalchemy import MetaData, exceptions, Table, String, Unicode
    from turbogears.database import metadata, get_engine
except ImportError: # if not available, complain only at run-time
    get_engine = None
else:
    try:
        from sqlalchemy import Text, UnicodeText
    except ImportError: # SQLAlchemy < 0.4.3
        Text, UnicodeText = String, Unicode

[dispatch.generic()]
def sacommand(command, args):
    pass

[sacommand.around("command and command != 'help' and not get_engine")]
def no_engine(command, args):
    print "Error: SQLAlchemy not installed."

[sacommand.when("command == 'help'")]
def help(command, args):
    print """TurboGears SQLAlchemy Helper

tg-admin sql command [options]

Available commands:
    create  Create tables
    execute Execute SQL statements
示例#28
0
文件: field.py 项目: Schevo/schevosql
"""Schevo field SQL operations.

For copyright, license, and warranty, see bottom of file.
"""

from dispatch import generic

from schevo.constant import UNASSIGNED
from schevo import field as F


[generic()]
def to_colspec(dialect, field):
    """Return a tuple of (specs, constraints) for the field."""


[generic()]
def to_data(dialect, field):
    """Return a tuple of (col name, value) suitable for INSERT."""


# --------------------------------------------------------------------


[to_colspec.when("dialect == 'jet' and isinstance(field, F.Field)")]
def to_colspec(dialect, field):
    if field.max_size is not None:
        max_size = '(%i)' % field.max_size
    else:
        max_size = ''
    specs = [