diff --git a/audb/core/repository.py b/audb/core/repository.py index 8e1497f2..a312f53e 100644 --- a/audb/core/repository.py +++ b/audb/core/repository.py @@ -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(" diff --git a/tests/test_repository.py b/tests/test_repository.py index a78c0ad2..98e138ea 100644 --- a/tests/test_repository.py +++ b/tests/test_repository.py @@ -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", [