-1

I have this method defined.

 def store_id(self, id):
        try:
            if id is None:
                raise ValueError('Empty id')
            self.id = id
            return self.invoke()
        except ValueError as e:
            print(e)

I want to test the if condition here using the pytest. I want to test if the Value Error was generated.

This test gives "AssertionError: ValueError not raised"

def teststore_id(self):
    with self.assertRaises(ValueError):
        User().store_id(None)
user8082934
  • 391
  • 1
  • 5
  • 12
  • 2
    Side note: you may want to read ['id' is a bad variable name in Python](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) – Brian61354270 Feb 20 '21 at 18:13
  • 1
    `store_od` doesn't raise anything, since the error is caught in the function. You can test whether the text is printed when `None` is passed as input, though. – hoefling Feb 20 '21 at 18:36
  • Can you please tell me how should I check whether the text is printed or not? – user8082934 Feb 20 '21 at 19:13

1 Answers1

0

As @hoefling pointed out, your function doesn't raise anything, so your test result is correct. Probably you don't need to check if the exception is raised, but how your method is behaving in this case.

To check for the print call, you can just mock it and check the calls:

from unittest import mock

def raise_and_catch_exception(do_raise):
    # example function that raises and catches an exception
    try:
        if do_raise:
            raise ValueError()
    except ValueError:
        print('Raised exception')

@mock.patch('my_tested_module.print')
def test_print(mocked_print):
    raise_and_catch_exception(False)
    mocked_print.assert_not_called()
    raise_and_catch_exception(True)
    mocked_print.assert_called_once_with('Raised exception')

In case you want to check if the exception is raised anyway, you can mock the exception itself. Note that cannot just replace the exception by a mock, because Python would complain that your exception is not raised from BaseException while trying to execute the exception handler. Here is some crude example how you could do this:

...
class MyException(ValueError):
    call_nr = 0  # note that this counts the instancion of the exception, not raising it

    def __init__(self, *args):
        self.__class__.call_nr += 1
        super().__init__(*args)


def test_raise():
    with mock.patch('builtins.ValueError', MyException):
        raise_and_catch_exception(False)
        assert MyException.call_nr == 0
        raise_and_catch_exception(True)
        assert MyException.call_nr == 1
MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46