def test_import_c_accel(self):
     import sys
     old_pp = FUT.PURE_PYTHON
     assert not hasattr(sys, 'import_c_accel')
     sys.import_c_accel = self
     try:
         FUT.PURE_PYTHON = False
         d = {'__name__': 'foo', 'import_c_accel': self}
         FUT.import_c_accel(d, 'sys')
         assert_that(d, has_key('modules'))
         assert_that(d, has_entry('__name__', 'sys'))
         self.assertNotIn('import_c_accel', d)
         FUT.import_c_accel(d, 'sys')
     finally:
         FUT.PURE_PYTHON = old_pp
         del sys.import_c_accel
            FutureWarning
        )


    if policy is NotGiven:
        if policy_name is not NotGiven:
            policy = getUtility(IExternalizationPolicy, policy_name)
        else:
            policy = manager_top[2]

    memos = manager_top[1]
    if memos is None:
        # Don't live beyond this dynamic function call
        memos = defaultdict(dict)

    state = _ExternalizationState(memos, name, catch_components, catch_component_action,
                                  request,
                                  default_non_externalizable_replacer,
                                  decorate, useCache, decorate_callback, policy)

    _manager_push((name, memos, policy))

    try:
        return _to_external_object_state(obj, state, top_level=True)
    finally:
        _manager_pop()


from nti.externalization._compat import import_c_accel # pylint:disable=wrong-import-position,wrong-import-order
import_c_accel(globals(), 'nti.externalization.externalization._externalizer')
Exemplo n.º 3
0
    # XXX: We have a public user of this in nti.ntiids.oids. We need
    # to document this and probably move it to a different module, or
    # provide a cleaner simpler replacement.
    for x in fields:
        value = getattr(self, x, None)
        if value is None:
            continue

        if converter is not None:
            value = converter(value)
        if value is not None:
            result[ext_name] = value
            return value

    # Nothing. Can we adapt it?
    if sup_iface is not None and sup_fields:
        self = sup_iface(self, None)
        if self is not None:
            return choose_field(result,
                                self,
                                ext_name,
                                converter=sup_converter,
                                fields=sup_fields)

    # Falling off the end: return None
    return None


