Skip to content

Commit

Permalink
Ensure audb.Repository is hashable (#491)
Browse files Browse the repository at this point in the history
* Ensure audb.Repository is hashable

* Update tests/test_repository.py

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>

* Add missing return type

* Extend test docstring

---------

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
  • Loading branch information
hagenw and sourcery-ai[bot] authored Dec 16, 2024
1 parent a3e9832 commit 90c6b5f
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
9 changes: 9 additions & 0 deletions audb/core/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ def __eq__(self, other) -> bool:
"""
return str(self) == str(other)

def __hash__(self) -> int:
"""Hash of repository.
Returns:
hash of repository
"""
return hash(str(self))

def __repr__(self): # noqa: D105
return (
f"Repository("
Expand Down
61 changes: 61 additions & 0 deletions tests/test_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,67 @@ def test_repository_eq(repository1, repository2, expected):
assert (repository1 == repository2) == expected


@pytest.mark.parametrize(
"repo1, repo2, should_have_same_hash",
[
# Same repositories should have same hash
(
audb.Repository("repo", "host", "file-system"),
audb.Repository("repo", "host", "file-system"),
True,
),
# Different attributes should have different hashes
(
audb.Repository("repo1", "host", "file-system"),
audb.Repository("repo2", "host", "file-system"),
False,
),
(
audb.Repository("repo", "host1", "file-system"),
audb.Repository("repo", "host2", "file-system"),
False,
),
(
audb.Repository("repo", "host", "file-system"),
audb.Repository("repo", "host", "s3"),
False,
),
],
)
def test_repository_hash(repo1, repo2, should_have_same_hash):
"""Test Repository object hash behavior.
Tests that:
- Repository objects are hashable
- Equal repositories have same hash
- Different repositories have different hashes
Args:
repo1: repository object
repo2: repository object
should_have_same_hash: if ``True``,
expects ``repo1`` and ``repo2``
to be the same object
"""
# Verify objects are hashable
assert isinstance(hash(repo1), int)
assert isinstance(hash(repo2), int)

# Test hash equality matches object equality
if should_have_same_hash:
assert hash(repo1) == hash(repo2)
assert repo1 == repo2
else:
assert hash(repo1) != hash(repo2)
assert repo1 != repo2

# Verify can be used in sets
test_set = {repo1, repo2}
expected_len = 1 if should_have_same_hash else 2
assert len(test_set) == expected_len


@pytest.mark.parametrize(
"backend, host, repo, expected",
[
Expand Down

0 comments on commit 90c6b5f

Please sign in to comment.