Ejemplo n.º 1
0
class Mandal(DbObject):
    schema = Schema(
        {
            Required('name'):
            All(str, Length(min=1)),
            'location':
            All(
                Schema({
                    Inclusive('lat', 'latlong'): float,
                    Inclusive('long', 'latlong'): float,
                })),
            'date_established':
            datetime,
            Required('primary_contact'):
            str
        },
        extra=PREVENT_EXTRA)

    def __init__(self):
        self._collection = 'mandal'
        self._fields = {}
        self._init_db_object()

    @classmethod
    def init_using_params(cls, data):
        instance = cls()
        instance.load(data)
        return instance

    @classmethod
    def init_empty_object(cls):
        return cls()

    def load(self, d):
        self._fields = Mandal.schema(d)
Ejemplo n.º 2
0
def test_inclusive_defaults():
    schema = Schema({
        Inclusive('x', 'stuff', default=3): int,
        Inclusive('y', 'stuff', default=4): int,
        })

    r = schema({})
    assert_equal(r, {'x': 3, 'y': 4})

    try:
        r = schema({'x': 1})
    except MultipleInvalid as e:
        assert_equal(str(e),
                     "some but not all values in the same group of inclusion 'stuff' @ data[<stuff>]")
    else:
        assert False, "Did not raise Invalid for incomplete Inclusive group with defaults"
Ejemplo n.º 3
0
def test_inclusive():
    schema = Schema({
        Inclusive('x', 'stuff'): int,
        Inclusive('y', 'stuff'): int,
    })

    r = schema({})
    assert r == {}

    r = schema({'x': 1, 'y': 2})
    assert r == {'x': 1, 'y': 2}

    try:
        r = schema({'x': 1})
    except MultipleInvalid as e:
        assert str(
            e
        ) == "some but not all values in the same group of inclusion 'stuff' @ data[<stuff>]"
    else:
        assert False, "Did not raise Invalid for incomplete Inclusive group"
Ejemplo n.º 4
0
class HumiditySensor:

    validate = Schema(
        {
            Required('channel'): str,
            Required('event'): str,
            Required("user"): str,
            Required('params'): {
                Inclusive("HumiditySensorID", "HumiditySensorGroup"): str,
                Exclusive("HumidityLevel", "HumiditySensorGroup"): float,
            },
        },
        extra=ALLOW_EXTRA)
Ejemplo n.º 5
0
class PresenceSensor:

    validate = Schema(
        {
            Required('channel'): str,
            Required('event'): str,
            Required("user"): str,
            Required('params'): {
                Inclusive("PresenceSensorID", "PresenceSensorGroup"): str,
                Exclusive("PresenceDistance", "PresenceSensorGroup"): float,
                Exclusive("PresenceTime", "PresenceSensorGroup"): str,
            },
        },
        extra=ALLOW_EXTRA)
Ejemplo n.º 6
0
class Presence:

    validate = Schema(
        {
            Required('channel'): str,
            Required('event'): str,
            Required("user"): str,
            Required('params'): {
                Inclusive("sensorID", "grupo"): str,
                Exclusive("distance", "grupo"): str,
                Exclusive("time", "grupo"): str,
            },
        },
        extra=ALLOW_EXTRA)
Ejemplo n.º 7
0
def test_description():
    marker = Marker(Schema(str), description='Hello')
    assert marker.description == 'Hello'

    optional = Optional('key', description='Hello')
    assert optional.description == 'Hello'

    exclusive = Exclusive('alpha', 'angles', description='Hello')
    assert exclusive.description == 'Hello'

    inclusive = Inclusive('alpha', 'angles', description='Hello')
    assert inclusive.description == 'Hello'

    required = Required('key', description='Hello')
    assert required.description == 'Hello'
Ejemplo n.º 8
0
class PlantSensor:

    validate = Schema(
        {
            Required('channel'): str,
            Required('event'): str,
            Required("user"): str,
            Required('params'): {
                Inclusive("PlantSensorID", "PlantSensorGroup"): str,
                Exclusive("PlantMoisture", "PlantSensorGroup"): float,
                Exclusive("PlantLight", "PlantSensorGroup"): float,
                Exclusive("PlantTemperature", "PlantSensorGroup"): float,
                Exclusive("PlantConductivity", "PlantSensorGroup"): float,
            },
        },
        extra=ALLOW_EXTRA)
