How to write pytest for an exception in string?

Question:

The code looks something like:

def check():
    if 'connector' in someMap:
        print("proceed")
    else:
        raise Exception('Positive vibes only')
    return 1

Pytest that I am trying looks like:

def test_check():
    e = 'negative test case for else block'
    with pytest.raises(e) as exc:  # pycharm shows e as Expected type 'Union[Tuple[Any, ...] Any]' (matched generic type 'Union[Type[E], Tuple[Type[E], ...]]') got 'str' instead
        res = check()
    assert res == e
Asked By: layman

||

Answers:

you would need to capture the exception, and the way is

 with pytest.raises(Exception) as exc_info:   # exc_info will strore the exception throw from check
        check()

once an exception is captured, you can get its string value by exc_info.value.args[0]}, for more detail, refer the pytest docs.

so the code would be(comments added for clarity)

import pytest
import os
def check():
    if 'connector' in os.environ:
        print("proceed")
    else:
        raise Exception('Positive vibes only')
    return 1

#check()

def test_check():
    e = 'negative test case for else block'
    with pytest.raises(Exception) as exc_info:   # exc_info will strore the exception throw from check
        check()
    print(f"type is:{exc_info.type} and value is {exc_info.value.args[0]}") # exc_info.type contain Exception and exc_info.value contains the value throw by exception, in this case 'Positive vibes only'
    assert e == exc_info.value.args[0] # this will fail as 'negative test case for else block' is compared with 'Positive vibes only'

def test_check_pass():
    e = 'negative test case for else block'
    with pytest.raises(Exception) as exc_info:   # exc_info will strore the exception throw from check
        check()
    assert 'Positive vibes only' == exc_info.value.args[0] # this will be a pass
Answered By: simpleApp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.