Ejemplo n.º 1
0
def make_patch():
    from selenium.webdriver.remote import webdriver
    from selenium.webdriver.remote import webelement

    webdriver.WebDriver = add_metaclass(ABCMeta)(webdriver.WebDriver)
    webelement.WebElement = add_metaclass(ABCMeta)(webelement.WebElement)

    webdriver.WebDriver.register(WebDriverProxy)
    webelement.WebElement.register(WebElementProxy)
Ejemplo n.º 2
0
def DocInherit(kclass):
    """
    Class decorator to enable `kclass` and all its sub-classes to
    automatically inherit docstrings from base classes.

    Usage:

    .. code-block:: python

        import six


        @DocInherit
        class Parent(object):
            \"""Docstring of the parent class.\"""

            def some_method(self):
                \"""Docstring of the method.\"""
                ...

        class Child(Parent):
            # inherits the docstring of :meth:`Parent`

            def some_method(self):
                # inherits the docstring of :meth:`Parent.some_method`
                ...

    Args:
        kclass (Type): The class to decorate.

    Returns:
        The decorated class.
    """
    return six.add_metaclass(DocStringInheritor)(kclass)
Ejemplo n.º 3
0
def add_metaclass(cls):
    """Call six's add_metaclass with the site's __metaclass__ in Python 3."""
    if not PY2:
        return six.add_metaclass(cls.__metaclass__)(cls)
    else:
        assert cls.__metaclass__
        return cls