from nti.externalization._compat import import_c_accel  # pylint:disable=wrong-import-position,wrong-import-order
import_c_accel(globals(), 'nti.externalization.externalization._fields')
Exemplo n.º 4
0
    Create and send an `~.ObjectModifiedFromExternalEvent` for
    *containedObject* using `zope.event.notify`.

    The *containedObject* is the subject of the event. The
    *externalObject* is the dictionary of data that was used to update
    the *containedObject*.

    *external_keys* is list of keys from *externalObject* that
    actually changed *containedObject*. If this is not given, we
    assume that all keys in *externalObject* were changed. Note that
    these should to correspond to the interface fields of interfaces
    that the *containedObject* implements in order to properly be able
    to create and populate the `zope.lifecycleevent` `~zope.lifecycleevent.IAttributes`.

    *updater*, if given, is the `~nti.externalization.interfaces.IInternalObjectUpdater`
    instance that was used to handle the updates. If this object implements
    an ``_ext_adjust_modified_event`` method, it will be called to adjust (and return)
    the event object that will be notified.

    *kwargs* are the keyword arguments passed to the event constructor.

    :return: The event object that was notified.
    """

    return _notifyModified(containedObject, externalObject, updater, external_keys,
                           kwargs)


from nti.externalization._compat import import_c_accel # pylint:disable=wrong-import-position,wrong-import-order
import_c_accel(globals(), 'nti.externalization.internalization._events')
Exemplo n.º 5
0
                externalObject[k] = _update_from_external_object(
                    new_obj, v, args)

    if _obj_has_usable_updateFromExternalObject(containedObject):
        # legacy support. The __ext_ignore_updateFromExternalObject__
        # allows a transition to an adapter without changing
        # existing callers and without triggering infinite recursion
        updater = containedObject
    else:
        # It's possible for INamedExternalizedObjectFactoryFinder and
        # IInternalObjectUpdater to be registered at two different levels
        # of specificity, so we need to look up IInternalObjectUpdater,
        # not test if it's provided by what we already have.
        if args.require_updater and not isinstance(containedObject, dict):
            updater = IInternalObjectUpdater(containedObject)
        else:
            updater = IInternalObjectUpdater(containedObject, None)

    if updater is not None:
        notify_event(
            ObjectWillUpdateFromExternalEvent(containedObject, externalObject,
                                              args.root))
        _invoke_updater(containedObject, externalObject, updater,
                        external_keys, args)

    return containedObject


from nti.externalization._compat import import_c_accel  # pylint:disable=wrong-import-position,wrong-import-order
import_c_accel(globals(), 'nti.externalization.internalization._updater')
Exemplo n.º 6
0
        attrs[key] = cache
        cache_instances.add(cache)

    return cache


def cache_for(externalizer,
              ext_self):  # type: (object, object) -> InterfaceCache
    return cache_for_key_in_providedBy(type(externalizer),
                                       providedBy(ext_self))


def _cache_cleanUp(instances):
    # XXX: On PyPy (3 only?) ``list(instances)`` has been
    # seen to raise "RuntimeError: set changed size during iteration."
    # We should probably try to run a gc.collect() before iterating it.
    for x in list(instances):
        x.__init__()


try:
    from zope.testing import cleanup
except ImportError:  # pragma: no cover
    pass
else:
    cleanup.addCleanUp(_cache_cleanUp, args=(cache_instances, ))

# pylint:disable=wrong-import-position
from nti.externalization._compat import import_c_accel
import_c_accel(globals(), 'nti.externalization.__interface_cache')
    :param bool case_sensitive: If False (the default), then the results will
        have each factory twice, once with its found name, and once
        with its name lower cased.
    :return: An iterable of found (name, factory).
    """
    # It's not totally clear why this is in legacy_factories;
    # it's used from modern stuff like ext:registerAutoPackageIO
    result = []
    mod_name = module.__name__
    # If we're dealing with a namespace object, such as what
    # AutoPackaegIO produces, it may represent types from many modules
    # on purpose. OTOH, if we get here via a string that was supposed
    # to be a module, then we need to respect that and ignore imports.
    # This is complicated by the fact that zope.deprecation puts DeprecationProxy
    # objects into sys.modules, but they appear to handle that correctly
    accept_any_module = not isinstance(module, types.ModuleType)
    for name, value in sorted(vars(module).items()):
        if (callable(value)
                and getattr(value, '__external_can_create__', False)
                and (accept_any_module or getattr(value, '__module__', NotGiven) == mod_name)):
            result.append((name, value))
            if not case_sensitive and name.lower() != name:
                result.append((name.lower(), value))

    return result


 # pylint:disable=wrong-import-position,wrong-import-order
from nti.externalization._compat import import_c_accel
import_c_accel(globals(), 'nti.externalization.internalization._legacy_factories')
Exemplo n.º 8
0
        ancestor = object
        for ancestor in cls.mro():
            if '__new__' in ancestor.__dict__:
                break
        if isinstance(ancestor, SingletonMetaclass) and ancestor is not cls:
            ctor = ancestor._new_instance
        else:
            ctor = cls.__new__
        cls._new_instance = staticmethod(ctor)

        the_instance = ctor(cls)

        cls.__new__ = staticmethod(lambda *args: the_instance)

        return cls


SingletonDecorator = SingletonMetaclass  # BWC

Singleton = SingletonMetaclass(
    'Singleton', (object, ), {
        '__doc__':
        "A base class for singletons. "
        "Can be more convenient than a metaclass for Python2/Python3 compatibility."
    })

from nti.externalization._compat import import_c_accel

