Esempio n. 1
0
def test_any_with_discriminant():
    schema = Schema({
        'implementation':
        Union({
            'type': 'A',
            'a-value': str,
        }, {
            'type': 'B',
            'b-value': int,
        }, {
            'type': 'C',
            'c-value': bool,
        },
              discriminant=lambda value, alternatives: filter(
                  lambda v: v['type'] == value['type'], alternatives))
    })
    try:
        schema({'implementation': {
            'type': 'C',
            'c-value': None,
        }})
    except MultipleInvalid as e:
        assert_equal(
            str(e),
            'expected bool for dictionary value @ data[\'implementation\'][\'c-value\']'
        )
    else:
        assert False, "Did not raise correct Invalid"
Esempio n. 2
0
def test_any_with_discriminant():
    schema = Schema({
        'implementation': Union({
            'type': 'A',
            'a-value': str,
        }, {
            'type': 'B',
            'b-value': int,
        }, {
            'type': 'C',
            'c-value': bool,
        }, discriminant=lambda value, alternatives: filter(lambda v: v['type'] == value['type'], alternatives))
    })

    with raises(MultipleInvalid, "expected bool for dictionary value @ data[\'implementation\'][\'c-value\']"):
        assert schema({
            'implementation': {
                'type': 'C',
                'c-value': None
            }
        })
Esempio n. 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)
Esempio n. 4
0
class VerificationMethod:
    """Representation of DID Document Verification Methods."""

    _validator = Schema(
        {
            "id": All(str, DIDUrl.validate),
            "type": str,
            "controller": All(str, DID.validate),
            All(str, verification_material): Union(str, dict),
        },
        required=True,
        extra=ALLOW_EXTRA,
    )

    @validate_init(id_=DIDUrl, suite=VerificationSuite, controller=DID)
    def __init__(self, id_: DIDUrl, suite: VerificationSuite, controller: DID,
                 material: Any, **extra):
        """Initialize VerificationMethod."""
        self._id = id_
        self._suite = suite
        self._controller = controller
        self._material = material
        self.extra = extra

    def __eq__(self, other):
        """Test equality."""
        if not isinstance(other, VerificationMethod):
            return False
        return (self._id == other._id and self._suite == other._suite
                and self._controller == other._controller
                and self._material == other._material
                and self.extra == other.extra)

    # pylint: disable=invalid-name
    @property
    def id(self):
        """Return id."""
        return self._id

    @property
    def suite(self):
        """Return suite."""
        return self._suite

    @property
    def type(self):
        """Return suite type."""
        return self._suite.type

    @property
    def controller(self):
        """Return controller."""
        return self._controller

    @property
    def material(self):
        """Return material."""
        return self._material

    def serialize(self):
        """Return serialized representation of VerificationMethod."""
        return {
            "id": str(self.id),
            "type": self.type,
            "controller": str(self.controller),
            self.suite.verification_material_prop: self.material,
            **self.extra,
        }

    @classmethod
    @wrap_validation_error(
        VerificationMethodValidationError,
        message="Failed to validate verification method",
    )
    def validate(cls, value: dict):
        """Validate against verification method."""
        return cls._validator(value)

    @classmethod
    @wrap_validation_error(
        VerificationMethodValidationError,
        message="Failed to deserialize verification method",
    )
    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)