Mock exception raised in function using Pytest

You can mock error raising via side_effect parameter:

Alternatively side_effect can be an exception class or instance. In this case the exception will be raised when the mock is called.

In your case, this can be used like this (assuming call_api is defined in module foo):

import pytest
from unittest.mock import patch

def test_api():
    with patch('foo.call_api', side_effect=Exception('mocked error')):
        with pytest.raises(Exception) as excinfo:
            create_key('localhost:8080', 'spam', 'eggs')
        assert excinfo.value.message == 'mocked error' 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)