import_c_accel(globals(), 'nti.externalization._singleton')
Exemplo n.º 9
0
        # In that case, we are not suitable for use with this object.
        # TODO: This algorithm can and should be better in some cases, following the
        # C3 algorithm that __sro__ derivation itself uses.
        for iface in self._ext_schemas_to_consider(ext_self):
            if iface is most_derived:
                # Support interfaces that have their __module__ changed
                # dynamically (e.g., test_benchmarks)
                continue
            if not most_derived.isOrExtends(iface):
                raise TypeError(
                    "Most derived interface %s does not extend %s; non-tree interface structure. "
                    "Searching module %s and considered %s on object %s of class %s and type %s"
                    % (most_derived, iface, self._ext_search_module,
                       list(self._ext_schemas_to_consider(ext_self)), ext_self,
                       ext_self.__class__, type(ext_self)))

        return most_derived

    def _ext_schemas_to_consider(self, ext_self):
        search_module_name = self._ext_search_module.__name__
        return [
            x for x in interface.providedBy(ext_self)
            if x.__module__ == search_module_name
            and not x.queryDirectTaggedValue('_ext_is_marker_interface')
        ]


# pylint:disable=wrong-import-position,wrong-import-order
from nti.externalization._compat import import_c_accel
import_c_accel(globals(), 'nti.externalization._datastructures')
    Instances are immutable.

    This class must not be subclassed; as such, there is no interface
    for it, merely the class itself.
    """

    __slots__ = ('use_iso8601_for_unix_timestamp', )

    def __init__(self, use_iso8601_for_unix_timestamp=False):
        #: Should unix timestamp fields be output as their numeric value,
        #: or be converted into an ISO 8601 timestamp string? By default,
        #: the numeric value is output. This is known to specifically apply
        #: to "Created Time" and "Last Modified."
        self.use_iso8601_for_unix_timestamp = use_iso8601_for_unix_timestamp

    def __repr__(self):  # pragma: no cover
        return "ExternalizationPolicy(use_iso8601_for_unix_timestamp=%s)" % (
            self.use_iso8601_for_unix_timestamp)


#: The default externalization policy.
DEFAULT_EXTERNALIZATION_POLICY = ExternalizationPolicy()


def get_default_externalization_policy():
    return DEFAULT_EXTERNALIZATION_POLICY


from nti.externalization._compat import import_c_accel  # pylint:disable=wrong-import-position
import_c_accel(globals(), 'nti.externalization.__base_interfaces')
Exemplo n.º 11
0
    return internal_to_standard_external_dictionary(
        self,
        mergeFrom,
        decorate,
        request,
        decorate_callback,
        policy,
    )


def to_minimal_standard_external_dictionary(self, mergeFrom=None):
    """
    Does no decoration. Useful for non-'object' types. *self* should have a *mime_type* field.
    """

    result = make_external_dict()
    if mergeFrom is not None:
        result.update_from_other(mergeFrom)
    if StandardExternalFields.CLASS not in result:
        get_class(self, result)

    mime_type = getattr(self, 'mimeType', None) or getattr(
        self, 'mime_type', None)
    if mime_type is not None and mime_type:
        result[StandardExternalFields.MIMETYPE] = mime_type
    return result


from nti.externalization._compat import import_c_accel  # pylint:disable=wrong-import-position,wrong-import-order
import_c_accel(globals(), 'nti.externalization.externalization._dictionary')
Exemplo n.º 12
0
            request = get_current_request()

        if request is not None:
            # Request specific decorating, if given, is more specific than plain object
            # decorating, so it gets to go last.
            for decorator in subscribers((original_object, request),
                                         decorate_interface):
                meth = getattr(decorator, decorate_meth_name)
                meth(original_object, external_object)
    elif call_if_not_decorate is not NotGiven and call_if_not_decorate is not None:
        # XXX: This makes no sense. What is this argument even for?
        call_if_not_decorate(original_object, external_object)

    return external_object


def decorate_external_mapping(
        original_object,
        external_object,
        registry,  # legacy, ignored. pylint:disable=unused-argument
        request):
    # A convenience API exposed to Python in __init__.py
    return decorate_external_object(True, None,
                                    IExternalStandardDictionaryDecorator,
                                    'decorateExternalMapping', original_object,
                                    external_object, None, request)


from nti.externalization._compat import import_c_accel  # pylint:disable=wrong-import-position,wrong-import-order
import_c_accel(globals(), 'nti.externalization.externalization._decorate')