Skip to content

Commit

Permalink
make entities comparable by ID
Browse files Browse the repository at this point in the history
  • Loading branch information
leoschwarz committed Sep 17, 2024
1 parent 3e8b913 commit a4c96be
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions bfabric/entities/core/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ def get(self, key: str, default: Any = None) -> Any:
"""Returns the value of a key in the data dictionary, or a default value if the key is not present."""
return self.__data_dict.get(key, default)

def __lt__(self, other: Entity) -> bool:
"""Compares the entity with another entity based on their IDs."""
if self.ENDPOINT != other.ENDPOINT:
return NotImplemented
return self.id < other.id

def __repr__(self) -> str:
"""Returns the string representation of the workunit."""
return f"{self.__class__.__name__}({repr(self.__data_dict)}, client={repr(self.__client)})"
Expand Down
22 changes: 22 additions & 0 deletions bfabric/tests/unit/entities/core/test_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,5 +112,27 @@ def test_str(mock_entity, mock_data_dict) -> None:
assert str(entity) == "Entity({'id': 1, 'name': 'Test Entity'}, client=None)"


def test_compare_when_possible():
entity_1 = Entity({"id": 1, "name": "Test Entity"}, None)
entity_1.ENDPOINT = "X"
entity_10 = Entity({"id": 10, "name": "Test Entity"}, None)
entity_10.ENDPOINT = "X"
assert entity_1 == entity_1
assert entity_1 < entity_10
assert entity_10 > entity_1


def test_compare_when_not_possible():
entity_1 = Entity({"id": 1, "name": "Test Entity"}, None)
entity_1.ENDPOINT = "X"
entity_2 = Entity({"id": 2, "name": "Test Entity"}, None)
entity_2.ENDPOINT = "Y"
assert entity_1 != entity_2
with pytest.raises(TypeError):
_ = entity_1 < entity_2
with pytest.raises(TypeError):
_ = entity_1 > entity_2


if __name__ == "__main__":
pytest.main()
4 changes: 4 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ Versioning currently follows `X.Y.Z` where

## \[Unreleased\]

### Added

- Entities can be compared and sorted by ID now.

## \[1.13.7\] - 2024-09-17

### Fixed
Expand Down

0 comments on commit a4c96be

Please sign in to comment.