Ejemplo n.º 9
0
                                    'version.txt')
    return get_contents(app_version_path)


base_schema = Schema({
    Required('app_version'):
    text_type,
    Required('backstop'):
    bool,
    Required('base_repository'):
    text_type,
    Required('build_date'):
    int,
    Required('build_number'):
    int,
    Inclusive('comm_base_repository', 'comm'):
    text_type,
    Inclusive('comm_head_ref', 'comm'):
    text_type,
    Inclusive('comm_head_repository', 'comm'):
    text_type,
    Inclusive('comm_head_rev', 'comm'):
    text_type,
    Required('do_not_optimize'): [text_type],
    Required('existing_tasks'): {
        text_type: text_type
    },
    Required('filters'): [text_type],
    Required('head_ref'):
    text_type,
    Required('head_repository'):
Ejemplo n.º 10
0
import aiohttp
import nio
import nio.responses
import nio.exceptions

from opsdroid import const, events
from opsdroid.connector import Connector, register_event
from voluptuous import Required, Inclusive

from . import events as matrixevents
from .create_events import MatrixEventCreator
from .html_cleaner import clean

_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = {
    Inclusive("mxid", "login"): str,
    Inclusive("password", "login"): str,
    "access_token": str,
    Required("rooms"): dict,
    "homeserver": str,
    "nick": str,
    "room_specific_nicks": bool,
    "device_name": str,
    "device_id": str,
    "store_path": str,
    "enable_encryption": bool,
}

__all__ = ["ConnectorMatrix"]

Ejemplo n.º 11
0
    Required('name'):
    str,
    'product_type':
    str,
    Required('statistic'):
    In(STATS.keys(), msg=available_stats_msg),
    'statistic_args':
    dict,
    'output_params':
    dict,
    'file_path_template':
    All(str, valid_format_string(valid_filepath_fields)),
})

spatial_attrs = {
    Inclusive('x', 'proj'): Any(float, int),
    Inclusive('y', 'proj'): Any(float, int),
    Inclusive('latitude', 'geo'): Any(float, int),
    Inclusive('longitude', 'geo'): Any(float, int)
}

available_drivers_msg = (
    'not a valid output driver (available drivers are {})'.format(", ".join(
        list(OUTPUT_DRIVERS.keys()))))

