mirror of
https://github.com/logos-storage/bittorrent-benchmarks.git
synced 2026-02-20 04:33:27 +00:00
fix: simplify and fix adaptation of models to log entries
This commit is contained in:
parent
1ab2112542
commit
63501c3b79
@ -47,19 +47,19 @@ class LogEntry(SnakeCaseModel):
|
||||
"""Adapts an existing Pydantic model to a LogEntry. This is useful for when you have a model
|
||||
that you want to log and later recover from logs using :class:`LogParser` or :class:`LogSplitter`."""
|
||||
|
||||
def adapt_instance(cls, data: BaseModel):
|
||||
return cls.model_validate(data.model_dump())
|
||||
def adapt_instance(klass, data: BaseModel):
|
||||
return klass.model_validate(data.model_dump())
|
||||
|
||||
def recover_instance(self):
|
||||
return model.model_validate(self.model_dump())
|
||||
|
||||
parents = [base for base in model.__bases__ if issubclass(base, BaseModel)]
|
||||
|
||||
adapted = type(
|
||||
f"{model.__name__}LogEntry",
|
||||
tuple([LogEntry] + parents),
|
||||
(
|
||||
LogEntry,
|
||||
model,
|
||||
),
|
||||
{
|
||||
"__annotations__": model.__annotations__,
|
||||
"adapt_instance": classmethod(adapt_instance),
|
||||
"recover_instance": recover_instance,
|
||||
},
|
||||
|
||||
@ -247,6 +247,9 @@ class AModel(BaseModel):
|
||||
class BModel(AModel):
|
||||
b: int
|
||||
|
||||
def hello(self):
|
||||
return f"world {self.a} {self.b}"
|
||||
|
||||
|
||||
def test_should_log_attributes_for_superclasses_in_adapted_entries():
|
||||
BModelLogEntry = LogEntry.adapt(BModel)
|
||||
@ -256,3 +259,10 @@ def test_should_log_attributes_for_superclasses_in_adapted_entries():
|
||||
str(BModelLogEntry.adapt_instance(instance))
|
||||
== '>>{"a":1,"b":2,"entry_type":"b_model_log_entry"}'
|
||||
)
|
||||
|
||||
|
||||
def test_should_preserve_methods_in_adapted_entries():
|
||||
BModelLogEntry = LogEntry.adapt(BModel)
|
||||
instance = BModel(a=1, b=2)
|
||||
|
||||
assert BModelLogEntry.adapt_instance(instance).hello() == "world 1 2"
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user