From b21f207b4f2bdf170d08c5d5fda6c77fa9b20abc Mon Sep 17 00:00:00 2001 From: Finn-Thorben Sell Date: Thu, 24 Mar 2022 17:07:16 +0100 Subject: [PATCH] add tests for error handling --- configurations/errors.py | 2 +- tests/test_error_handling.py | 43 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 tests/test_error_handling.py diff --git a/configurations/errors.py b/configurations/errors.py index 1f4a984..b339801 100644 --- a/configurations/errors.py +++ b/configurations/errors.py @@ -4,7 +4,7 @@ import sys import os if TYPE_CHECKING: - from .values import Value + from .values import Value # pragma: no cover class TermStyles: diff --git a/tests/test_error_handling.py b/tests/test_error_handling.py new file mode 100644 index 0000000..7f5d0ff --- /dev/null +++ b/tests/test_error_handling.py @@ -0,0 +1,43 @@ +import io +from unittest.mock import patch + +from django.test import TestCase + +from configurations.errors import ValueRetrievalError, SetupError, with_error_handler +from configurations.values import Value + + +class ErrorHandlingTestCase(TestCase): + def test_help_text_in_explanation_lines(self): + value_instance = Value(help_text="THIS IS A TEST") + exception = ValueRetrievalError(value_instance) + self.assertIn("Help: THIS IS A TEST", exception.explanation_lines) + + def test_help_reference_in_explanation_lines(self): + value_instance = Value(help_reference="https://example.com") + exception = ValueRetrievalError(value_instance) + self.assertIn("Reference: https://example.com", exception.explanation_lines) + + def test_example_in_explanation_lines(self): + value_instance = Value(example_generator=lambda: "test") + exception = ValueRetrievalError(value_instance) + self.assertIn("Example value: 'test'", exception.explanation_lines) + + def test_error_handler_rendering(self): + # setup + with patch("configurations.errors.sys.stderr", new=io.StringIO()) as mock: + def inner(): + try: + value_instance = Value(environ_required=True) + value_instance.setup("TEST") + except ValueRetrievalError as err: + raise SetupError("This is a test exception", [err]) + + # execution + with_error_handler(inner)() + + # verification + self.assertEqual(mock.getvalue().strip(), + "This is a test exception\n" + " * Value of TEST could not be retrieved from environment\n" + " - TEST is taken from the environment variable DJANGO_TEST as a Value")