简体   繁体   中英

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

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM