Skip to content

Commit

Permalink
AmpelAlert: restore id-based hash
Browse files Browse the repository at this point in the history
  • Loading branch information
jvansanten committed Jan 8, 2025
1 parent c157980 commit ad7e43c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
3 changes: 3 additions & 0 deletions ampel/alert/AmpelAlert.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class AmpelAlert:
tag: None | Tag | list[Tag] = None #: Optional tag associated with this alert
extra: None | JDict = None #: Optional information associated with this alert

def __hash__(self) -> int:
return id(self)

def get_values(self,
key: str,
filters: None | Sequence[JDict] = None
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "ampel-interface"
version = "0.10.4.post0"
version = "0.10.4.post1"
description = "Base classes for the Ampel analysis platform"
authors = ["Valery Brinnel"]
maintainers = ["Jakob van Santen <[email protected]>"]
Expand Down
30 changes: 29 additions & 1 deletion tests/test_AmpelAlert.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,37 @@
from copy import deepcopy

import pytest
from pydantic import ValidationError

from ampel.alert.AmpelAlert import AmpelAlert
from ampel.base.AmpelBaseModel import AmpelBaseModel
from ampel.protocol.AmpelAlertProtocol import AmpelAlertProtocol


def test_protocol():
alert = AmpelAlert(0, 0, [])
assert isinstance(alert, AmpelAlertProtocol), "dataclass fields recognized as protocol"
assert isinstance(
alert, AmpelAlertProtocol
), "dataclass fields recognized as protocol"

assert alert.tag is None, "defaults are populated"

class Model(AmpelBaseModel):
alerts: list[AmpelAlertProtocol]

# this works: AmpelAlert is a structural sub-type of AmpelAlertProtocol
m = Model(
alerts=[AmpelAlert(id=0, stock="stockystock", datapoints=[{"id": 0}])]
)
assert isinstance(
m.model_dump(mode="json")["alerts"][0], dict
), "dataclass serialized as dict"
# this does not: pydantic does not know how to deserialize a dict to AmpelAlertProtocol
with pytest.raises(ValidationError):
Model(**m.model_dump(mode="json"))


def test_hash():
"""AmpelAlert should be hashable"""
alert = AmpelAlert(id=0, stock="stockystock", datapoints=[{"id": 0}])
assert hash(alert) != hash(deepcopy(alert)), "hash is not the same after deepcopy"

0 comments on commit ad7e43c

Please sign in to comment.