Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idiomatic & easy to read way of defining events #21

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
.tox
.coverage
.cache
venv
cq.egg-info
*.pyc
*.log
*.bak
Expand Down
61 changes: 51 additions & 10 deletions cq/events.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,54 @@
import datetime
import uuid
from .genuuid import genuuid
from datetime import datetime
from pyrsistent import field
from pyrsistent import PRecord
from pyrsistent import InvariantException


class Event:
def __init__(self, id, name, aggregate_id, data=None, ts=None):
self.id = id
self.name = name
self.aggregate_id = aggregate_id
self.data = data
self.ts = ts or datetime.datetime.now()
def isoformat(format, dt):
return dt.isoformat()

def __str__(self):
return '%s | %s | %s' % (self.name, self.aggregate_id, self.ts)

def get_datetime(val=None):
if not val:
return datetime.utcnow()
return val


def get_id():
return genuuid()


class EventBody(PRecord):
"""
Base class for `Event.data` field definition.
Note: I would suggest `Event` name instead.
"""
pass


class Event(PRecord):
"""
Base event class that specifies must have event fields.
Note: I would suggest `EventEnvelope` name instead.
"""
# pyrsistent style event class, like the simplicity of the syntax
# UUID & date validation could be added easily.
# Serialization is pretty much out of the box here as well.
id = field(mandatory=True, type=str, initial=get_id)
aggregate_id = field(mandatory=True, type=str)
name = field(mandatory=True, type=str)
ts = field(
mandatory=True,
type=datetime,
# use `get_datetime` is ts is not provided on init
initial=get_datetime,
# use `get_datetime` if `ts=None` on init
factory=get_datetime,
serializer=isoformat
)

# type below should be PRecord or None.
# `dict` is left for now, to allieviate fixing alll the failing tests
data = field(type=(EventBody, dict, type(None)))
79 changes: 79 additions & 0 deletions cq/tests/test_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from ..storages import LocalMemoryStorage
from ..storages import Storage
from cq import events
from datetime import datetime
from freezegun import freeze_time
from unittest import mock
import pytest


# Base `Event` class tests.

def test_assigns_all_properties():
d = datetime.utcnow()
e = events.Event(id='evt', aggregate_id='agg', ts=d, name='evt_name', data=None)

assert e.id == 'evt'
assert e.aggregate_id == 'agg'
assert e.ts == d
assert e.name == 'evt_name'


def test_requires_needed_properties():
with pytest.raises(events.InvariantException) as exc:
e = events.Event()


@freeze_time('2000-1-1')
@mock.patch.object(events, 'genuuid', return_value='evt_uuid')
def test_default_values_fields(_):
e = events.Event(aggregate_id='agg', name='evt_name')

assert e.id == 'evt_uuid'
assert e.aggregate_id == 'agg'
assert e.ts == datetime(2000, 1, 1)
assert e.name == 'evt_name'


@freeze_time('2000-1-1')
@mock.patch.object(events, 'genuuid', return_value='evt_uuid')
def test_base_serialization(_):
d = datetime.utcnow()
e = events.Event(id='evt', aggregate_id='agg', ts=d, name='evt_name', data=None)

assert e.serialize() == {
'id': 'evt',
'aggregate_id': 'agg',
'data': None,
'name': 'evt_name',
'ts': '2000-01-01T00:00:00'
}


# More complex tests against event data nesting & serialization

class UserCreatedEvent(events.EventBody):
"""
Sample event body class for User.Created event.
"""
name = events.field(mandatory=True, type=str)
email = events.field(mandatory=True, type=str)
age = events.field(type=int)


@freeze_time('2000-1-1')
def test_complex_serialization():
data = UserCreatedEvent(name='John', email='[email protected]', age=20)
e = events.Event(id='evt', aggregate_id='agg', name='evt_name', data=data)

assert e.serialize() == {
'id': 'evt',
'aggregate_id': 'agg',
'name': 'evt_name',
'ts': '2000-01-01T00:00:00',
'data': {
'name': 'John',
'email': '[email protected]',
'age': 20
}
}
25 changes: 16 additions & 9 deletions cq/tests/test_storages.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from ..genuuid import genuuid
from ..storages import LocalMemoryStorage
from ..storages import Storage
from datetime import datetime
from pyrsistent import PRecord, field
from unittest import mock
import pytest

Expand Down Expand Up @@ -28,21 +31,25 @@ def test_store(publish):


def test_local__append(local_storage):
local_storage.store('User.Registered', 'JOE_ID', {'name': 'joe'}, 'TS')
local_storage.store('User.Registered', 'JANE_ID', {'name': 'jane'}, 'TS')
local_storage.store('User.Activated', 'JOE_ID', ts='TS')
ts = datetime.utcnow()

local_storage.store('User.Registered', 'JOE_ID', {'name': 'joe'}, ts)
local_storage.store('User.Registered', 'JANE_ID', {'name': 'jane'}, ts)
local_storage.store('User.Activated', 'JOE_ID', ts=ts)

assert [(e.name, e.aggregate_id, e.data, e.ts) for e in local_storage.events] == [
('User.Registered', 'JOE_ID', {'name': 'joe'}, 'TS'),
('User.Registered', 'JANE_ID', {'name': 'jane'}, 'TS'),
('User.Activated', 'JOE_ID', None, 'TS'),
('User.Registered', 'JOE_ID', {'name': 'joe'}, ts),
('User.Registered', 'JANE_ID', {'name': 'jane'}, ts),
('User.Activated', 'JOE_ID', None, ts),
]


def test_local__get_events(local_storage):
local_storage.store('User.Registered', 'JOE_ID', {'name': 'joe'}, 'TS')
local_storage.store('User.Registered', 'JANE_ID', {'name': 'jane'}, 'TS')
local_storage.store('User.Activated', 'JOE_ID', {'name': 'joe'}, 'TS')
ts = datetime.utcnow()

local_storage.store('User.Registered', 'JOE_ID', {'name': 'joe'}, ts)
local_storage.store('User.Registered', 'JANE_ID', {'name': 'jane'}, ts)
local_storage.store('User.Activated', 'JOE_ID', {'name': 'joe'}, ts)

assert [(e.name, e.aggregate_id) for e in local_storage.get_events('JOE_ID')] == [
('User.Registered', 'JOE_ID'),
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def get_packages(top):
packages=get_packages('cq'),
include_package_data=True,
install_requires=[
'pyrsistent',
'jsonfield', # TODO: only needed django, make it optional
],
)