Skip to content

Black formatter #51

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

Merged
merged 12 commits into from
Jul 9, 2020
Merged
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
4 changes: 4 additions & 0 deletions .isort.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[settings]
line_length = 80
multi_line_output = 3
include_trailing_comma = True
10 changes: 10 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
repos:
- repo: https://github.com/timothycrosley/isort/
rev: 5.0.4
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 19.10b0
hooks:
- id: black
language_version: python3.8
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,14 @@ the same API. It will use semantic versioning with following rules:
[CNCF's Slack workspace](https://slack.cncf.io/).
- Email: https://lists.cncf.io/g/cncf-cloudevents-sdk
- Contact for additional information: Denis Makogon (`@denysmakogon` on slack).

## Maintenance

We use black and isort for autoformatting. We setup a tox environment to reformat
the codebase.

e.g.
```python
pip install tox
tox -e reformat
```
3 changes: 1 addition & 2 deletions cloudevents/sdk/converters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
# License for the specific language governing permissions and limitations
# under the License.

from cloudevents.sdk.converters import binary
from cloudevents.sdk.converters import structured
from cloudevents.sdk.converters import binary, structured

TypeBinary = binary.BinaryHTTPCloudEventConverter.TYPE
TypeStructured = structured.JSONHTTPCloudEventConverter.TYPE
6 changes: 2 additions & 4 deletions cloudevents/sdk/converters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def read(
event,
headers: dict,
body: typing.IO,
data_unmarshaller: typing.Callable
data_unmarshaller: typing.Callable,
) -> base.BaseEvent:
raise Exception("not implemented")

Expand All @@ -37,8 +37,6 @@ def can_read(self, content_type: str) -> bool:
raise Exception("not implemented")

def write(
self,
event: base.BaseEvent,
data_marshaller: typing.Callable
self, event: base.BaseEvent, data_marshaller: typing.Callable
) -> (dict, object):
raise Exception("not implemented")
6 changes: 2 additions & 4 deletions cloudevents/sdk/converters/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from cloudevents.sdk import exceptions, types
from cloudevents.sdk.converters import base
from cloudevents.sdk.event import base as event_base
from cloudevents.sdk.event import v03, v1
from cloudevents.sdk.event import v1, v03


class BinaryHTTPCloudEventConverter(base.Converter):
Expand All @@ -44,9 +44,7 @@ def read(
return event

def write(
self,
event: event_base.BaseEvent,
data_marshaller: types.MarshallerType
self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType
) -> (dict, bytes):
return event.MarshalBinary(data_marshaller)

Expand Down
5 changes: 1 addition & 4 deletions cloudevents/sdk/converters/structured.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import typing

from cloudevents.sdk import types

from cloudevents.sdk.converters import base
from cloudevents.sdk.event import base as event_base

Expand Down Expand Up @@ -43,9 +42,7 @@ def read(
return event

def write(
self,
event: event_base.BaseEvent,
data_marshaller: types.MarshallerType
self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType
) -> (dict, bytes):
http_headers = {"content-type": self.MIME_TYPE}
return http_headers, event.MarshalJSON(data_marshaller).encode("utf-8")
Expand Down
9 changes: 4 additions & 5 deletions cloudevents/sdk/event/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str:
def UnmarshalJSON(
self,
b: typing.Union[str, bytes],
data_unmarshaller: types.UnmarshallerType
data_unmarshaller: types.UnmarshallerType,
):
raw_ce = json.loads(b)

Expand All @@ -228,9 +228,9 @@ def UnmarshalBinary(
self,
headers: dict,
body: typing.Union[bytes, str],
data_unmarshaller: types.UnmarshallerType
data_unmarshaller: types.UnmarshallerType,
):
if 'ce-specversion' not in headers:
if "ce-specversion" not in headers:
raise ValueError("Missing required attribute: 'specversion'")
for header, value in headers.items():
header = header.lower()
Expand All @@ -244,8 +244,7 @@ def UnmarshalBinary(
raise ValueError(f"Missing required attributes: {missing_attrs}")

def MarshalBinary(
self,
data_marshaller: types.MarshallerType
self, data_marshaller: types.MarshallerType
) -> (dict, bytes):
if data_marshaller is None:
data_marshaller = json.dumps
Expand Down
14 changes: 8 additions & 6 deletions cloudevents/sdk/event/opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ def set(self, new_value):
if self.is_required and is_none:
raise ValueError(
"Attribute value error: '{0}', "
"" "invalid new value."
.format(self.name)
""
"invalid new value.".format(self.name)
)

self.value = new_value
Expand All @@ -37,7 +37,9 @@ def required(self):
return self.is_required

def __eq__(self, obj):
return isinstance(obj, Option) and \
obj.name == self.name and \
obj.value == self.value and \
obj.is_required == self.is_required
return (
isinstance(obj, Option)
and obj.name == self.name
and obj.value == self.value
and obj.is_required == self.is_required
)
24 changes: 8 additions & 16 deletions cloudevents/sdk/event/v03.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,18 @@
# License for the specific language governing permissions and limitations
# under the License.

from cloudevents.sdk.event import base
from cloudevents.sdk.event import opt
from cloudevents.sdk.event import base, opt


class Event(base.BaseEvent):
_ce_required_fields = {
'id',
'source',
'type',
'specversion'
}
_ce_required_fields = {"id", "source", "type", "specversion"}

_ce_optional_fields = {
'datacontentencoding',
'datacontenttype',
'schemaurl',
'subject',
'time'
"datacontentencoding",
"datacontenttype",
"schemaurl",
"subject",
"time",
}

def __init__(self):
Expand All @@ -40,9 +34,7 @@ def __init__(self):

self.ce__datacontenttype = opt.Option("datacontenttype", None, False)
self.ce__datacontentencoding = opt.Option(
"datacontentencoding",
None,
False
"datacontentencoding", None, False
)
self.ce__subject = opt.Option("subject", None, False)
self.ce__time = opt.Option("time", None, False)
Expand Down
19 changes: 4 additions & 15 deletions cloudevents/sdk/event/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,13 @@
# License for the specific language governing permissions and limitations
# under the License.

from cloudevents.sdk.event import base
from cloudevents.sdk.event import opt
from cloudevents.sdk.event import base, opt


class Event(base.BaseEvent):
_ce_required_fields = {
'id',
'source',
'type',
'specversion'
}

_ce_optional_fields = {
'datacontenttype',
'dataschema',
'subject',
'time'
}
_ce_required_fields = {"id", "source", "type", "specversion"}

_ce_optional_fields = {"datacontenttype", "dataschema", "subject", "time"}

def __init__(self):
self.ce__specversion = opt.Option("specversion", "1.0", True)
Expand Down
12 changes: 3 additions & 9 deletions cloudevents/sdk/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@

class UnsupportedEvent(Exception):
def __init__(self, event_class):
super().__init__(
"Invalid CloudEvent class: '{0}'".format(event_class)
)
super().__init__("Invalid CloudEvent class: '{0}'".format(event_class))


class InvalidDataUnmarshaller(Exception):
Expand All @@ -27,16 +25,12 @@ def __init__(self):

class InvalidDataMarshaller(Exception):
def __init__(self):
super().__init__(
"Invalid data marshaller, is not a callable"
)
super().__init__("Invalid data marshaller, is not a callable")


class NoSuchConverter(Exception):
def __init__(self, converter_type):
super().__init__(
"No such converter {0}".format(converter_type)
)
super().__init__("No such converter {0}".format(converter_type))


class UnsupportedEventConverter(Exception):
Expand Down
57 changes: 29 additions & 28 deletions cloudevents/sdk/http_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,8 @@
import typing
import uuid

from cloudevents.sdk import converters
from cloudevents.sdk import marshaller
from cloudevents.sdk import types

from cloudevents.sdk.event import v03, v1
from cloudevents.sdk import converters, marshaller, types
from cloudevents.sdk.event import v1, v03

_marshaller_by_format = {
converters.TypeStructured: lambda x: x,
Expand All @@ -43,7 +40,7 @@ def _json_or_string(content: typing.Union[str, bytes]):
return content


class CloudEvent():
class CloudEvent:
"""
Python-friendly cloudevent class supporting v1 events
Supports both binary and structured mode CloudEvents
Expand All @@ -54,7 +51,7 @@ def from_http(
cls,
data: typing.Union[str, bytes],
headers: typing.Dict[str, str],
data_unmarshaller: types.UnmarshallerType = None
data_unmarshaller: types.UnmarshallerType = None,
):
"""Unwrap a CloudEvent (binary or structured) from an HTTP request.
:param data: the HTTP request body
Expand All @@ -68,18 +65,17 @@ def from_http(
data_unmarshaller = _json_or_string

event = marshaller.NewDefaultHTTPMarshaller().FromRequest(
v1.Event(), headers, data, data_unmarshaller)
v1.Event(), headers, data, data_unmarshaller
)
attrs = event.Properties()
attrs.pop('data', None)
attrs.pop('extensions', None)
attrs.pop("data", None)
attrs.pop("extensions", None)
attrs.update(**event.extensions)

return cls(attrs, event.data)

def __init__(
self,
attributes: typing.Dict[str, str],
data: typing.Any = None
self, attributes: typing.Dict[str, str], data: typing.Any = None
):
"""
Event Constructor
Expand All @@ -97,28 +93,31 @@ def __init__(
"""
self._attributes = {k.lower(): v for k, v in attributes.items()}
self.data = data
if 'specversion' not in self._attributes:
self._attributes['specversion'] = "1.0"
if 'id' not in self._attributes:
self._attributes['id'] = str(uuid.uuid4())
if 'time' not in self._attributes:
self._attributes['time'] = datetime.datetime.now(
datetime.timezone.utc).isoformat()

if self._attributes['specversion'] not in _required_by_version:
if "specversion" not in self._attributes:
self._attributes["specversion"] = "1.0"
if "id" not in self._attributes:
self._attributes["id"] = str(uuid.uuid4())
if "time" not in self._attributes:
self._attributes["time"] = datetime.datetime.now(
datetime.timezone.utc
).isoformat()

if self._attributes["specversion"] not in _required_by_version:
raise ValueError(
f"Invalid specversion: {self._attributes['specversion']}")
f"Invalid specversion: {self._attributes['specversion']}"
)
# There is no good way to default 'source' and 'type', so this
# checks for those (or any new required attributes).
required_set = _required_by_version[self._attributes['specversion']]
required_set = _required_by_version[self._attributes["specversion"]]
if not required_set <= self._attributes.keys():
raise ValueError(
f"Missing required keys: {required_set - attributes.keys()}")
f"Missing required keys: {required_set - attributes.keys()}"
)

def to_http(
self,
format: str = converters.TypeStructured,
data_marshaller: types.MarshallerType = None
data_marshaller: types.MarshallerType = None,
) -> (dict, typing.Union[bytes, str]):
"""
Returns a tuple of HTTP headers/body dicts representing this cloudevent
Expand All @@ -133,15 +132,17 @@ def to_http(
data_marshaller = _marshaller_by_format[format]
if self._attributes["specversion"] not in _obj_by_version:
raise ValueError(
f"Unsupported specversion: {self._attributes['specversion']}")
f"Unsupported specversion: {self._attributes['specversion']}"
)

event = _obj_by_version[self._attributes["specversion"]]()
for k, v in self._attributes.items():
event.Set(k, v)
event.data = self.data

return marshaller.NewDefaultHTTPMarshaller().ToRequest(
event, format, data_marshaller)
event, format, data_marshaller
)

# Data access is handled via `.data` member
# Attribute access is managed via Mapping type
Expand Down
Loading