Home > other >  How do I assert that sys.exit gets raised in pytest
How do I assert that sys.exit gets raised in pytest

Time:01-19

I want to assert in pytest that if my call fails that sys.exit is called.

import requests
import sys

def httpRequest(uri):
    try:
        response = requests.get(uri,verify=False)
    except requests.ConnectionError:
        sys.exit(1)
    return response
    

uri = 'http://reallybaduri.com/test'
response = httpRequest(uri)
print(response.text)

Testing Code:

import api_call
import requests
import pytest

def test_httpRequest():
    uri = 'http://reallybaduri.com/test'
    with pytest.raises(SystemExit) as pytest_wrapped_e:
        api_call.httpRequest(uri)
    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == 42 

This gives me a "did not raise" error. How Do I assert that an error is raised?

CodePudding user response:

You should change your code assert pytest_wrapped_e.value.code == 1 . You are expecting 1 not 42

CodePudding user response:

The test will automatically fail if no exception / exception other than SystemExit is raised.

The code only needs to be

import api_call
import requests
import pytest

def test_httpRequest():
    uri = 'http://reallybaduri.com/test'
    with pytest.raises(SystemExit):
        api_call.httpRequest(uri)
  •  Tags:  
  • Related