Example #1
0
def test_remove():
    """Verify that Remove works."""
    # remove dict keys
    schema = Schema({"weight": int,
                     Remove("color"): str,
                     Remove("amount"): int})
    out_ = schema({"weight": 10, "color": "red", "amount": 1})
    assert "color" not in out_ and "amount" not in out_

    # remove keys by type
    schema = Schema({"weight": float,
                     "amount": int,
                     # remvove str keys with int values
                     Remove(str): int,
                     # keep str keys with str values
                     str: str})
    out_ = schema({"weight": 73.4,
                   "condition": "new",
                   "amount": 5,
                   "left": 2})
    # amount should stay since it's defined
    # other string keys with int values will be removed
    assert "amount" in out_ and "left" not in out_
    # string keys with string values will stay
    assert "condition" in out_

    # remove value from list
    schema = Schema([Remove(1), int])
    out_ = schema([1, 2, 3, 4, 1, 5, 6, 1, 1, 1])
    assert_equal(out_, [2, 3, 4, 5, 6])

    # remove values from list by type
    schema = Schema([1.0, Remove(float), int])
    out_ = schema([1, 2, 1.0, 2.0, 3.0, 4])
    assert_equal(out_, [1, 2, 1.0, 4])
Example #2
0
def test_marker_hashable():
    """Verify that you can get schema keys, even if markers were used"""
    definition = {
        Required('x'): int, Optional('y'): float,
        Remove('j'): int, Remove(int): str, int: int
    }
    assert_equal(definition.get('x'), int)
    assert_equal(definition.get('y'), float)
    assert_true(Required('x') == Required('x'))
    assert_true(Required('x') != Required('y'))
    # Remove markers are not hashable
    assert_equal(definition.get('j'), None)
Example #3
0
    def deserialize(cls,
                    value: dict,
                    *,
                    options: Set[VerificationMethodOptions] = None):
        """Deserialize into VerificationMethod."""
        # Apply options
        if options:
            value = VerificationMethodOptions.apply(value, options)

        # Perform validation
        value = cls.validate(value)

        def _suite_and_material(value):
            suite = VerificationSuite.derive(value["type"], **value)
            material = value[suite.verification_material_prop]
            value["suite"] = suite
            value["material"] = material
            return value

        deserializer = Schema(
            All(
                {
                    Into("id", "id_"): All(str, DIDUrl.parse),
                    "controller": All(str, Coerce(DID)),
                },
                _suite_and_material,
                {
                    Remove("type"): str,
                    Remove(verification_material): Union(str, dict)
                },
            ),
            extra=ALLOW_EXTRA,
        )

        # Hydrate object
        value = deserializer(value)
        return cls(**value)
Example #4
0
import sys

from voluptuous import (ALLOW_EXTRA, REMOVE_EXTRA, All, Any, Remove, Replace,
                        Schema, SetTo)
from voluptuous.util import Strip

from weathergc.utils import html_to_dict

is_python3 = sys.version_info.major == 3
if is_python3:
    unicode = str

# top level validator, ensure we're dealing with a known file format
META_SCHEMA = Schema(
    {All('@xml:lang', SetTo('lang')): 'en-ca',
     Remove('@xmlns'): 'http://www.w3.org/2005/Atom',
     'author': {'name': 'Environment Canada',
                'uri': 'http://www.weather.gc.ca'},
     'logo': unicode,
     'rights': unicode,
     'title': unicode,
     'updated': unicode,
     Remove('entry'): Any(list, dict)},
    extra=REMOVE_EXTRA)

# Validator for each member of the 'entry' list in the feed.
# Includes some minor transformations to simplify later validations
ENTRY_SCHEMA = Schema(
    {'category': All({'@term': Any('Weather Forecasts', 'Current Conditions',
                                   'Warnings and Watches')}, dict.values,
                     ''.join),
Example #5
0
    ], Length(min=1)),
    Required('state', default='ready'): 'ready',
    Required('duration'): All(int, Range(min=1)),
})


get_game_validator = Schema({
    Required('team'): str,
    Required('team_members'): All([
        {
            Required('name'): str,
            Required('level'): All(int, Range(min=1)),
            Required('theme'): str,
            Required('id'): str,
            Required('level_max'): All(int, Range(min=1)),
            Remove('levels_obj'): BaseLevel
        }
    ], Length(min=1)),
    Required('state'): Any('ready', 'start', 'stop',
                           msg='Expected ready, start or stop'),
    Required('duration'): All(int, Range(min=1)),
    Required('remaining'): int
}, extra=REMOVE_EXTRA)


@web.middleware
async def error_middleware(request, handler):
    """
    This coroutine wraps exception in json response if an exception
    of type `Invalid`, `DoesntExist`, `GameConflict` or
    `LevelSet.DoneException` is raised. The json response has two field
Example #6
0
# -*- coding: utf-8 -*-
import re

from voluptuous import Schema, Remove, REMOVE_EXTRA


user_model_response = Schema({
    'email': basestring,
    'phone_numbers': [basestring],
    'transactions': [dict],
    'messages_remaining': int,
    'mailhook_id': basestring,
    'mailgun_route_id': basestring,
    'enabled': bool,
    'first_name': basestring,
    'last_name': basestring,
    Remove('_id'): None,
}, extra=REMOVE_EXTRA)


def validate_phone_number(number):
    return bool(re.search('^[\d]{10}$', number))