Beispiel #1
0
    def test_same_url(self):

        class TestSameUrlSpider(Spider):
            name = 'test_same_url'

            def __init__(self, *args, **kwargs):
                super(TestSameUrlSpider, self).__init__(*args, **kwargs)
                self.visited = 0

            def start_requests(s):
                return self.conman.from_spider(s, self.results)

            def parse_first(self, response):
                self.visited += 1
                return TestItem()

            def parse_second(self, response):
                self.visited += 1
                return TestItem()

        with MockServer() as mockserver:
            contract_doc = '@url {}'.format(mockserver.url('/status?n=200'))

            get_unbound_function(TestSameUrlSpider.parse_first).__doc__ = contract_doc
            get_unbound_function(TestSameUrlSpider.parse_second).__doc__ = contract_doc

            crawler = CrawlerRunner().create_crawler(TestSameUrlSpider)
            yield crawler.crawl()

        self.assertEqual(crawler.spider.visited, 2)
    def test_same_url(self):
        class TestSameUrlSpider(Spider):
            name = 'test_same_url'

            def __init__(self, *args, **kwargs):
                super(TestSameUrlSpider, self).__init__(*args, **kwargs)
                self.visited = 0

            def start_requests(s):
                return self.conman.from_spider(s, self.results)

            def parse_first(self, response):
                self.visited += 1
                return TestItem()

            def parse_second(self, response):
                self.visited += 1
                return TestItem()

        with MockServer() as mockserver:
            contract_doc = '@url {}'.format(mockserver.url('/status?n=200'))

            get_unbound_function(
                TestSameUrlSpider.parse_first).__doc__ = contract_doc
            get_unbound_function(
                TestSameUrlSpider.parse_second).__doc__ = contract_doc

            crawler = CrawlerRunner().create_crawler(TestSameUrlSpider)
            yield crawler.crawl()

        self.assertEqual(crawler.spider.visited, 2)
Beispiel #3
0
    def wrapped(cls):
        applies_to = set([])
        classess_to_apply = [c for c in classess if not skip_classess or c not in skip_classess]
        if add_classess:
            classess_to_apply += [c for c in add_classess if not skip_classess or c not in skip_classess]

        for autodoc_class in classess_to_apply:
            applies_to |= set(autodoc_class.applies_to)

        # Create facades for original methods - docstring of methods are immutable, so we need to change docstring of
        # functions. But without shadowing the method.__func__ will point to the same function for classes that
        # inherits them from the same parents.
        for method_name in applies_to:
            method = getattr(cls, method_name, None)
            if method:
                copy_method(cls, method_name, method)

        # update docstrings
        for autodoc_class in classess_to_apply:
            for method_name in autodoc_class.applies_to:
                method = getattr(cls, method_name, None)
                if method:
                    six.get_unbound_function(method).__doc__ = \
                        autodoc_class.update_docstring(cls, base_doc, six.get_unbound_function(method).__doc__,
                                                       method_name)
        return cls
Beispiel #4
0
class Helper(object):
    """Helper class."""

    begin_goodjson = six.get_unbound_function(gj_doc.Helper.begin_goodjson)
    __set_gj_flag_sub_field = six.get_unbound_function(
        gj_doc.Helper.__set_gj_flag_sub_field)
    __unset_gj_flag_sub_field = six.get_unbound_function(
        gj_doc.Helper.__unset_gj_flag_sub_field)
Beispiel #5
0
 def _parse(*a):
     if a[0] in builtin_x:
         x = getattr(A.X, a[0])
         # Get the function out of unbound method.
         # In Python 3, unbound methods don't exist, so this function
         # just returns the function object unchanged.
         return six.get_unbound_function(x)(*[A.Y._alias_field(f) for f in a[1:]]) if callable(x) else x
     else:
         return six.get_unbound_function(A.X._)(*a)
Beispiel #6
0
def getdefiningclass(m, owner_class):
  """Resolves the class (e.g. one of the superclasses) that defined a method."""
  m = six.get_unbound_function(m)
  last_defining = owner_class
  for superclass in tf_inspect.getmro(owner_class):
    if hasattr(superclass, m.__name__):
      superclass_m = getattr(superclass, m.__name__)
      if six.get_unbound_function(superclass_m) == m:
        last_defining = superclass
  return last_defining