Ejemplo n.º 4
0
class DriverBase(object):

    six.add_metaclass(abc.ABCMeta)
    '''Base class for all drivers.'''
    def __init__(self, context):
        self.context = context

    @abc.abstractmethod
    def get_resource_usages(self, project_id):
        '''Collects resource usages for a given project

        :params: project_id
        :return: dictionary of corresponding resources with its usage
        '''

    @abc.abstractmethod
    def update_quota_limits(self, project_id, new_quota):
        '''Updates quota limits for a given project

        :params: project_id, dictionary with the quota limits to update
        :return: Nothing
        '''

    @abc.abstractmethod
    def delete_quota_limits(self, project_id):
        '''Delete quota limits for a given project
Ejemplo n.º 5
0
def add_metaclass(metaclass):
    """ Compat shim for el7. """
    if hasattr(six, 'add_metaclass'):
        return six.add_metaclass(metaclass)
    else:
        # Do nothing.  It's not worth it.
        return lambda klass: klass
Ejemplo n.º 6
0
def add_metaclass(cls):
    """Call six's add_metaclass with the site's __metaclass__ in Python 3."""
    if sys.version_info[0] > 2:
        return six.add_metaclass(cls.__metaclass__)(cls)
    else:
        assert cls.__metaclass__
        return cls
Ejemplo n.º 7
0
def add_metaclass(cls):
    """Call six's add_metaclass with the site's __metaclass__ in Python 3."""
    if not PY2:
        return six.add_metaclass(cls.__metaclass__)(cls)
    else:
        assert cls.__metaclass__
        return cls
Ejemplo n.º 8
0
    def class_or_func_decorator(class_or_func):
        # this code will run during compile time, when we apply dbnd decorator (for example: @task)
        task_decorator = TaskDecorator(class_or_func,
                                       decorator_kwargs=decorator_kwargs)
        tp = task_decorator.task_passport

        # we need to manually register the task here, since in regular flow
        # this happens in TaskMetaclass, but it's not invoked here due to lazy
        # evaluation task_cls
        r = get_task_registry()
        r.register_task_cls_factory(
            task_cls_factory=task_decorator.get_task_cls,
            full_task_family=tp.full_task_family,
            task_family=tp.task_family,
        )
        if task_decorator.is_class:
            # we will change metaclass for UserClass so we will process all UserClass calls
            #
            # @task
            # class UserClass():
            #     pass
            # so the the moment user call UserClass(), -> _DecoratedUserClassMeta.__call__ will be called
            dbnd_decorated_class = six.add_metaclass(
                _UserClassWithTaskDecoratorMetaclass)(class_or_func)
            dbnd_decorated_class.task_decorator = task_decorator
            task_decorator.class_or_func = dbnd_decorated_class
            return dbnd_decorated_class
        else:
            # @task
            # def user_func():
            #     pass
            # we will return our wrapper, that will be called during a runtime,
            # when user calls his own code.
            return build_dbnd_decorated_func(task_decorator)
Ejemplo n.º 9
0
def add_metaclass(metaclass):
    """ Compat shim for el7. """
    if hasattr(six, 'add_metaclass'):
        return six.add_metaclass(metaclass)
    else:
        # Do nothing.  It's not worth it.
        return lambda klass: klass
Ejemplo n.º 10
0
class BaseMigrationChecks(object):

    six.add_metaclass(abc.ABCMeta)

    def __init__(self):
        self.test_case = None

    def set_test_case(self, test_case):
        self.test_case = test_case

    @abc.abstractmethod
    def setup_upgrade_data(self, engine):
        """This method should be used to insert test data for migration.

        :param engine: SQLAlchemy engine
        :return: any data which will be passed to 'check_upgrade' as 'data' arg
        """

    @abc.abstractmethod
    def check_upgrade(self, engine, data):
        """This method should be used to do assertions after upgrade method.

        To perform assertions use 'self.test_case' instance property:
        self.test_case.assertTrue(True)

        :param engine: SQLAlchemy engine
        :param data: data returned by 'setup_upgrade_data'
        """

    @abc.abstractmethod
    def check_downgrade(self, engine):
        """This method should be used to do assertions after downgrade method.
Ejemplo n.º 11
0
def add_metaclass(cls):
    """Call six's add_metaclass with the site's __metaclass__ in Python 3."""
    if sys.version_info[0] > 2:
        return six.add_metaclass(cls.__metaclass__)(cls)
    else:
        assert cls.__metaclass__
        return cls
Ejemplo n.º 12
0
def capture_objs(cls):
    from six import add_metaclass
    module = inspect.getmodule(cls)
    name = cls.__name__
    keeper_class = add_metaclass(ObjKeeper)(cls)
    setattr(module, name, keeper_class)
    cls = getattr(module, name)
    return keeper_class.instances[cls]
Ejemplo n.º 13
0
def capture_objs(cls):
    from six import add_metaclass
    module = inspect.getmodule(cls)
    name = cls.__name__
    keeper_class = add_metaclass(ObjKeeper)(cls)
    setattr(module, name, keeper_class)
    cls = getattr(module, name)
    return keeper_class.instances[cls]
Ejemplo n.º 14
0
def create_manager(name, index):
    frame = getframe(1)  # get caller frame
    kwargs = dict(Builder.__dict__)
    kwargs['__module__'] = frame.f_locals.get('__name__', '')
    manager = type(name, (Builder,), kwargs)
    manager = six.add_metaclass(abc.ABCMeta)(manager)
    manager.index = index
    return manager
Ejemplo n.º 15
0
def interface_as_type(typ, module):
    # type: (Interface, str) -> type
    # we don't add the fields yet -- these types may not exist yet.
    return six.add_metaclass(types.Interface)(type(
        str(typ.name), (types.Namespace, ), {
            "__doc__": typ.desc,
            '__raw__': typ,
            '__module__': module
        }))
Ejemplo n.º 16
0
    def test_synchronized_meta(self, mock_rlock_cls):
        fake_cls = type('fake_cls', (object, ),
                        dict(method1=lambda x: None, method2=lambda y: None))
        fake_cls = six.add_metaclass(baseutils.SynchronizedMeta)(fake_cls)

        fake_cls().method1()
        fake_cls().method2()

        mock_rlock_cls.assert_called_once_with()
        self.assertEqual(2, mock_rlock_cls.return_value.__exit__.call_count)
Ejemplo n.º 17
0
    def _decorate_class(self, cls):
        class _Meta(type):
            def __new__(cls, name, bases, attrs):
                for attr_name, attr in attrs.items():
                    if callable(attr):
                        attrs[attr_name] = self(attr)

                return super(_Meta, cls).__new__(cls, name, bases, attrs)

        return six.add_metaclass(_Meta)(cls)
Ejemplo n.º 18
0
    def __call__(self, func_or_cls):
        if not self.what:
            self.what = func_or_cls.__name__ + '()'
        msg, details = self._build_message()

        if inspect.isfunction(func_or_cls):

            @six.wraps(func_or_cls)
            def wrapped(*args, **kwargs):
                report_deprecated_feature(LOG, msg, details)
                return func_or_cls(*args, **kwargs)

            return wrapped
        elif inspect.isclass(func_or_cls):
            orig_init = func_or_cls.__init__

            # TODO(tsufiev): change `functools` module to `six` as
            # soon as six 1.7.4 (with fix for passing `assigned`
            # argument to underlying `functools.wraps`) is released
            # and added to the oslo-incubator requrements
            @functools.wraps(orig_init, assigned=('__name__', '__doc__'))
            def new_init(self, *args, **kwargs):
                if self.__class__ in _DEPRECATED_EXCEPTIONS:
                    report_deprecated_feature(LOG, msg, details)
                orig_init(self, *args, **kwargs)

            func_or_cls.__init__ = new_init
            _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            if issubclass(func_or_cls, Exception):
                # NOTE(dhellmann): The subclasscheck is called,
                # sometimes, to test whether a class matches the type
                # being caught in an exception. This lets us warn
                # folks that they are trying to catch an exception
                # that has been deprecated. However, under Python 3
                # the test for whether one class is a subclass of
                # another has been optimized so that the abstract
                # check is only invoked in some cases. (See
                # PyObject_IsSubclass in cpython/Objects/abstract.c
                # for the short-cut.)
                class ExceptionMeta(type):
                    def __subclasscheck__(self, subclass):
                        if self in _DEPRECATED_EXCEPTIONS:
                            report_deprecated_feature(LOG, msg, details)
                        return super(ExceptionMeta,
                                     self).__subclasscheck__(subclass)

                func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
                _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            return func_or_cls
        else:
            raise TypeError('deprecated can be used only with functions or '
                            'classes')
Ejemplo n.º 19
0
    def __call__(self, func_or_cls):
        report_deprecated = functools.partial(
            deprecation_warning,
            what=self.what or func_or_cls.__name__ + '()',
            as_of=self.as_of,
            in_favor_of=self.in_favor_of,
            remove_in=self.remove_in)

        if inspect.isfunction(func_or_cls):

            @six.wraps(func_or_cls)
            def wrapped(*args, **kwargs):
                report_deprecated()
                return func_or_cls(*args, **kwargs)
            return wrapped
        elif inspect.isclass(func_or_cls):
            orig_init = func_or_cls.__init__

            # TODO(tsufiev): change `functools` module to `six` as
            # soon as six 1.7.4 (with fix for passing `assigned`
            # argument to underlying `functools.wraps`) is released
            # and added to the oslo-incubator requrements
            @functools.wraps(orig_init, assigned=('__name__', '__doc__'))
            def new_init(self, *args, **kwargs):
                if self.__class__ in _DEPRECATED_EXCEPTIONS:
                    report_deprecated()
                orig_init(self, *args, **kwargs)
            func_or_cls.__init__ = new_init
            _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            if issubclass(func_or_cls, Exception):
                # NOTE(dhellmann): The subclasscheck is called,
                # sometimes, to test whether a class matches the type
                # being caught in an exception. This lets us warn
                # folks that they are trying to catch an exception
                # that has been deprecated. However, under Python 3
                # the test for whether one class is a subclass of
                # another has been optimized so that the abstract
                # check is only invoked in some cases. (See
                # PyObject_IsSubclass in cpython/Objects/abstract.c
                # for the short-cut.)
                class ExceptionMeta(type):
                    def __subclasscheck__(self, subclass):
                        if self in _DEPRECATED_EXCEPTIONS:
                            report_deprecated()
                        return super(ExceptionMeta,
                                     self).__subclasscheck__(subclass)
                func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
                _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            return func_or_cls
        else:
            raise TypeError('deprecated can be used only with functions or '
                            'classes')
Ejemplo n.º 20
0
    def __call__(self, func_or_cls):
        report_deprecated = functools.partial(deprecation_warning,
                                              what=self.what
                                              or func_or_cls.__name__ + '()',
                                              as_of=self.as_of,
                                              in_favor_of=self.in_favor_of,
                                              remove_in=self.remove_in)

        if inspect.isfunction(func_or_cls):

            @six.wraps(func_or_cls)
            def wrapped(*args, **kwargs):
                report_deprecated()
                return func_or_cls(*args, **kwargs)

            return wrapped
        elif inspect.isclass(func_or_cls):
            orig_init = func_or_cls.__init__

            @six.wraps(orig_init, assigned=('__name__', '__doc__'))
            def new_init(self, *args, **kwargs):
                if self.__class__ in _DEPRECATED_EXCEPTIONS:
                    report_deprecated()
                orig_init(self, *args, **kwargs)

            func_or_cls.__init__ = new_init
            _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            if issubclass(func_or_cls, Exception):
                # NOTE(dhellmann): The subclasscheck is called,
                # sometimes, to test whether a class matches the type
                # being caught in an exception. This lets us warn
                # folks that they are trying to catch an exception
                # that has been deprecated. However, under Python 3
                # the test for whether one class is a subclass of
                # another has been optimized so that the abstract
                # check is only invoked in some cases. (See
                # PyObject_IsSubclass in cpython/Objects/abstract.c
                # for the short-cut.)
                class ExceptionMeta(type):
                    def __subclasscheck__(self, subclass):
                        if self in _DEPRECATED_EXCEPTIONS:
                            report_deprecated()
                        return super(ExceptionMeta,
                                     self).__subclasscheck__(subclass)

                func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
                _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            return func_or_cls
        else:
            raise TypeError('deprecated can be used only with functions or '
                            'classes')
Ejemplo n.º 21
0
def capture_objs(cls):
    """
    Captures the instances of a given class during runtime

     :param cls: class to capture
     :return: dynamic list with references to all instances of ``cls``
    """
    module = inspect.getmodule(cls)
    name = cls.__name__
    keeper_class = add_metaclass(ObjKeeper)(cls)
    setattr(module, name, keeper_class)
    cls = getattr(module, name)
    return keeper_class.instances[cls]
Ejemplo n.º 22
0
def capture_objs(cls):
    """
    Captures the instances of a given class during runtime

     :param cls: class to capture
     :return: dynamic list with references to all instances of ``cls``
    """
    module = inspect.getmodule(cls)
    name = cls.__name__
    keeper_class = add_metaclass(ObjKeeper)(cls)
    setattr(module, name, keeper_class)
    cls = getattr(module, name)
    return keeper_class.instances[cls]
Ejemplo n.º 23
0
    def _inner(cls):
        # pragma pylint: disable=unused-variable
        metabases = tuple(
            collections.OrderedDict(  # noqa: F841
                (c, None) for c in (metaclasses + (type(cls), ))).keys())
        # pragma pylint: enable=unused-variable
        _Meta = metabases[0]
        for base in metabases[1:]:

            class _Meta(base, _Meta):  # pylint: disable=function-redefined
                pass

        return six.add_metaclass(_Meta)(cls)
Ejemplo n.º 24
0
class State():
    six.add_metaclass(ABCMeta)

    @abstractmethod
    def start(self):
        pass

    @abstractmethod
    def stop(self):
        pass

    @abstractmethod
    def cleanup(self):
        pass
Ejemplo n.º 25
0
def test_add_metaclass():
    class Meta(type):
        pass
    class X:
        "success"
    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, object)
    assert X.__module__ == __name__
    assert X.__doc__ == "success"
    class Base(object):
        pass
    class X(Base):
        pass
    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, Base)
    class Base2(object):
        pass
    class X(Base, Base2):
        pass
    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, Base)
    assert issubclass(X, Base2)

    # Test a second-generation subclass of a type.
    class Meta1(type):
        m1 = "m1"
    class Meta2(Meta1):
        m2 = "m2"
    class Base:
        b = "b"
    Base = six.add_metaclass(Meta1)(Base)
    class X(Base):
        x = "x"
    X = six.add_metaclass(Meta2)(X)
    assert type(X) is Meta2
    assert issubclass(X, Base)
    assert type(Base) is Meta1
    assert "__dict__" not in vars(X)
    instance = X()
    instance.attr = "test"
    assert vars(instance) == {"attr": "test"}
    assert instance.b == Base.b
    assert instance.x == X.x

    # test a class with slots
    class MySlots(object):
        __slots__ = ["a", "b"]
    MySlots = six.add_metaclass(Meta1)(MySlots)

    assert MySlots.__slots__ == ["a", "b"]
    instance = MySlots()
    instance.a = "foo"
    py.test.raises(AttributeError, setattr, instance, "c", "baz")
Ejemplo n.º 26
0
def define_hook(subclass=None, only_one_registered=False):
    """
    This method must be used as a decorator to define a new hook inheriting from
    the hook class that this is called from, this will return an abstract base
    class, which distinguishes is from the classes returned by register_hook
    which can be instantiated. Only abstract base classes track registered hooks.
    """

    # Allow optional arguments to be passed to define_hook when used as a decorator
    if subclass is None:
        return partial(define_hook, only_one_registered=only_one_registered)

    subclass = six.add_metaclass(KolibriHookMeta)(subclass)

    subclass._setup_base_class(only_one_registered=only_one_registered)

    return subclass
Ejemplo n.º 27
0
class BaseTemplate(six.add_metaclass(ABCMeta)):
	 
	def __init__(self, template):
		self._template = template

	@abstractmethod
	def render(self):
		for element in self._get_iter_elements():
			self._parse_element(element)

	@abstractmethod
	def _parse_element(self, element):
		pass

	@abstractmethod
	def _get_element_paremetrs(self, element):
		pass
Ejemplo n.º 28
0
    def decorated(item):
        try:

            func_spec = build_task_decorator_spec(
                item=item,
                decorator_kwargs=decorator_kwargs,
                default_result=task_default_result,
            )

            # we can't create class dynamically because of python2/3
            # __name__ is not overridable

            task_cls = TaskMetaclass(
                str(item.__name__),
                (task_type, ),
                dict(
                    _conf__decorator_spec=func_spec,
                    _callable_item=None,
                    __doc__=item.__doc__,
                    __module__=item.__module__,
                    defaults=task_defaults,
                ),
            )
        except Exception as ex:
            logger.error(
                "Failed to create task %s: %s\n%s\n",
                item.__name__,
                str(ex),
                user_side_code(context=5),
                exc_info=show_exc_info(ex),
            )
            raise

        if func_spec.is_class:
            callable_item = six.add_metaclass(_DecoratedUserClassMeta)(item)
        else:
            callable_item = DbndFuncProxy(task_cls=task_cls)
        task_cls._callable_item = callable_item

        callable_item.func = item
        callable_item.task_cls = task_cls
        callable_item.task = task_cls
        callable_item.t = task_cls
        return task_cls._callable_item
Ejemplo n.º 29
0
def _make_intent_from_args(args):
    """
    Create an intent type for a given set of arguments.

    :param args: a dict with keys as the names of arguments and values as
        :class:`argument`s.

    :returns: A new type that can hold all of the data to call a function that
        has the given arguments.
    """
    class _Intent(PClass):
        pass

    for name, arg in iteritems(args):
        setattr(_Intent, name, field(type=arg.type))

    _PIntent = add_metaclass(PClassMeta)(_Intent)

    return _PIntent
Ejemplo n.º 30
0
class ExternalLogger(object):
    six.add_metaclass(abc.ABCMeta)

    @abc.abstractmethod
    def set_runtime_args(self, runtime_args):
        """
            Set runtime arguments for the logger.
            runtime_args: dict of runtime arguments.
        """
        raise NotImplementedError(
            'Must define set_runtime_args function to use this base class')

    @abc.abstractmethod
    def log(self, log_dict):
        """
            log a dict of key/values to an external destination
            log_dict: input dict
        """
        raise NotImplementedError(
            'Must define log function to use this base class')
Ejemplo n.º 31
0
def meta_interface(interface):
    class _MetaInterface(type):
        def __new__(metacls, classname, baseclasses, attrs):
            attrs.update({
                "__xml_dom": interface,
                "properties": [],
                "methods": [],
                "_properties_xml": {},
                "_methods_xml": {},
            })

            _call_method = attrs["_call_method"]
            _get_property = attrs["_get_property"]
            _set_property = attrs["_set_property"]
            elements = [n for n in interface.childNodes if n.nodeType == 1]

            for element in elements:
                if element.tagName == "property":
                    property_name = element.getAttribute("name")

                    attrs["properties"].append(property_name)
                    attrs["_properties_xml"][property_name] = element
                    attrs[property_name] = property(
                        _wrap_call_with_name(_get_property, property_name),
                        _wrap_call_with_name(_set_property, property_name),
                    )

                elif element.tagName == "method":
                    method_name = element.getAttribute("name")
                    attrs["methods"].append(method_name)
                    attrs["_methods_xml"][method_name] = element

                    attrs[method_name] = _wrap_call_with_name(
                        _call_method, method_name)

                    attrs[method_name].__name__ = (method_name.encode()
                                                   if six.PY2 else method_name)

            return type.__new__(metacls, classname, baseclasses, attrs)

    return six.add_metaclass(_MetaInterface)(SDInterface)
Ejemplo n.º 32
0
def meta_interface(interface):
    class _MetaInterface(type):
        def __new__(metacls, classname, baseclasses, attrs):
            attrs.update({
                '__xml_dom': interface,
                'properties': [],
                'methods': [],
                '_properties_xml': {},
                '_methods_xml': {},
            })

            _call_method = attrs['_call_method']
            _get_property = attrs['_get_property']
            _set_property = attrs['_set_property']
            elements = [n for n in interface.childNodes if n.nodeType == 1]

            for element in elements:
                if element.tagName == 'property':
                    property_name = element.getAttribute('name')

                    attrs['properties'].append(property_name)
                    attrs['_properties_xml'][property_name] = element
                    attrs[property_name] = property(
                        _wrap_call_with_name(_get_property, property_name),
                        _wrap_call_with_name(_set_property, property_name),
                    )

                elif element.tagName == 'method':
                    method_name = element.getAttribute('name')
                    attrs['methods'].append(method_name)
                    attrs['_methods_xml'][method_name] = element

                    attrs[method_name] = _wrap_call_with_name(
                        _call_method, method_name)

                    attrs[method_name].__name__ = (method_name.encode()
                                                   if six.PY2 else method_name)

            return type.__new__(metacls, classname, baseclasses, attrs)

    return six.add_metaclass(_MetaInterface)(SDInterface)
Ejemplo n.º 33
0
    def __call__(self, func_or_cls):
        if not self.what:
            self.what = func_or_cls.__name__ + '()'
        msg, details = self._build_message()

        if inspect.isfunction(func_or_cls):

            @six.wraps(func_or_cls)
            def wrapped(*args, **kwargs):
                report_deprecated_feature(LOG, msg, details)
                return func_or_cls(*args, **kwargs)
            return wrapped
        elif inspect.isclass(func_or_cls):
            orig_init = func_or_cls.__init__

            # TODO(tsufiev): change `functools` module to `six` as
            # soon as six 1.7.4 (with fix for passing `assigned`
            # argument to underlying `functools.wraps`) is released
            # and added to the oslo-incubator requrements
            @functools.wraps(orig_init, assigned=('__name__', '__doc__'))
            def new_init(self, *args, **kwargs):
                report_deprecated_feature(LOG, msg, details)
                orig_init(self, *args, **kwargs)
            func_or_cls.__init__ = new_init

            if issubclass(func_or_cls, Exception):
                class ExceptionMeta(type):
                    def __subclasscheck__(self, subclass):
                        if self in _DEPRECATED_EXCEPTIONS:
                            report_deprecated_feature(LOG, msg, details)
                        return super(ExceptionMeta,
                                     self).__subclasscheck__(subclass)
                func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
                _DEPRECATED_EXCEPTIONS.add(func_or_cls)
            return func_or_cls
        else:
            raise TypeError('deprecated can be used only with functions or '
                            'classes')
Ejemplo n.º 34
0

class CITextField(CIText, models.TextField):
    pass


class CICharField(CIText, models.CharField):
    pass


class CIEmailField(CIText, models.EmailField):
    pass


if hasattr(models, 'SubfieldBase'):
    CITextField = six.add_metaclass(models.SubfieldBase)(CITextField)
    CICharField = six.add_metaclass(models.SubfieldBase)(CICharField)
    CIEmailField = six.add_metaclass(models.SubfieldBase)(CIEmailField)

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules([], ["^sentry\.db\.models\.fields\.citext\.CITextField"])
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.citext\.CICharField"])
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.citext\.CIEmailField"])


def create_citext_extension(db, **kwargs):
    from sentry.utils.db import is_postgres

    # We always need the citext extension installed for Postgres,
Ejemplo n.º 35
0
        from south.modelsinspector import introspector

        # Get the args and kwargs with which this field was generated.
        # The "double" variable name is a riff of of South "triples", since
        #   the `introspector` function only returns the final two elements
        #   of a South triple. This is fine since those two pieces are all
        #   we actually need.
        double = introspector(self.of)

        # Return the appropriate South triple.
        return (
            '%s.%s' % (self.__class__.__module__, self.__class__.__name__),
            [],
            {
                # The `of` argument is *itself* another triple, of
                #   the internal field.
                # The ArrayField constructor understands how to resurrect
                #   its internal field from this serialized state.
                'of': (
                    u'{module}.{class_name}'.format(
                        module=self.of.__class__.__module__,
                        class_name=self.of.__class__.__name__,
                    ), double[0], double[1],
                ),
            },
        )


if hasattr(models, 'SubfieldBase'):
    ArrayField = six.add_metaclass(models.SubfieldBase)(ArrayField)
Ejemplo n.º 36
0
def serialize_fw(func):
    """
    a decorator to add FW serializations keys
    see documentation of FWSerializable for more details
    """

    def _decorator(self, *args, **kwargs):
        m_dict = func(self, *args, **kwargs)
        m_dict['_fw_name'] = self.fw_name
        return m_dict

    return _decorator


six.add_metaclass(abc.ABCMeta)
class FWSerializable(object):
    """
    To create a serializable object within FireWorks, you should subclass this
    class and implement the to_dict() and from_dict() methods.

    If you want the load_object() implicit de-serialization to work, you must
    also:
        - Use the @serialize_fw decorator on to_dict()
        - Override the _fw_name parameter with a unique key.

    See documentation of load_object() for more details.

    The use of @classmethod for from_dict allows you to define a superclass
    that implements the to_dict() and from_dict() for all its subclasses.
Ejemplo n.º 37
0
            node_id = value.pop('node_id')
            data = None
        else:
            node_id = None
            data = value

        return NodeData(self, node_id, data)

    def get_prep_value(self, value):
        if not value and self.null:
            # save ourselves some storage
            return None

        # TODO(dcramer): we should probably do this more intelligently
        # and manually
        if not value.id:
            value.id = nodestore.create(value.data)
        else:
            nodestore.set(value.id, value.data)

        return compress(pickle.dumps({'node_id': value.id}))


if hasattr(models, 'SubfieldBase'):
    NodeField = six.add_metaclass(models.SubfieldBase)(NodeField)

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules([], ["^sentry\.db\.models\.fields\.node\.NodeField"])
Ejemplo n.º 38
0
 def __new__(cls, *args, **kwargs):
     if args and type(args[0]) == type and issubclass(args[0], TestCase):
         return six.add_metaclass(TestCaseMeta)(args[0])
     return object.__new__(cls)
Ejemplo n.º 39
0
    def get_missing_article(self, site=None):
        """Get a Page which refers to a missing page on the site."""
        if not site:
            site = self.get_site()
        page = pywikibot.Page(pywikibot.page.Link(
                              "There is no page with this title", site))
        if page.exists():
            raise unittest.SkipTest("Did not find a page that does not exist.")

        return page


if sys.version_info[0] > 2:
    import six
    TestCase = six.add_metaclass(MetaTestCaseClass)(TestCase)


class DefaultSiteTestCase(TestCase):

    """Run tests against the config specified site."""

    family = config.family
    code = config.mylang

    @classmethod
    def override_default_site(cls, site):
        print('%s using %s instead of %s:%s.'
              % (cls.__name__, site, cls.family, cls.code))
        cls.site = site
        cls.family = site.family.name
Ejemplo n.º 40
0
def test_add_metaclass():
    class Meta(type):
        pass

    class X:
        "success"

    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, object)
    assert X.__module__ == __name__
    assert X.__doc__ == "success"

    class Base(object):
        pass

    class X(Base):
        pass

    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, Base)

    class Base2(object):
        pass

    class X(Base, Base2):
        pass

    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, Base)
    assert issubclass(X, Base2)

    # Test a second-generation subclass of a type.
    class Meta1(type):
        m1 = "m1"

    class Meta2(Meta1):
        m2 = "m2"

    class Base:
        b = "b"

    Base = six.add_metaclass(Meta1)(Base)

    class X(Base):
        x = "x"

    X = six.add_metaclass(Meta2)(X)
    assert type(X) is Meta2
    assert issubclass(X, Base)
    assert type(Base) is Meta1
    assert "__dict__" not in vars(X)
    instance = X()
    instance.attr = "test"
    assert vars(instance) == {"attr": "test"}
    assert instance.b == Base.b
    assert instance.x == X.x

    # Test a class with slots.
    class MySlots(object):
        __slots__ = ["a", "b"]

    MySlots = six.add_metaclass(Meta1)(MySlots)

    assert MySlots.__slots__ == ["a", "b"]
    instance = MySlots()
    instance.a = "foo"
    py.test.raises(AttributeError, setattr, instance, "c", "baz")

    # Test a class with string for slots.
    class MyStringSlots(object):
        __slots__ = "ab"

    MyStringSlots = six.add_metaclass(Meta1)(MyStringSlots)
    assert MyStringSlots.__slots__ == "ab"
    instance = MyStringSlots()
    instance.ab = "foo"
    py.test.raises(AttributeError, setattr, instance, "a", "baz")
    py.test.raises(AttributeError, setattr, instance, "b", "baz")

    class MySlotsWeakref(object):
        __slots__ = "__weakref__",

    MySlotsWeakref = six.add_metaclass(Meta)(MySlotsWeakref)
    assert type(MySlotsWeakref) is Meta
Ejemplo n.º 41
0
class ObjectMeta(type):
    """the singleton class factory"""
    
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, '_instances'):
            cls._instances = dict()
        arg_ids = tuple(
            hash(arg) if hashable(arg)
            else id(arg) for arg in args
        )
        if arg_ids not in cls._instances:
            cls._instances[arg_ids] = Object.__new__(cls)
            cls._instances[arg_ids].__init__(*args, **kwargs)
        return cls._instances[arg_ids]

singleton = add_metaclass(ObjectMeta)


@singleton
class Object(object):
    """a new-style singleton class base"""


class RunResult(Object):
    success = False


def read_by_struct(struct, bytedata):
    size = struct.struct_size
    return [
        struct(bytedata[i * size:(i + 1) * size])
Ejemplo n.º 42
0
class ROLLBACK_COMPLETE(Status): pass

class DELETE_IN_PROGRESS(Status): pass
class DELETE_FAILED(Status): pass
class DELETE_COMPLETE(Status): pass

class UPDATE_IN_PROGRESS(Status): pass
class UPDATE_COMPLETE_CLEANUP_IN_PROGRESS(Status): pass
class UPDATE_COMPLETE(Status): pass
class UPDATE_ROLLBACK_IN_PROGRESS(Status): pass
class UPDATE_ROLLBACK_FAILED(Status): pass
class UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS(Status): pass
class UPDATE_ROLLBACK_COMPLETE(Status): pass

for kls in [Status] + Status.__subclasses__():
    with_meta = six.add_metaclass(StatusMeta)(kls)
    locals()[kls.__name__] = with_meta
    Status.statuses[kls.__name__] = with_meta

class Cloudformation(AmazonMixin):
    def __init__(self, stack_name, region="ap-southeast-2"):
        self.region = region
        self.stack_name = stack_name

    @hp.memoized_property
    def conn(self):
        log.info("Using region [%s] for cloudformation (%s)", self.region, self.stack_name)
        return boto.cloudformation.connect_to_region(self.region)

    def reset(self):
        self._description = None
Ejemplo n.º 43
0
Archivo: uuid.py Proyecto: zvrr/sentry
            return self._auto_add
        return "%s:%s" % (self._auto_add.__module__, self._auto_add.__name__)


class UUIDAdapter(object):
    def __init__(self, value):
        if not isinstance(value, UUID):
            raise TypeError("UUIDAdapter only understands UUID objects.")
        self.value = value

    def getquoted(self):
        return ("'%s'" % self.value).encode("utf8")


if hasattr(models, "SubfieldBase"):
    UUIDField = six.add_metaclass(models.SubfieldBase)(UUIDField)

# Register the UUID type with psycopg2.
register_adapter(UUID, UUIDAdapter)

# If South is installed, then tell South how to properly
# introspect a UUIDField.
if SOUTH:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules(
        [(
            (UUIDField, ),
            [],
            {
                "auto_add": ["_auto_add_str", {
Ejemplo n.º 44
0
Archivo: node.py Proyecto: webZW/sentry
            value = None

        return NodeData(self, node_id, value, wrapper=self.wrapper)

    def get_prep_value(self, value):
        """
            Prepares the NodeData to be written in a Model.save() call.

            Makes sure the event body is written to nodestore and
            returns the node_id reference to be written to rowstore.
        """
        if not value and self.null:
            # save ourselves some storage
            return None

        if value.id is None:
            value.id = self.id_func()

        value.save()
        return compress(pickle.dumps({'node_id': value.id}))


if hasattr(models, 'SubfieldBase'):
    NodeField = six.add_metaclass(models.SubfieldBase)(NodeField)

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules([],
                            ["^sentry\.db\.models\.fields\.node\.NodeField"])
Ejemplo n.º 45
0
    depending on whether it is in the auto_run_script_list.
    """

    __metaclass__ = TestScriptMeta

    def setUp(self):
        """Prepare the environment for running the pwb.py script."""
        super(TestScript, self).setUp()
        self.old_pywikibot_dir = None
        if 'PYWIKIBOT2_DIR' in os.environ:
            self.old_pywikibot_dir = os.environ['PYWIKIBOT2_DIR']
        os.environ['PYWIKIBOT2_DIR'] = pywikibot.config.base_dir

    def tearDown(self):
        """Restore the environment after running the pwb.py script."""
        super(TestScript, self).tearDown()
        del os.environ['PYWIKIBOT2_DIR']
        if self.old_pywikibot_dir:
            os.environ['PYWIKIBOT2_DIR'] = self.old_pywikibot_dir


if sys.version_info[0] > 2:
    import six
    TestScript = six.add_metaclass(TestScriptMeta)(TestScript)

if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass
Ejemplo n.º 46
0
def reloadable_class(cls):
    """
    convinience decorator instead of @six.add_metaclass(ReloadingMetaclass)
    """
    return six.add_metaclass(ReloadingMetaclass)(cls)
Ejemplo n.º 47
0
    :returns: Dictionary of `Field` descriptors

    """
    fields = {}
    for base in bases[::-1]:
        if issubclass(base, Model):
            fields.update({
                key: copy.deepcopy(value)
                for key, value in six.iteritems(base._fields)
            })
    return fields


class ModelMeta(type):
    """Model metaclass. Collects field descriptors and inherits fields from
    parent.

    """
    def __init__(cls, name, bases, dct):
        cls._fields = copy_fields(bases)
        cls._fields.update({
            key: value
            for key, value in six.iteritems(dct)
            if isinstance(value, Field)
        })
        super(ModelMeta, cls).__init__(name, bases, dct)


# Apply metaclass to `Model`
Model = six.add_metaclass(ModelMeta)(Model)
Ejemplo n.º 48
0
                value = pickle.loads(decompress(value))
            except Exception as e:
                logger.exception(e)
                return {}
        elif not value:
            return {}
        return value

    def get_prep_value(self, value):
        if not value and self.null:
            # save ourselves some storage
            return None
        # enforce six.text_type strings to guarantee consistency
        if isinstance(value, six.binary_type):
            value = six.text_type(value)
        # db values need to be in unicode
        return compress(pickle.dumps(value))

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)


if hasattr(models, 'SubfieldBase'):
    GzippedDictField = six.add_metaclass(models.SubfieldBase)(GzippedDictField)

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules([], ["^sentry\.db\.models\.fields\.gzippeddict\.GzippedDictField"])
Ejemplo n.º 49
0
        value = super(EncryptedTextField, self).get_db_prep_value(value, *args, **kwargs)
        return encrypt(value)

    def to_python(self, value):
        if value is not None and isinstance(value, six.string_types):
            value = decrypt(value)
        return super(EncryptedTextField, self).to_python(value)

    def get_prep_lookup(self, lookup_type, value):
        raise NotImplementedError(
            '{!r} lookup type for {!r} is not supported'.format(
                lookup_type,
                self,
            )
        )


if hasattr(models, 'SubfieldBase'):
    EncryptedCharField = six.add_metaclass(models.SubfieldBase)(EncryptedCharField)
    EncryptedTextField = six.add_metaclass(models.SubfieldBase)(EncryptedTextField)

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules(
        [], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedPickledObjectField"]
    )
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedCharField"])
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedJsonField"])
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedTextField"])
Ejemplo n.º 50
0
def singleton(cls):
    return six.add_metaclass(Singleton)(cls)
Ejemplo n.º 51
0
        # Get the args and kwargs with which this field was generated.
        # The "double" variable name is a riff of of South "triples", since
        #   the `introspector` function only returns the final two elements
        #   of a South triple. This is fine since those two pieces are all
        #   we actually need.
        double = introspector(self.of)

        # Return the appropriate South triple.
        return (
            "%s.%s" % (self.__class__.__module__, self.__class__.__name__),
            [],
            {
                # The `of` argument is *itself* another triple, of
                #   the internal field.
                # The ArrayField constructor understands how to resurrect
                #   its internal field from this serialized state.
                "of": (
                    u"{module}.{class_name}".format(
                        module=self.of.__class__.__module__,
                        class_name=self.of.__class__.__name__),
                    double[0],
                    double[1],
                )
            },
        )


if hasattr(models, "SubfieldBase"):
    ArrayField = six.add_metaclass(models.SubfieldBase)(ArrayField)
Ejemplo n.º 52
0
    @classmethod
    def find_root(cls):
        try:
            result = next(cls.find_valid_roots())
        except StopIteration:
            raise RuntimeError(
                "{cls.__name__} unable to find executables"
                .format(**locals()))
        return path.Path(result)

    @classmethod
    def find_valid_roots(cls):
        """
        Generate valid roots for the target executable based on the
        candidate paths.
        """
        return filter(cls.is_valid_root, cls.candidate_paths)

    @classmethod
    def is_valid_root(cls, root):
        try:
            cmd = [os.path.join(root, cls.exe)] + cls.args
            subprocess.check_call(cmd, stdout=cls.DEV_NULL)
        except OSError:
            return False
        return True


if not six.PY2:
    PathFinder = six.add_metaclass(abc.ABCMeta)(PathFinder)
Ejemplo n.º 53
0
            raise TypeError("Expected an OID, got " + str(type(mech)))

        minor_status = ffi.new('OM_uint32[1]')
        out_name = ffi.new('gss_name_t[1]')
        try:
            retval = C.gss_canonicalize_name(minor_status, self._name[0],
                                             ffi.addressof(oid), out_name)
            if GSS_ERROR(retval):
                raise _exception_for_status(retval, minor_status[0])
            return MechName(out_name, mech)
        except:
            C.gss_release_name(minor_status, out_name)


# Add metaclass in Python 2/3 compatible way:
Name = six.add_metaclass(_NameMeta)(Name)


class MechName(Name):
    """
    Represents a GSSAPI Mechanism Name (MN) as obtained by
    :meth:`~gssapi.names.Name.canonicalize` or as the
    :attr:`~gssapi.ctx.AcceptContext.peer_name` property of an :class:`~gssapi.ctx.AcceptContext`.

    Don't construct instances of this class directly; use
    :meth:`~gssapi.names.Name.canonicalize` on a :class:`Name` to create a :class:`MechName`.
    """
    def __init__(self, name, mech_type):
        """Don't construct instances of this class directly; This object will acquire
        ownership of `name`, and release the associated storage when it is deleted."""
        if isinstance(
Ejemplo n.º 54
0
        instance._launched = False
        instance.__init__()
        return instance

    def launch(self):
        """Start this component (but only do this once)"""
        if not self._launched:
            self._launched = True
            self.start()

    def start(self):
        """Start this component (top-level start does nothing)"""

    def stop(self):
        """Stop the component (top-level stop does nothing)"""
Component = six.add_metaclass(ComponentMeta)(Component)



class ComponentList(Component):
    """A list of components, used to implement dependency lists.

    This generally will not be instantiated by a user; instead,
    when a dependency is set to a list in the configuration,
    this is an adaptor to set that dependency to a list-like object
    with the ordered dependencies.

    """
    dependency_list = ListSetting()

    def __init__(self, components):
Ejemplo n.º 55
0
def test_add_metaclass():
    class Meta(type):
        pass
    class X:
        'success'
    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, object)
    assert X.__module__ == __name__
    assert X.__doc__ == 'success'
    class Base(object):
        pass
    class X(Base):
        pass
    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, Base)
    class Base2(object):
        pass
    class X(Base, Base2):
        pass
    X = six.add_metaclass(Meta)(X)
    assert type(X) is Meta
    assert issubclass(X, Base)
    assert issubclass(X, Base2)

    # Test a second-generation subclass of a type.
    class Meta1(type):
        m1 = 'm1'
    class Meta2(Meta1):
        m2 = 'm2'
    class Base:
        b = 'b'
    Base = six.add_metaclass(Meta1)(Base)
    class X(Base):
        x = 'x'
    X = six.add_metaclass(Meta2)(X)
    assert type(X) is Meta2
    assert issubclass(X, Base)
    assert type(Base) is Meta1
    assert '__dict__' not in vars(X)
    instance = X()
    instance.attr = 'test'
    assert vars(instance) == {'attr': 'test'}
    assert instance.b == Base.b
    assert instance.x == X.x

    # Test a class with slots.
    class MySlots(object):
        __slots__ = ['a', 'b']
    MySlots = six.add_metaclass(Meta1)(MySlots)

    assert MySlots.__slots__ == ['a', 'b']
    instance = MySlots()
    instance.a = 'foo'
    py.test.raises(AttributeError, setattr, instance, 'c', 'baz')

    # Test a class with string for slots.
    class MyStringSlots(object):
        __slots__ = 'ab'
    MyStringSlots = six.add_metaclass(Meta1)(MyStringSlots)
    assert MyStringSlots.__slots__ == 'ab'
    instance = MyStringSlots()
    instance.ab = 'foo'
    py.test.raises(AttributeError, setattr, instance, 'a', 'baz')
    py.test.raises(AttributeError, setattr, instance, 'b', 'baz')

    class MySlotsWeakref(object):
        __slots__ = '__weakref__',
    MySlotsWeakref = six.add_metaclass(Meta)(MySlotsWeakref)
    assert type(MySlotsWeakref) is Meta
Ejemplo n.º 56
0

class CITextField(CIText, models.TextField):
    pass


class CICharField(CIText, models.CharField):
    pass


class CIEmailField(CIText, models.EmailField):
    pass


if hasattr(models, "SubfieldBase"):
    CITextField = six.add_metaclass(models.SubfieldBase)(CITextField)
    CICharField = six.add_metaclass(models.SubfieldBase)(CICharField)
    CIEmailField = six.add_metaclass(models.SubfieldBase)(CIEmailField)

if "south" in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules(
        [], ["^sentry\.db\.models\.fields\.citext\.CITextField"])
    add_introspection_rules(
        [], ["^sentry\.db\.models\.fields\.citext\.CICharField"])
    add_introspection_rules(
        [], ["^sentry\.db\.models\.fields\.citext\.CIEmailField"])


def create_citext_extension(using, **kwargs):
Ejemplo n.º 57
0
 def find(kls, name):
     if name in kls.statuses:
         return kls.statuses[name]
     return six.add_metaclass(StatusMeta)(type(name, (Status, ), {}))
Ejemplo n.º 58
0
        else:
            raise TypeError("Expected an OID, got " + str(type(mech)))

        minor_status = ffi.new("OM_uint32[1]")
        out_name = ffi.new("gss_name_t[1]")
        try:
            retval = C.gss_canonicalize_name(minor_status, self._name[0], ffi.addressof(oid), out_name)
            if GSS_ERROR(retval):
                raise _exception_for_status(retval, minor_status[0])
            return MechName(out_name, mech)
        except:
            C.gss_release_name(minor_status, out_name)


# Add metaclass in Python 2/3 compatible way:
Name = six.add_metaclass(_NameMeta)(Name)


class MechName(Name):
    """
    Represents a GSSAPI Mechanism Name (MN) as obtained by
    :meth:`~gssapi.names.Name.canonicalize` or as the
    :attr:`~gssapi.ctx.AcceptContext.peer_name` property of an :class:`~gssapi.ctx.AcceptContext`.

    Don't construct instances of this class directly; use
    :meth:`~gssapi.names.Name.canonicalize` on a :class:`Name` to create a :class:`MechName`.
    """

    def __init__(self, name, mech_type):
        """Don't construct instances of this class directly; This object will acquire
        ownership of `name`, and release the associated storage when it is deleted."""
Ejemplo n.º 59
0
# not use this file except in compliance with the License. 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
six.add_metaclass(type)


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = """
---
module: docker_facts
version_added: '2.6'
short_description: Gather list of volumes, images, containers
notes:
    - When specifying mulitple filters, only assets matching B(all) filters
      will be returned.
description: