Exemplo n.º 1
0
    def test_to_document_and_to_aggregate() -> None:
        class _Event(Event):
            @dataclass
            class Attributes:
                foo: str

            attributes: Attributes

        class _EventMapper(EventMapper):
            event_type = _Event
            service_name = '_service_name'
            event_name = '_name'

            def decode(self, data: Dict[str, Any]) -> Event:
                return _Event(_Event.Attributes(foo=data['foo']))

            @staticmethod
            def map_attributes(msg: _Event.Attributes) -> Dict[str, Any]:
                return {'foo': msg.foo}

        evt = _Event(_Event.Attributes(foo=Id.generate().value()))

        sut = MongoDBEventPublisherMapper([_EventMapper()])

        doc = sut.to_document(evt)

        assert Id.validate(doc['id'])
        assert doc['name'] == '_service_name._name'
        assert doc['type'] == 'event'
        assert doc['payload'] == {'foo': evt.attributes.foo}
        assert (datetime.utcnow() - doc['occurred_on']).total_seconds() < 1

        agg: _Event = sut.to_aggregate(doc)

        assert agg.attributes.foo == evt.attributes.foo
Exemplo n.º 2
0
def test_event_and_event_mapper() -> None:
    class _EventTest(Event):
        @dataclass
        class Attributes:
            __slots__ = ('foo', )
            foo: str

        attributes: Attributes

    event = _EventTest(attributes=_EventTest.Attributes(foo='test'))

    assert Id.validate(event.meta.id)
    assert event.meta.type == 'event'
    assert event.attributes.foo == 'test'

    class _EventTestEventMapper(EventMapper):
        event_type = _EventTest
        service_name = 'test_service_name'
        event_name = 'test_name'

    event_mapper = _EventTestEventMapper()

    assert event_mapper.belongs_to(event)
    assert event_mapper.service_name == 'test_service_name'
    assert event_mapper.event_name == 'test_name'

    event_encoded = event_mapper.encode(event)

    assert event_encoded['attributes'] == asdict(event.attributes)
    event_decoded = event_mapper.decode(event_encoded)

    assert event_decoded.meta == event.meta
    assert event_decoded.attributes == event.attributes
Exemplo n.º 3
0
def _add_validations_errors(err: ValidationError,
                            errors: list[APIError]) -> list[APIError]:
    _error = errors[0]
    _error.code = 'invalid_request_validation'
    errors = []
    for error in err.errors():
        errors.append(
            APIError(
                **{
                    **_error.dict(),
                    'id':
                    Id.generate().value(),
                    'title':
                    error['msg'],
                    'detail':
                    dumps({
                        'field': list(error['loc'])[1:],
                        'message': f'{error["msg"]}: {error["type"]}',
                    }).decode('utf-8'),
                    'source': {
                        'pointer': error['loc'][0]
                    },
                    'meta': {
                        'error_correlation_id': _error.id
                    },
                }))
    return errors
Exemplo n.º 4
0
    def test_to_documents_and_to_aggregates() -> None:
        class _Aggregate(Aggregate):
            _id: str

            def __init__(self, agg_id: str) -> None:
                self._id = agg_id

            def id(self) -> str:
                return self._id

        class _MongoDBBaseMapper(MongoDBBaseMapper):
            def to_aggregate(self, data: Dict[str, Any]) -> Union[Aggregate, Any]:
                return _Aggregate(data['agg_id'])

            def to_document(self, aggregate: Union[_Aggregate, Any]) -> Dict[str, Any]:
                return {'agg_id': aggregate.id()}

        the_agg = _Aggregate(Id.generate().value())

        sut = _MongoDBBaseMapper()

        docs = sut.to_documents([the_agg])
        aggs = sut.to_aggregates(docs)
        for agg in aggs:
            assert agg.id() == the_agg.id()
    async def test_generate_and_read() -> None:
        user_id = UserIdMother.random()
        secret = Id.generate().value()

        sut = JWTTokenFactory(lambda: datetime.utcnow(), secret)

        token = await sut.generate(user_id, 1)
        auth_user_id = await sut.read(token)

        assert user_id.value() == auth_user_id.value()
Exemplo n.º 6
0
def test_id_is_not_valid() -> None:
    assert not Id.validate('0')
Exemplo n.º 7
0
def test_id_fails_with_invalid_uuid() -> None:
    pytest.raises(IdInvalidError, lambda: Id('0'))
Exemplo n.º 8
0
def test_id_str_returns_value() -> None:
    id_ = Id.generate()
    assert id_.value() == id_.__str__()
Exemplo n.º 9
0
def test_id_generated_is_valid() -> None:
    id_ = Id.generate()
    assert Id.validate(id_.value())