Beispiel #7
0
def test_replace():
    """Replaced methods replace the original one, but are restored after the with."""
    class SomethingElse(object):
        def foo(self, n, y=None):
            assert None, 'This should never be reached in this test'

    # Case: bound method
    s = SomethingElse()

    def replacement(n, y=None):
        return y

    original_method = six.get_method_function(s.foo)

    with replaced(s.foo, replacement):
        assert s.foo(1, y='a') == 'a'
        assert s.foo(2) == None

    assert six.get_method_function(s.foo) is original_method

    # Case: unbound method
    """Python 3 does not support the concept of unbound methods, they are
    just plain functions without an im_class pointing back to their class.
    See https://docs.python.org/3/whatsnew/3.0.html#operators-and-special-methods,
    and https://mail.python.org/pipermail/python-dev/2005-January/050625.html
    for the rationale.

    To be able to support them under Python3, on= is mandatory.
    """

    s = SomethingElse()

    def replacement(self, n, y=None):
        return y

    original_method = six.get_unbound_function(SomethingElse.foo)

    with replaced(SomethingElse.foo, replacement, on=SomethingElse):
        assert s.foo(1, y='a') == 'a'
        assert s.foo(2) == None

    restored_method = six.get_unbound_function(SomethingElse.foo)
    assert restored_method is original_method

    # Case: unbound method (no on= given)
    s = SomethingElse()

    def replacement(self, n, y=None):
        return y

    with pytest.raises(
            ValueError,
            match='You have to supply a on= when stubbing an unbound method'):
        with replaced(SomethingElse.foo, replacement):
            pass
Beispiel #8
0
class TimerServiceMixin(object):

    security = ClassSecurityInfo()

    security.declareProtected(Permissions.AccessContentsInformation,
                              'isSubscribed')

    def isSubscribed(self):
        """Return True if we are subscribed to TimerService, otherwise return False
    """
        service = getTimerService(self)
        return service and \
          '/'.join(self.getPhysicalPath()) in service.lisSubscriptions()

    security.declareProtected(Permissions.ManageProperties, 'subscribe')

    def subscribe(self):
        """Subscribe to the global Timer Service"""
        service = getTimerService(self)
        if service:
            service.subscribe(self)
            return "Subscribed to Timer Service"
        return "TimerService not available"

    security.declareProtected(Permissions.ManageProperties, 'unsubscribe')

    def unsubscribe(self):
        """Unsubscribe from the global Timer Service"""
        service = getTimerService(self)
        if service:
            service.unsubscribe(self)
            return "Usubscribed from Timer Service"
        return "TimerService not available"

    security.declarePrivate('manage_beforeDelete')

    def manage_beforeDelete(self, *args, **kw):
        self.unsubscribe()
        super(TimerServiceMixin, self).manage_beforeDelete(*args, **kw)

    security.declarePrivate('manage_afterAdd')

    def manage_afterAdd(self, *args, **kw):
        self.subscribe()
        super(TimerServiceMixin, self).manage_afterAdd(*args, **kw)

    security.declarePublic('getCurrentNode')
    getCurrentNode = six.get_unbound_function(ActivityTool.getCurrentNode)
    security.declarePublic('getServerAddress')
    getServerAddress = six.get_unbound_function(ActivityTool.getServerAddress)

    _isValidNodeName = six.get_unbound_function(ActivityTool._isValidNodeName)
Beispiel #9
0
    def __new__(cls, obj, recursive=False):
        self = object.__new__(cls)
        obj = aq_base(obj)
        connection = obj._p_jar
        ObjectReader.__init__(self, connection, connection._cache,
                              connection._db.classFactory)
        ObjectWriter.__init__(self, obj)
        migrated_oid_set = set()
        oid_set = {obj._p_oid}
        while oid_set:
            oid = oid_set.pop()
            obj = ObjectReader.load_oid(self, oid)
            obj._p_activate()
            klass = obj.__class__
            self.lazy = None
            if not recursive:
                _setOb = getattr(klass, '_setOb', None)
                if _setOb:
                    if isinstance(_setOb, WorkflowMethod):
                        _setOb = _setOb._m
                    import six
                    if six.get_unbound_function(
                            _setOb) is six.get_unbound_function(
                                OFS_Folder._setOb):
                        self.lazy = Ghost
                elif klass.__module__[:
                                      7] == 'BTrees.' and klass.__name__ != 'Length':
                    self.lazy = LazyBTree()
            self.oid_dict = {}
            self.oid_set = set()
            p, serial = self._conn._storage.load(oid, '')
            unpickler = self._get_unpickler(p)

            def find_global(*args):
                self.do_migrate = args != (klass.__module__, klass.__name__) and \
                                  not isOldBTree('%s.%s' % args)
                unpickler.find_global = self._get_class
                return self._get_class(*args)

            unpickler.find_global = find_global
            unpickler.load()  # class
            state = unpickler.load()
            if isinstance(self.lazy, LazyPersistent):
                self.oid_set.update(self.lazy.getOidList(state))
            migrated_oid_set.add(oid)
            oid_set |= self.oid_set - migrated_oid_set
            self.oid_set = None
            if self.do_migrate:
                log.debug('PickleUpdater: migrate %r (%r)', obj, klass)
                self.setGhostState(obj, self.serialize(obj))
                obj._p_changed = 1
