How to check custom exception raised in pytest specific to my case?

Viewed 897

I am trying out a simple function and the test case is, to check the raise condtion is working or not. In raise custom exception message is given. The file name is converter.py.

I am using Pytest framework and testing it. I want to check if the error is raised and pass the test.

def convert_file(list_files):

    if type(list_files) is list:
        do some operations
    else:
        raise Exception("The file type is not a list")
    return True`

The test function wrote for this:

def test_convert_file_difference():
    result = converter.convert_file('1.xlxs')
 
    assert pytest.raises("The file type is not a list") == result

But i am getting the following error

=========================== short test summary info ============================
ERROR test_converter.py - Exception: The file type is not a list
=============================== 1 error in 0.07s ===============================

Assertion failed

I have tried the following approach but still the test case is failing.

def test_convert_file_difference():
    with pytest.raises(Exception) as exc:
        converter.convert_file('1.xlxs')
    assert "The file type is not a list" in str(exc.value)

I am new to Pytest. Could someone give the right specific code.I want to check in the test condition whether custom error has been occured and I want to pass the test. how to do that ?

1 Answers

Use the following code snippet for passing this scenario in such a way that we can check for the exception getting caught

class TestFunction(unittest.TestCase):
    def test_convert_file(self):
        with pytest.raises(Exception) as e:
            result = convert_file({})
        self.assertEqual(str(e.value), "The file type is not a list")

Here I have just passed a dictionary into the function to make sure that it goes into exception. Hope this helps for you.

Related