storage_schema = Schema({
    'driver':
    In(OUTPUT_DRIVERS.keys(), msg=available_drivers_msg),
    'tile_size':
    spatial_attrs,
    'resolution':
Ejemplo n.º 12
0
                                'version_display.txt')
    return get_contents(version_path)


def get_app_version(product_dir='browser'):
    app_version_path = os.path.join(GECKO, product_dir, 'config',
                                    'version.txt')
    return get_contents(app_version_path)


base_schema = Schema({
    Required('app_version'): text_type,
    Required('base_repository'): text_type,
    Required('build_date'): int,
    Required('build_number'): int,
    Inclusive('comm_base_repository', 'comm'): text_type,
    Inclusive('comm_head_ref', 'comm'): text_type,
    Inclusive('comm_head_repository', 'comm'): text_type,
    Inclusive('comm_head_rev', 'comm'): text_type,
    Required('do_not_optimize'): [text_type],
    Required('existing_tasks'): {
        text_type: text_type
    },
    Required('filters'): [text_type],
    Required('head_ref'): text_type,
    Required('head_repository'): text_type,
    Required('head_rev'): text_type,
    Required('hg_branch'): text_type,
    Required('level'): text_type,
    Required('message'): text_type,
    Required('moz_build_date'): text_type,
Ejemplo n.º 13
0
                                'version_display.txt')
    return get_contents(version_path)


def get_app_version(product_dir='browser'):
    app_version_path = os.path.join(GECKO, product_dir, 'config',
                                    'version.txt')
    return get_contents(app_version_path)


base_schema = {
    Required('app_version'): basestring,
    Required('base_repository'): basestring,
    Required('build_date'): int,
    Required('build_number'): int,
    Inclusive('comm_base_repository', 'comm'): basestring,
    Inclusive('comm_head_ref', 'comm'): basestring,
    Inclusive('comm_head_repository', 'comm'): basestring,
    Inclusive('comm_head_rev', 'comm'): basestring,
    Required('do_not_optimize'): [basestring],
    Required('existing_tasks'): {
        basestring: basestring
    },
    Required('filters'): [basestring],
    Required('head_ref'): basestring,
    Required('head_repository'): basestring,
    Required('head_rev'): basestring,
    Required('hg_branch'): basestring,
    Required('level'): basestring,
    Required('message'): basestring,
    Required('moz_build_date'): basestring,
Ejemplo n.º 14
0
                                    "version.txt")
    return get_contents(app_version_path)


base_schema = Schema({
    Required("app_version"):
    text_type,
    Required("backstop"):
    bool,
    Required("base_repository"):
    text_type,
    Required("build_date"):
    int,
    Required("build_number"):
    int,
    Inclusive("comm_base_repository", "comm"):
    text_type,
    Inclusive("comm_head_ref", "comm"):
    text_type,
    Inclusive("comm_head_repository", "comm"):
    text_type,
    Inclusive("comm_head_rev", "comm"):
    text_type,
    Required("do_not_optimize"): [text_type],
    Required("existing_tasks"): {
        text_type: text_type
    },
    Required("filters"): [text_type],
    Required("head_ref"):
    text_type,
    Required("head_repository"):
Ejemplo n.º 15
0
class Settings(object):
    """ Holds settings for libary

    Attributes:
        configFile (String): Location of config file
    """
    _refresh_format = '%Y-%m-%d_%H:%M'
    _msg = 'accessToken, tokenType, expiresIn and refreshToken must exist together'
    _validate = Schema(
        {
            Required(BASE_KEY): {
                Required('clientID'):
                All(str, Length(min=61)),
                Required('clientSecret'):
                All(str, Length(min=61)),
                Optional('webPort', default=8080):
                All(int, Range(min=1024)),
                Inclusive('accessToken', 'token', msg=_msg):
                All(str, Length(min=61)),
                Inclusive('tokenType', 'token', msg=_msg):
                All(str, Length(min=5)),
                Inclusive('refreshToken', 'token', msg=_msg):
                All(str, Length(min=61)),
                Inclusive('expiresIn', 'token', msg=_msg):
                All(str, Length(min=5)),
            }
        },
        extra=True)

    configFile = None

    def __init__(self, config):
        """Returns an Settings Object

        Args:
            config (String): Location of config file

        """
        self._config = {}
        # if not default and not config and not dataDict:
        #     raise Exception('You must provide one of dataDict or config')

        self.configFile = config
        self.readConfig()

        # check if we need to refresh the token
        if self._config.get('refreshToken') and self._config.get('expiresIn'):
            parsedExpired = datetime.strptime(self.expiresIn,
                                              self._refresh_format)
            if parsedExpired < datetime.now():
                log.info("Need to refresh token ...")
                self._refreshToken()

    def _refreshToken(self):
        """ Send token refresh request to amazon
        """
        # POST /auth/o2/token HTTP/l.l
        #  Host: api.amazon.com
        #  Content-Type: application/x-www-form-urlencoded;charset=UTF-8
        #  grant_type=refresh_token
        #  &refresh_token=Atzr|IQEBLzAtAhRPpMJxdwVz2Nn6f2y-tpJX2DeX...
        #  &client_id=foodev
        #  &client_secret=Y76SDl2F
        #
        # HTTP/l.l 200 OK
        #  Content-Type: application/json;charset UTF-8
        #  Cache-Control: no-store
        #  Pragma: no-cache
        #  {
        #     "access_token":"Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...",
        #     "token_type":"bearer",
        #     "expires_in":3600,
        #     "refresh_token":"Atzr|IQEBLzAtAhRPpMJxdwVz2Nn6f2y-tpJX2DeX..."
        #  }
        res = requests.post(
            url='https://api.amazon.com/auth/o2/token',
            headers={
                'Content-Type':
                'application/x-www-form-urlencoded;charset=UTF-8'
            },
            data={
                'grant_type': 'refresh_token',
                'refresh_token': self.refreshToken,
                'client_id': self.clientID,
                'client_secret': self.clientSecret
            },
        )
        if res.status_code == 200:
            self.updateWithResponse(res.json())
        else:
            raise Exception('%s: %s' % (
                res.status_code,
                res.text,
            ))

    def readConfig(self):
        """ Read data from config file.

        Returns:
            Boolean: Success?
        """
        with open(self.configFile, 'r') as infile:
            data = yaml.load(infile)

        if self._validate(data):
            self._config.update(data[BASE_KEY])
            return True

    def writeConfig(self):
        """ Update data in config file.
        """
        if not self._config:
            raise Exception(
                "Unable to overwrite configfile %s with empty data" %
                (self.configFile))

        with open(self.configFile, 'r') as infile:
            data = yaml.load(infile)

        data[BASE_KEY].update(self._config)
        with open(self.configFile, 'w') as outfile:
            yaml.safe_dump(data, outfile, default_flow_style=False)
        return True

    def updateWithResponse(self, response):
        """ Update data and config file with response from amazon.

        Args:
            response (Dictionary): Response dict from amazon.

        Returns:
            Boolean: Success?
        """
        if response.get('access_token') and response.get('refresh_token'):
            return self.setAuthData(
                response['access_token'],
                response['token_type'],
                response['refresh_token'],
                response['expires_in'],
            )
        else:
            raise Exception("Invalid data for update: %s" % (response, ))

    def setAuthData(self, accessToken, tokenType, refreshToken, expiresIn):
        """ Set authentication Data

        Args:
            accessToken (String): Access Token
            tokenType (String): Access Token Type
            refreshToken (String): Refresh Token
            expiresIn (String): Datestring when Access Token needs to be refreshed

        Returns:
            Boolean: Success?
        """
        self._config['accessToken'] = str(accessToken)
        self._config['tokenType'] = str(tokenType)
        self._config['refreshToken'] = str(refreshToken)

        if isinstance(expiresIn, datetime):
            pass
        elif isinstance(expiresIn, (types.StringTypes, types.IntType)):
            expiresIn = datetime.now() + timedelta(seconds=int(expiresIn))
        else:
            raise Exception('Invalid value for expiresIn')
        self._config['expiresIn'] = expiresIn.strftime(self._refresh_format)
        return self.writeConfig()

    def __getattr__(self, name):
        """Overwrites class.__getattr__ to provide self._config values as attributes.

        Args:
            name (String): Name of the attribute

        Returns:
            TYPE: Description
        """
        if name in self._config:
            return self._config[name]
        raise AttributeError("'%s' object has no attribute '%s'" %
                             (self.__class__.__name__, name))

    def __repr__(self):
        """ Representation of class.

        Returns:
            String: Representation
        """
        return '<%s.%s object at %s data=%s>' % (self.__class__.__module__,
                                                 self.__class__.__name__,
                                                 hex(id(self)), self._config)
Ejemplo n.º 16
0
from common.enums import EmailResult

contact_schema = Schema(
    {"name": str, "email": Email(), "first_name": str, "last_name": str}, required=True
)

segment_schema = Schema({"name": str}, required=True)

template_schema = Schema({"name": str, "template": str}, required=True)

segment_contact_join_schema = Schema({"segment_id": Coerce(int)}, required=True)

settings_schema = Schema(
    {
        Inclusive("name", "from"): str,
        Inclusive("email", "from"): Email(),
        Inclusive("user", "auth"): str,
        Inclusive("password", "auth"): str,
    }
)


campaign_schema = Schema(
    {"segment_id": Coerce(int), "template_id": Coerce(int), "subject": str},
    required=True,
)

update_status_schema = Schema(
    {
        In(frozenset(result.value for result in EmailResult)): [