Beispiel #10
0
def _load_ui_into_display(uifile, display):
    klass, _ = uic.loadUiType(uifile)

    # Python 2.7 compatibility. More info at the following links:
    # https://github.com/universe-proton/universe-topology/issues/3
    # https://stackoverflow.com/questions/3296993/python-how-to-call-unbound-method-with-other-type-parameter
    retranslateUi = six.get_unbound_function(klass.retranslateUi)
    setupUi = six.get_unbound_function(klass.setupUi)

    # Add retranslateUi to Display class
    display.retranslateUi = functools.partial(retranslateUi, display)
    setupUi(display, display)

    display.ui = display
Beispiel #11
0
 def can_validate_otp(self):
     """If the interface is able to validate OTP codes then this returns
     `True`.
     """
     return self.validate_otp.__func__ is not six.get_unbound_function(
         AuthenticatorInterface.validate_otp
     )
Beispiel #12
0
def monkey_mix(cls, mixin, methods=None):
    """
    Mixes a mixin into existing class.
    Does not use actual multi-inheritance mixins, just monkey patches methods.
    Mixin methods can call copies of original ones stored in `_no_monkey` proxy:

    class SomeMixin(object):
        def do_smth(self, arg):
            ... do smth else before
            self._no_monkey.do_smth(self, arg)
            ... do smth else after
    """
    assert '_no_monkey' not in cls.__dict__, 'Multiple monkey mix not supported'
    cls._no_monkey = MonkeyProxy(cls)

    if methods is None:
        # NOTE: there no such thing as unbound method in Python 3, it uses naked functions,
        #       so we use some six based altering here
        isboundmethod = inspect.isfunction if six.PY3 else inspect.ismethod
        methods = inspect.getmembers(mixin, isboundmethod)
    else:
        methods = [(m, getattr(mixin, m)) for m in methods]

    for name, method in methods:
        if hasattr(cls, name):
            setattr(cls._no_monkey, name, getattr(cls, name))
        # NOTE: remember, there is no bound methods in Python 3
        setattr(cls, name, six.get_unbound_function(method))
Beispiel #13
0
class MappingProperty(AnnotationMixin, QueryableProperty):
    """
    A property that translates values of an attribute into other values using
    defined mappings.
    """

    # Copy over Django's implementation to forcibly evaluate a lazy value.
    _force_value = six.get_unbound_function(Field.get_prep_value)

    def __init__(self,
                 attribute_path,
                 output_field,
                 mappings,
                 default=None,
                 **kwargs):
        """
        Initialize a property that maps values from an attribute to other
        values.

        :param str attribute_path: The name of the attribute to compare
                                   against. May also be a more complex path to
                                   a related attribute using dot-notation (like
                                   with :func:`operator.attrgetter`). If an
                                   intermediate value on the path is None, it
                                   will be treated as "no match" instead of
                                   raising an exception. The behavior is the
                                   same if an intermediate value raises an
                                   ``ObjectDoesNotExist`` error.
        :param django.db.models.Field output_field: The field to represent the
                                                    mapped values in querysets.
        :param mappings: An iterable containing 2-tuples that represent the
                         mappings to use (the first value of each tuple is
                         mapped to the second value).
        :type mappings: collections.Iterable[(object, object)]
        :param default: A default value to return/use in querysets when in case
                        none of the mappings match an encountered value.
                        Defaults to None.
        """
        super(MappingProperty, self).__init__(**kwargs)
        self.attribute_getter = ModelAttributeGetter(attribute_path)
        self.output_field = output_field
        self.mappings = mappings
        self.default = default

    def get_value(self, obj):
        attibute_value = self.attribute_getter.get_value(obj)
        for from_value, to_value in self.mappings:
            if attibute_value == from_value:
                return self._force_value(to_value)
        return self._force_value(self.default)

    def get_annotation(self, cls):
        from django.db.models import Case, Value, When

        cases = (When(self.attribute_getter.build_filter('exact', from_value),
                      then=Value(self._force_value(to_value)))
                 for from_value, to_value in self.mappings)
        return Case(*cases,
                    default=Value(self._force_value(self.default)),
                    output_field=self.output_field)
Beispiel #14
0
 def get_validator(self, name, **kwargs):
     attr_name = '%s_validator' % name
     attr = getattr(self.meta, attr_name)
     if inspect.ismethod(attr):
         return six.get_unbound_function(attr)(**kwargs)
     else:
         return attr(**kwargs)
