Skip to content

feat(idempotency): support dataclasses & pydantic models payloads #908

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
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
Persistence layers supporting idempotency
"""

import datetime
import hashlib
import json
Expand Down Expand Up @@ -226,7 +225,13 @@ def _generate_hash(self, data: Any) -> str:
Hashed representation of the provided data

"""
data = getattr(data, "raw_event", data) # could be a data class depending on decorator order
if hasattr(data, "__dataclass_fields__"):
import dataclasses

data = dataclasses.asdict(data)
else:
data = getattr(data, "raw_event", data)

hashed_data = self.hash_function(json.dumps(data, cls=Encoder, sort_keys=True).encode())
return hashed_data.hexdigest()

Expand Down
30 changes: 30 additions & 0 deletions tests/functional/idempotency/test_idempotency.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,3 +1057,33 @@ def two(data):
assert one(data=mock_event) == "one"
assert two(data=mock_event) == "two"
assert len(persistence_store.table.method_calls) == 4


def test_idempotent_function_dataclasses():
try:
# Scenario idempotent_function should allow for python dataclasses
from dataclasses import asdict, dataclass

@dataclass
class Foo:
name: str

mock_event = Foo(name="Bar")
persistence_layer = MockPersistenceLayer(
"test-func.record_handler#" + hashlib.md5(serialize(asdict(mock_event)).encode()).hexdigest()
)
expected_result = {"message": "Foo"}

@idempotent_function(persistence_store=persistence_layer, data_keyword_argument="record")
def record_handler(record):
assert isinstance(record, Foo)
return expected_result

# WHEN calling the function
result = record_handler(record=mock_event)
# THEN we expect the function to execute successfully
assert result == expected_result

except ModuleNotFoundError:
# Python 3.6
pass