| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from _pytest.stash import Stash |
| 4 |
from _pytest.stash import StashKey |
| 5 |
import pytest |
| 6 |
|
| 7 |
|
| 8 |
def test_stash() -> None: |
| 9 |
stash = Stash() |
| 10 |
|
| 11 |
assert len(stash) == 0 |
| 12 |
assert not stash |
| 13 |
|
| 14 |
key1 = StashKey[str]() |
| 15 |
key2 = StashKey[int]() |
| 16 |
|
| 17 |
# Basic functionality - single key. |
| 18 |
assert key1 not in stash |
| 19 |
stash[key1] = "hello" |
| 20 |
assert key1 in stash |
| 21 |
assert stash[key1] == "hello" |
| 22 |
assert stash.get(key1, None) == "hello" |
| 23 |
stash[key1] = "world" |
| 24 |
assert stash[key1] == "world" |
| 25 |
# Has correct type (no mypy error). |
| 26 |
stash[key1] + "string" |
| 27 |
assert len(stash) == 1 |
| 28 |
assert stash |
| 29 |
|
| 30 |
# No interaction with another key. |
| 31 |
assert key2 not in stash |
| 32 |
assert stash.get(key2, None) is None |
| 33 |
with pytest.raises(KeyError): |
| 34 |
stash[key2] |
| 35 |
with pytest.raises(KeyError): |
| 36 |
del stash[key2] |
| 37 |
stash[key2] = 1 |
| 38 |
assert stash[key2] == 1 |
| 39 |
# Has correct type (no mypy error). |
| 40 |
stash[key2] + 20 |
| 41 |
del stash[key1] |
| 42 |
with pytest.raises(KeyError): |
| 43 |
del stash[key1] |
| 44 |
with pytest.raises(KeyError): |
| 45 |
stash[key1] |
| 46 |
|
| 47 |
# setdefault |
| 48 |
stash[key1] = "existing" |
| 49 |
assert stash.setdefault(key1, "default") == "existing" |
| 50 |
assert stash[key1] == "existing" |
| 51 |
key_setdefault = StashKey[bytes]() |
| 52 |
assert stash.setdefault(key_setdefault, b"default") == b"default" |
| 53 |
assert stash[key_setdefault] == b"default" |
| 54 |
assert len(stash) == 3 |
| 55 |
assert stash |
| 56 |
|
| 57 |
# Can't accidentally add attributes to stash object itself. |
| 58 |
with pytest.raises(AttributeError): |
| 59 |
stash.foo = "nope" # type: ignore[attr-defined] |
| 60 |
|
| 61 |
# No interaction with another stash. |
| 62 |
stash2 = Stash() |
| 63 |
key3 = StashKey[int]() |
| 64 |
assert key2 not in stash2 |
| 65 |
stash2[key2] = 100 |
| 66 |
stash2[key3] = 200 |
| 67 |
assert stash2[key2] + stash2[key3] == 300 |
| 68 |
assert stash[key2] == 1 |
| 69 |
assert key3 not in stash |