Beispiel #15
0
def _is_known_loaded_type(f, module_name, entity_name):
  """Tests whether the function or method is an instance of a known type."""
  if (module_name not in sys.modules or
      not hasattr(sys.modules[module_name], entity_name)):
    return False
  type_entity = getattr(sys.modules[module_name], entity_name)
  if isinstance(f, type_entity):
    # The method if of this type. Example:
    #
    # o = ClassType()
    # function(o.method)()
    return True
  if tf_inspect.ismethod(f):
    f = six.get_unbound_function(f)
    # The the unbound method if of this type. Example:
    #
    # class ClassType:
    #   @function
    #   def method(self):
    #     ...
    # o = ClassType()
    # o.method()
    if isinstance(f, type_entity):
      return True
  return False
Beispiel #16
0
def _is_known_loaded_type(f, module_name, entity_name):
    """Tests whether the function or method is an instance of a known type."""
    if (module_name not in sys.modules
            or not hasattr(sys.modules[module_name], entity_name)):
        return False
    type_entity = getattr(sys.modules[module_name], entity_name)
    if isinstance(f, type_entity):
        # The method if of this type. Example:
        #
        # o = ClassType()
        # function(o.method)()
        return True
    # Note: inspect is required here, to avoid unpacking tf.function decorators.
    if inspect.ismethod(f):
        f = six.get_unbound_function(f)
        # The the unbound method if of this type. Example:
        #
        # class ClassType:
        #   @function
        #   def method(self):
        #     ...
        # o = ClassType()
        # o.method()
        if isinstance(f, type_entity):
            return True
    return False
Beispiel #17
0
 def _parse(*a):
     if a[0] in builtin_y:
         y = getattr(A.Y, a[0])
         return six.get_unbound_function(y)(
             *a[1:]) if callable(y) else y
     else:
         return a[0]
Beispiel #18
0
def monkey_mix(cls, mixin, methods=None):
    """
    Mixes a mixin into existing class.
    Does not use actual multi-inheritance mixins, just monkey patches methods.
    Mixin methods can call copies of original ones stored in `_no_monkey` proxy:

    class SomeMixin(object):
        def do_smth(self, arg):
            ... do smth else before
            self._no_monkey.do_smth(self, arg)
            ... do smth else after
    """
    assert '_no_monkey' not in cls.__dict__, 'Multiple monkey mix not supported'
    cls._no_monkey = MonkeyProxy(cls)

    if methods is None:
        # NOTE: there no such thing as unbound method in Python 3, it uses naked functions,
        #       so we use some six based altering here
        isboundmethod = inspect.isfunction if six.PY3 else inspect.ismethod
        methods = inspect.getmembers(mixin, isboundmethod)
    else:
        methods = [(m, getattr(mixin, m)) for m in methods]

    for name, method in methods:
        if hasattr(cls, name):
            setattr(cls._no_monkey, name, getattr(cls, name))
        # NOTE: remember, there is no bound methods in Python 3
        setattr(cls, name, six.get_unbound_function(method))
Beispiel #19
0
 def requires_activation(self):
     """If the interface has an activation method that needs to be
     called this returns `True`.
     """
     return self.activate.__func__ is not six.get_unbound_function(
         AuthenticatorInterface.activate
     )
Beispiel #20
0
 def get_validator(self, name, **kwargs):
     attr_name = '%s_validator' % name
     attr = getattr(self.meta, attr_name)
     if inspect.ismethod(attr):
         return six.get_unbound_function(attr)(**kwargs)
     else:
         return attr(**kwargs)
Beispiel #21
0
class MysqlRefsContainer(RefsContainer):
    """RefsContainer backed by MySql.

    This container does not support packed references.
    """
    def __init__(self, repo):
        super(MysqlRefsContainer, self).__init__()
        self._repo = repo

    get_packed_refs = get_unbound_function(DictRefsContainer.get_packed_refs)

    def allkeys(self):
        for ref in Refs.objects.filter(repo=self._repo).only('ref').iterator():
            yield ref.ref

    def read_loose_ref(self, name):
        qs = Refs.objects.only('value')
        if not get_autocommit(using=qs._db):
            qs = qs.select_for_update()
        try:
            ref = qs.get(repo=self._repo, ref=name)
        except Refs.DoesNotExist:
            return None
        else:
            return ref.value

    def set_symbolic_ref(self, name, other):
        self._update_ref(name, SYMREF + other)

    def set_if_equals(self, name, old_ref, new_ref):
        if old_ref is not None and self.read_loose_ref(name) != old_ref:
            return False
        realnames, _ = self.follow(name)
        for realname in realnames:
            self._check_refname(realname)
            self._update_ref(realname, new_ref)
        return True

    def add_if_new(self, name, ref):
        if self.read_loose_ref(name):
            return False
        self._update_ref(name, ref)
        return True

    def remove_if_equals(self, name, old_ref):
        if old_ref is not None and self.read_loose_ref(name) != old_ref:
            return False
        self._remove_ref(name)
        return True

    def _update_ref(self, name, value):
        Refs.objects.update_or_create(repo=self._repo,
                                      ref=name,
                                      defaults={
                                          'value': value,
                                      })

    def _remove_ref(self, name):
        Refs.objects.filter(repo=self._repo, ref=name).delete()
