The code looks something like:
def check():
if 'connector' in os.environ:
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
CodePudding user response:
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