Skip to content

Commit 5f39e31

Browse files
committed
stash: implement __len__
Part of the MutableMapping abc (though we can't actually implement that).
1 parent 5470d33 commit 5f39e31

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

src/_pytest/stash.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,7 @@ def __delitem__(self, key: StashKey[T]) -> None:
123123
def __contains__(self, key: StashKey[T]) -> bool:
124124
"""Return whether key was set."""
125125
return key in self._storage
126+
127+
def __len__(self) -> int:
128+
"""Return how many items exist in the stash."""
129+
return len(self._storage)

testing/test_stash.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
def test_stash() -> None:
77
stash = Stash()
88

9+
assert len(stash) == 0
10+
assert not stash
11+
912
key1 = StashKey[str]()
1013
key2 = StashKey[int]()
1114

@@ -19,6 +22,8 @@ def test_stash() -> None:
1922
assert stash[key1] == "world"
2023
# Has correct type (no mypy error).
2124
stash[key1] + "string"
25+
assert len(stash) == 1
26+
assert stash
2227

2328
# No interaction with another key.
2429
assert key2 not in stash
@@ -44,6 +49,8 @@ def test_stash() -> None:
4449
key_setdefault = StashKey[bytes]()
4550
assert stash.setdefault(key_setdefault, b"default") == b"default"
4651
assert stash[key_setdefault] == b"default"
52+
assert len(stash) == 3
53+
assert stash
4754

4855
# Can't accidentally add attributes to stash object itself.
4956
with pytest.raises(AttributeError):

0 commit comments

Comments
 (0)