Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pytest raises exception but assert doesn't catch it, although they are the same type and same value

I am writing test for this function:

def get_current_active_user(current_user: models.User = Depends(get_current_user)) -> models.User:
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user

I am trying to check if the arguments of HTTPException are right. That is my test:

def test_get_current_active_user_not_active():
    user: models.User = UserFactory()
    user.is_active = False

    with pytest.raises(HTTPException) as exc_info:
        get_current_active_user(current_user=user)
    
    assert exc_info.value == HTTPException(status_code=400, detail='Inactive user')

For some reason, this assert is never true, although the values are the same. Debugging session:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>exc_info.value
HTTPException(status_code=400, detail='Inactive user')

>type(exc_info.value)
<class 'fastapi.exceptions.HTTPException'>

>type(HTTPException(status_code=400, detail='Inactive user'))
<class 'fastapi.exceptions.HTTPException'>

>exc_info.value == HTTPException(status_code=400, detail='Inactive user')
False

>str(exc_info.value) == "HTTPException(status_code=400, detail='Inactive user')"
False

Any ideas why this is happening are greatly appreciated.

>Solution :

== in python might just compare the objects’s ids, which is why the equality fails here.

Maybe you should try something like:

assert exc_info.value.status_code == 400
assert exc_info.detail == 'Inactive user'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading