Skip to content

Commit

Permalink
🦄 refactor: message extra use dataclass
Browse files Browse the repository at this point in the history
  • Loading branch information
mic1on committed Nov 16, 2023
1 parent 8efbcc0 commit 9d5a8be
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/onestep/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys
import time
import uuid
from dataclasses import dataclass
from traceback import TracebackException
from typing import Optional, Any, Union

Expand All @@ -14,11 +15,15 @@ def __init__(self, exc_type, exc_value, exc_traceback, **kwargs):
self.exc_value = exc_value


@dataclass
class Extra:
def __init__(self, task_id=None, publish_time=None, failure_count=0):
self.task_id = task_id or str(uuid.uuid4())
self.publish_time = publish_time or round(time.time(), 3)
self.failure_count = failure_count
task_id: str = None
publish_time: float = None
failure_count: int = 0

def __post_init__(self):
self.task_id = self.task_id or str(uuid.uuid4())
self.publish_time = self.publish_time or round(time.time(), 3)

def to_dict(self):
return {
Expand All @@ -30,9 +35,6 @@ def to_dict(self):
def __str__(self):
return str(self.to_dict())

def __repr__(self):
return f"{self.__class__.__name__}({self.task_id}, {self.publish_time}, {self.failure_count})"


class Message:

Expand Down
44 changes: 44 additions & 0 deletions tests/test_message_extra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import pytest
from onestep.message import Extra


@pytest.fixture
def extra_instance():
# 创建一个 Extra 实例供测试使用
return Extra()


def test_to_dict(extra_instance):
# 测试 to_dict 方法是否返回正确的字典
expected_dict = {
'task_id': extra_instance.task_id,
'publish_time': extra_instance.publish_time,
'failure_count': extra_instance.failure_count,
}
assert extra_instance.to_dict() == expected_dict


def test_str(extra_instance):
# 测试 __str__ 方法是否返回正确的字符串表示
expected_str = str(extra_instance.to_dict())
assert str(extra_instance) == expected_str


def test_custom_values():
# 测试使用自定义值创建 Extra 实例是否正确
task_id = 'custom_task_id'
publish_time = 123456789.0
failure_count = 2

extra = Extra(task_id=task_id, publish_time=publish_time, failure_count=failure_count)
assert extra.task_id == task_id
assert extra.publish_time == publish_time
assert extra.failure_count == failure_count


def test_default_values():
# 测试使用默认值创建 Extra 实例是否正确
extra = Extra()
assert isinstance(extra.task_id, str)
assert isinstance(extra.publish_time, float)
assert extra.failure_count == 0

0 comments on commit 9d5a8be

Please sign in to comment.