Beispiel #22
0
def _update_class(oldclass, newclass):
    """Update a class object."""
    # XXX What about __slots__?
    olddict = oldclass.__dict__
    newdict = newclass.__dict__
    oldnames = set(olddict)
    newnames = set(newdict)
    for name in newnames - oldnames:
        setattr(oldclass, name, newdict[name])

    # Note: We do not delete attributes, because various ZCML directives,
    # grokkers and other wiring add class attributes during startup that
    # would get lost if we did this. Note that attributes will still be
    # overwritten if they've changed.
    #
    # for name in oldnames - newnames:
    #     delattr(oldclass, name)

    for name in oldnames & newnames - CLASS_STATICS:
        try:
            new = getattr(newclass, name)
            old = getattr(oldclass, name, None)
            if isinstance(new, (types.FunctionType, types.MethodType)):
                if isinstance(old, property) and not isinstance(new, property):
                    # Removing a decorator
                    setattr(oldclass, name, six.get_unbound_function(new))
                elif isinstance(new, types.FunctionType):
                    # Under Py3 there are only functions
                    _update_function(old, new)
                elif isinstance(new, types.MethodType):
                    # Py2-only
                    _update_method(old, new)
            else:
                new2 = newdict.get(name)
                if new is not new2:
                    # Do we have some sort of descriptor? Set the underlying
                    # descriptor and not the result of the descriptor call
                    setattr(oldclass, name, new2)
                else:
                    # Fallback to just replace the item
                    setattr(oldclass, name, new)
        except ClosureChanged:
            # If the closure changed, we need to replace the entire function
            setattr(oldclass, name, six.get_unbound_function(new))

    return oldclass
Beispiel #23
0
    def on_bound(cls, app):
        # Set up celery beat entry after celery app initialization is done.
        enabled = cls._enabled
        if callable(enabled):
            enabled = get_unbound_function(enabled)(app.app_config)

        if enabled and cls._schedule:
            app.conf.CELERYBEAT_SCHEDULE.update(cls.beat_config())
Beispiel #24
0
def _update_class(oldclass, newclass):
    """Update a class object."""
    # XXX What about __slots__?
    olddict = oldclass.__dict__
    newdict = newclass.__dict__
    oldnames = set(olddict)
    newnames = set(newdict)
    for name in newnames - oldnames:
        setattr(oldclass, name, newdict[name])

    # Note: We do not delete attributes, because various ZCML directives,
    # grokkers and other wiring add class attributes during startup that
    # would get lost if we did this. Note that attributes will still be
    # overwritten if they've changed.
    #
    # for name in oldnames - newnames:
    #     delattr(oldclass, name)

    for name in oldnames & newnames - CLASS_STATICS:
        try:
            new = getattr(newclass, name)
            old = getattr(oldclass, name, None)
            if isinstance(new, (types.FunctionType, types.MethodType)):
                if isinstance(old, property) and not isinstance(new, property):
                    # Removing a decorator
                    setattr(oldclass, name, six.get_unbound_function(new))
                elif isinstance(new, types.FunctionType):
                    # Under Py3 there are only functions
                    _update_function(old, new)
                elif isinstance(new, types.MethodType):
                    # Py2-only
                    _update_method(old, new)
            else:
                new2 = newdict.get(name)
                if new is not new2:
                    # Do we have some sort of descriptor? Set the underlying
                    # descriptor and not the result of the descriptor call
                    setattr(oldclass, name, new2)
                else:
                    # Fallback to just replace the item
                    setattr(oldclass, name, new)
        except ClosureChanged:
            # If the closure changed, we need to replace the entire function
            setattr(oldclass, name, six.get_unbound_function(new))

    return oldclass
Beispiel #25
0
    def test_namreply_no_channel(self):
        """
        If channel is '*', _on_namreply should not crash.

        Regression test for #22
        """
        event = irc.client.Event(type=None, source=None, target=None, arguments=["*", "*", "nick"])
        _on_namreply = six.get_unbound_function(irc.bot.SingleServerIRCBot._on_namreply)
        _on_namreply(None, None, event)
Beispiel #26
0
def _instance_overrides_method(base, instance, method_name):
    """
    Returns True if instance overrides a method (method_name)
    inherited from base.
    """
    bound_method = getattr(instance, method_name)
    unbound_method = getattr(base, method_name)
    return get_unbound_function(unbound_method) != get_method_function(
        bound_method)
