Testing that code raises ValueError sounds strict, but a typo in your function can raise a ValueError too. I’d add match so the test checks the reason as well.
import pytest
def parse_port(s):
port = int(s)
if not 0 < port < 65536:
raise ValueError(f"port out of range: {port}")
return port
def test_port_too_high():
with pytest.raises(ValueError, match="out of range"):
parse_port("70000")
Without match, this test would also pass for parse_port("abc"), where int() raises its own ValueError with a completely different message. With it, pytest checks the message too and fails if the text doesn’t match.
match is a regular expression, searched anywhere in the message with re.search. A plain phrase like the one above works fine, but characters like (, . or [ have special meaning. Wrap the expected text in re.escape() when you want to match it literally.
If you need more than the message, write with pytest.raises(ValueError) as exc: and inspect exc.value after the block. Keep only the line that should fail inside the with: any statement after it never runs, and an earlier line that raises the same error makes the test pass for the wrong reason.
Further reading: pytest.raises, pytest: assertions about expected exceptions