From 6a014d06730ffe3dd36baaff27d67e69e994038f Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Fri, 22 Sep 2023 13:43:31 +0100 Subject: [PATCH] python: add note on excinfo in pytest --- .../Python/Concepts/Testing_Python_code.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Programming_Languages/Python/Concepts/Testing_Python_code.md b/Programming_Languages/Python/Concepts/Testing_Python_code.md index bbeb103..5a665f2 100644 --- a/Programming_Languages/Python/Concepts/Testing_Python_code.md +++ b/Programming_Languages/Python/Concepts/Testing_Python_code.md @@ -236,3 +236,27 @@ def test_http_error(capsys): captured = capsys.readouterr() assert "An error occurred" in captured.out ``` + +## `excinfo` + +We can use `excinfo` to test that an exception is raised: + +For example, instead of using `logging.error` to log an error message when the environment variable cannot be sourced. We could instead raise an exception with `ValueError`: + +```py +if POCKET_LAMBDA_ENDPOINT is None: + raise ValueError( + "Error: POCKET_LAMBDA_ENDPOINT environment variable is not set" + ) +``` + +Then to test this, we would use pytest's `excinfo` fixture along with `raises`: + +```py + with pytest.raises(ValueError) as excinfo: # Watch for the ValueError + get_articles("some_type") + + assert "Error: POCKET_LAMBDA_ENDPOINT environment variable is not set" in str( + excinfo.value + ) +```