Beispiel #27
0
def patch():
    import six

    import traceback
    from unittest import TextTestResult, TextTestRunner

    TextTestResult_addError = six.get_unbound_function(TextTestResult.addError)
    def addError(self, test, err):
        if isinstance(err[1], SetupSiteError):
            self.errors.append(None)
        elif isinstance(err[1], SystemExit):
            raise err
        else:
            TextTestResult_addError(self, test, err)
    TextTestResult.addError = addError

    def wasSuccessful(self):
        "Tells whether or not this result was a success"
        return not (self.failures or self.errors or self.unexpectedSuccesses)
    TextTestResult.wasSuccessful = wasSuccessful

    def printErrors(self):
        if self.dots or self.showAll:
            self.stream.writeln()
        # 'None' correspond to redundant errors due to site creation errors,
        # and we do not display them here.
        self.printErrorList('ERROR', filter(None, self.errors))
        self.printErrorList('FAIL', self.failures)
        if self.unexpectedSuccesses:
          self.stream.writeln(self.separator1)
          for test in self.unexpectedSuccesses:
            self.stream.writeln("SUCCESS: %s" % self.getDescription(test))
    TextTestResult.printErrors = printErrors

    TextTestRunner_run = six.get_unbound_function(TextTestRunner.run)
    def run(self, test):
        def t(result):
            try:
                test(result)
            except (KeyboardInterrupt, SystemExit):
                traceback.print_exc()
        return TextTestRunner_run(self, t)
    TextTestRunner.run = run
Beispiel #28
0
    def test_namreply_no_channel(self):
        """
        If channel is '*', _on_namreply should not crash.

        Regression test for #22
        """
        event = irc.client.Event(type=None, source=None, target=None,
            arguments=['*', '*', 'nick'])
        _on_namreply = six.get_unbound_function(
            irc.bot.SingleServerIRCBot._on_namreply)
        _on_namreply(None, None, event)
Beispiel #29
0
def update_docstrings(klass):
    super_klass = super(klass, klass)
    for property in dir(klass):
        if property.startswith('t_'):
            source = getattr(super_klass, property, None)
            if callable(source):
                destination = getattr(klass, property)
                assert callable(destination)
                destination = six.get_unbound_function(destination)
                if destination.__doc__ is None:
                    destination.__doc__ = source.__doc__
Beispiel #30
0
 def __new__(cls):
     self = object.__new__(cls)
     self._connection = os.getenv(
         'erp5_sql_connection_string') or 'test test'
     self.conv = None
     parse_connection_string_function = six.get_unbound_function(
         DB._parse_connection_string)
     parse_connection_string_function(self)
     return ''.join('-%s%s ' % (self.args_dict[k], v)
                    for k, v in six.iteritems(self._kw_args)
                    if k in self.args_dict) + self._kw_args['db']
Beispiel #31
0
def load_ui_file(uifile, macros=None):
    """
    Load a .ui file, perform macro substitution, then return the resulting QWidget.

    This is an internal method, users will usually want to use `open_file` instead.

    Parameters
    ----------
    uifile : str
        The path to a .ui file to load.
    macros : dict, optional
        A dictionary of macro variables to supply to the file
        to be opened.

    Returns
    -------
    QWidget
    """

    d = Display(macros=macros)
    if macros:
        f = macro.substitute_in_file(uifile, macros)
    else:
        f = uifile

    klass, _ = uic.loadUiType(f)

    # Python 2.7 compatibility. More info at the following links:
    # https://github.com/universe-proton/universe-topology/issues/3
    # https://stackoverflow.com/questions/3296993/python-how-to-call-unbound-method-with-other-type-parameter
    retranslateUi = six.get_unbound_function(klass.retranslateUi)
    setupUi = six.get_unbound_function(klass.setupUi)

    # Add retranslateUi to Display class
    d.retranslateUi = functools.partial(retranslateUi, d)
    d._loaded_file = uifile
    setupUi(d, d)

    d.ui = d

    return d
    def test_getter(self, old_getter, init_kwargs, old_docstring,
                    new_docstring, kwargs):
        original = queryable_property(old_getter, **init_kwargs)
        if old_docstring is not None:
            original.__doc__ = old_docstring

        def func():
            pass

        func.__doc__ = new_docstring

        clone = self.decorate_function(func, original.getter, kwargs)
        changed_attrs = dict(kwargs or {},
                             get_value=func,
                             __doc__=new_docstring or old_docstring)
        if init_kwargs.get('annotation_based', False):
            changed_attrs['get_filter'] = six.create_bound_method(
                six.get_unbound_function(AnnotationMixin.get_filter), clone)
            changed_attrs['get_annotation'] = six.create_bound_method(
                six.get_unbound_function(AnnotationMixin.get_annotation),
                clone)
        self.assert_cloned_property(original, clone, changed_attrs)
Beispiel #33
0
 def test_taskset_inheritance(self):
     def t1(l):
         pass
     class MyBaseTaskSet(TaskSet):
         tasks = [t1]
         host = ""
     class MySubTaskSet(MyBaseTaskSet):
         @task
         def t2(self):
             pass
     
     l = MySubTaskSet(self.locust)
     self.assertEqual(2, len(l.tasks))
     self.assertEqual([t1, six.get_unbound_function(MySubTaskSet.t2)], l.tasks)
