Raising errors

Raising errors#

If you have cases with handling errors in your program, to test such cases you may need a tool to raise these errors.

One particular case is testing logging for `try/except’ blocks.

You can use mocking mechanisms in such cases - you can pass the error to unittest.mock.MagicMock.side_effect and it’ll be raised when the mock is called.

Here is example of the function that uses request.get. But, suppose, it can raise some errors and we need to handle them. The handling assumes that we will write the error information to the log. The log, for simplicity, is just a toy - just a list to which we can write something.

import requests
def request_user(user_id, toy_log):
    try:
        response = requests.get(f"https://im_not_exist/{user_id}")
        if response.ok:
            return response.text
    except ValueError:
        toy_log.append("ValueError")
    except ZeroDivisionError:
        toy_log.append("ZeroDivisionError")
    return "Fail!"

The function handles ValueError and ZeroDivisionError. To check that all is well, we need to raise one of these within the try block.

The following cell shows the test case that will do the planned thing. It uses mocked_get.side_effect = ValueError("") to raise ValueError so that the appropriate string should appear in toy_log.

import unittest
from unittest.mock import patch

class TestUnit(unittest.TestCase):
    def test_error_raised(self):
        toy_log = []
        with patch("__main__.requests.get") as mocked_get:
            mocked_get.side_effect = ValueError("")
            output = request_user(10, toy_log)
            # check if answer was "Fail"
            self.assertEqual(output, "Fail!")
            # check if "ValueError" was 
            # appened to the toy log
            self.assertEqual(toy_log, ["ValueError"])

ans = unittest.main(argv=[''], verbosity=2, exit=False)
del TestUnit
test_error_raised (__main__.TestUnit) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.002s

OK