Beispiel #34
0
 def test_taskset_inheritance(self):
     def t1(l):
         pass
     class MyBaseTaskSet(TaskSet):
         tasks = [t1]
         host = ""
     class MySubTaskSet(MyBaseTaskSet):
         @task
         def t2(self):
             pass
     
     l = MySubTaskSet(self.locust)
     self.assertEqual(2, len(l.tasks))
     self.assertEqual([t1, six.get_unbound_function(MySubTaskSet.t2)], l.tasks)
Beispiel #35
0
    def plot_ratio(self, target_axes, error_contributions=('data',), **kwargs):
        """
        Plot the data/model ratio to a specified ``matplotlib`` ``Axes`` object.

        :param target_axes: ``matplotlib`` ``Axes`` object
        :param kwargs: keyword arguments accepted by the ``matplotlib`` methods ``errorbar`` or ``plot``
        :return: plot handle(s)
        """
        return six.get_unbound_function(XYPlotAdapter.plot_ratio)(
            self,
            target_axes=target_axes,
            error_contributions=error_contributions,
            **kwargs
        )
Beispiel #36
0
 def __getattr__(self, name):
     if name in (_[0] for _ in getmembers(UserEditable, predicate=isroutine)) and \
             self.is_content_editable:
         self._content_editable = True
         setattr(
             self, name,
             six.create_bound_method(
                 six.get_unbound_function(getattr(UserEditable, name)),
                 self))
         return getattr(self, name)
     else:
         raise AttributeError("Element '{}' has no attribute "
                              "'{}'".format(
                                  self.__class__.__name__.capitalize(),
                                  name))
def fetch_cls_init(cls):
    """Return reference to the class.__init__() method if it is defined.

    :param cls: Class instance
    :type cls: type

    :return: Reference to the class.__init__() if any, or None otherwise.
    :rtype: unbound method | None
    """
    try:
        cls_init = six.get_unbound_function(cls.__init__)
        assert cls_init is not _OBJECT_INIT
    except (AttributeError, AssertionError):
        return None
    else:
        return cls_init
Beispiel #38
0
    def _getFunction(self, reload=False):
        import erp5.component.extension
        component_module = erp5.component.extension.find_load_module(
            self._module)
        if component_module is None:
            # Fall back on filesystem
            if not reload:
                from Globals import DevelopmentMode
                if DevelopmentMode:
                    try:
                        last_read, path = self._v_fs
                    except AttributeError:
                        last_read = None
                        path = getPath('Extensions',
                                       self._module,
                                       suffixes=('', 'py', 'pyc'))
                    ts = os.stat(path)[stat.ST_MTIME]
                    if last_read != ts:
                        self._v_fs = ts, path
                        reload = True
            f = getObject(self._module, self._function, reload)
        else:
            f = getattr(component_module, self._function)
        try:
            _f = self._v_f
            if _f[0] is f:
                return _f
        except AttributeError:
            pass
        code = f.func_code
        argument_object = getargs(code)
        # reconstruct back the original names
        arg_list = argument_object.args[:]
        if argument_object.varargs:
            arg_list.append('*' + argument_object.varargs)
        if argument_object.keywords:
            arg_list.append('**' + argument_object.keywords)

        i = isinstance(f, MethodType)
        ff = six.get_unbound_function(f) if i else f
        has_self = len(arg_list) > i and arg_list[i] == 'self'
        i += has_self
        if i:
            code = FuncCode(ff, i)
        self._v_f = _f = (f, f.func_defaults, code, has_self, arg_list)
        return _f
Beispiel #39
0
    def __call__(self, wrapped):
        if isinstance(wrapped, six.class_types):
            cls = wrapped
            try:
                cls_init = six.get_unbound_function(cls.__init__)
                assert cls_init is not OBJECT_INIT
            except (AttributeError, AssertionError):
                raise DiError('Class %s has no __init__ to inject' % cls)
            cls.__init__ = self(cls_init)
            return cls

        if not any([self.args, self.kwargs]):
            self.injectables = self.di.get_deps(wrapped)
        else:
            self.injectables = []
            if self.args:
                self.injectables.extend(self.args)
            if self.kwargs:
                self.injectables.extend(self.kwargs.values())
            self.di.depends_on(*self.injectables)(wrapped)

        return self.decorate(wrapped)
 def __init__(self, doc_object):
     self.doc_object = doc_object
     self.description = dedent(self.doc_object.__doc__)
     try:
         if isinstance(self.doc_object, type):
             func = six.get_unbound_function(self.doc_object.__init__)
         elif (hasattr(self.doc_object, '__call__')
               and not isinstance(self.doc_object, types.FunctionType)):
             func = self.doc_object.__call__
         else:
             func = self.doc_object
         if hasattr(func, '__paste_sig__'):
             sig = func.__paste_sig__
         else:
             sig = inspect.getargspec(func)
             sig = inspect.formatargspec(*sig)
     except TypeError:
         sig = None
     if sig:
         if self.description:
             self.description = '%s\n\n%s' % (
                 sig, self.description)
         else:
             self.description = sig
Beispiel #41
0
def patch():
    """
    Patch `bs4.Tag` to include new functionality.

    :return:
    """
    bs4.Tag._feature_hash = six.get_unbound_function(TagHash._feature_hash)
    bs4.Tag._tag_hash = six.get_unbound_function(TagHash._tag_hash)
    bs4.Tag.hash = six.get_unbound_function(TagHash._hash)
    bs4.Tag.hash_compare = six.get_unbound_function(TagHash._tag_hash_compare)

    bs4.Tag._recursive_structure_xpath = six.get_unbound_function(TagHash._recursive_structure_xpath)
    bs4.Tag.structure_xpath = six.get_unbound_function(TagHash._structure_xpath)

    bs4.Tag._tag_sibling_position = six.get_unbound_function(TagHash._tag_sibling_position)
    bs4.Tag.identifying_xpath = six.get_unbound_function(TagHash._identifying_xpath)
    bs4.Tag.relative_xpath = six.get_unbound_function(TagHash._relative_xpath)

    bs4.Tag._recursive_count = six.get_unbound_function(TagHash._recursive_count)
    bs4.Tag.count = six.get_unbound_function(TagHash._count)

    bs4.Tag.lxml = TagHash._lxml
    bs4.Tag.iterate = six.get_unbound_function(TagHash._iterate)
    bs4.Tag.inner_text = TagHash._inner_text
    bs4.Tag.level = TagHash._level
    bs4.Tag.is_list = six.get_unbound_function(TagHash._is_list)
    bs4.Tag.has_identical_parent = six.get_unbound_function(TagHash._has_identical_parent)
    @security.protected(AddPortalFolders)
    def manage_addPortalFolder(self, id, title='', REQUEST=None):
        """Add a new PortalFolder object with id *id*.
        """
        ob = PortalFolder(id, title)
        self._setObject(id, ob, suppress_events=True)
        if REQUEST is not None:
            return self.folder_contents(  # XXX: ick!
                self, REQUEST, portal_status_message='Folder added')


InitializeClass(PortalFolder)

PortalFolderFactory = Factory(PortalFolder)

manage_addPortalFolder = get_unbound_function(
                            PortalFolder.manage_addPortalFolder)


class ContentFilter:

    """Represent a predicate against a content object's metadata.
    """

    MARKER = []
    filterSubject = []

    def __init__(self, Title=MARKER, Creator=MARKER, Subject=MARKER,
                 Description=MARKER, created=MARKER, created_usage='range:min',
                 modified=MARKER, modified_usage='range:min', Type=MARKER,
                 portal_type=MARKER, **Ignored):
Beispiel #43
0
def _get_object_init():
    if six.PY3 or IS_PYPY:
        return six.get_unbound_function(object.__init__)
Beispiel #44
0
def _update_method(oldmeth, newmeth):
    """Update a method object."""
    # XXX What if im_func is not a function?
    _update_function(six.get_unbound_function(oldmeth),
                     six.get_unbound_function(newmeth))
    return oldmeth
Beispiel #45
0
 def __init__(self, likelihood, Y, tolerance):
     self.likelihood, self.Y, self.tolerance = likelihood, Y, tolerance
     self.is_analytic = six.get_unbound_function(likelihood.predict_density) is not\
         six.get_unbound_function(GPflow.likelihoods.Likelihood.predict_density)
import threading

import six

from dependency_injector.errors import Error


GLOBAL_LOCK = threading.RLock()
"""Dependency injector global reentrant lock.

:type: :py:class:`threading.RLock`
"""

_IS_PYPY = '__pypy__' in sys.builtin_module_names
if _IS_PYPY or six.PY3:  # pragma: no cover
    _OBJECT_INIT = six.get_unbound_function(object.__init__)
else:  # pragma: no cover
    _OBJECT_INIT = None

if six.PY2:  # pragma: no cover
    copy._deepcopy_dispatch[types.MethodType] = \
        lambda obj, memo: type(obj)(obj.im_func,
                                    copy.deepcopy(obj.im_self, memo),
                                    obj.im_class)


def is_provider(instance):
    """Check if instance is provider instance.

    :param instance: Instance to be checked.
    :type instance: object
Beispiel #47
0
def test_get_unbound_function():
    class X(object):
        def m(self):
            pass
    assert six.get_unbound_function(X.m) is X.__dict__["m"]