{"id":940,"hash":"61c54c64d64dde1f9d1a9802b7d7a3e79173dd3480a74ac882e2c5f17e79e4ee","pattern":"How to use pytest to check that Error is NOT raised","full_message":"Let's assume we have smth like that :\n\nimport py, pytest\n\nERROR1 = ' --- Error : value < 5! ---'\nERROR2 = ' --- Error : value > 10! ---'\n\nclass MyError(Exception):\n    def __init__(self, m):\n        self.m = m\n\n    def __str__(self):\n        return self.m\n\ndef foo(i):\n    if i < 5:\n        raise MyError(ERROR1)\n    elif i > 10:\n        raise MyError(ERROR2)\n    return i\n\n# ---------------------- TESTS -------------------------\ndef test_foo1():\n    with pytest.raises(MyError) as e:\n        foo(3)\n    assert ERROR1 in str(e)\n\ndef test_foo2():\n    with pytest.raises(MyError) as e:\n        foo(11)\n    assert ERROR2 in str(e)\n\ndef test_foo3():\n        ....\n        foo(7)\n         ....\n\nQ: How can I make test_foo3() to test, that no MyError is raised?\nIt's obvious, that i could just test :\n\ndef test_foo3():\n    assert foo(7) == 7\n\nbut i want to test that via pytest.raises(). Is is possible someway?\nFor example: in a case, that function \"foo\" has no return-value at all,\n\ndef foo(i):\n    if i < 5:\n        raise MyError(ERROR1)\n    elif i > 10:\n        raise MyError(ERROR2)\n\nit could make sense to test this way, imho.","ecosystem":"pypi","package_name":"pytest","package_version":null,"solution":"A test will fail if it raises any kind of unexpected Exception. You can just invoke foo(7) and you will have tested that no MyError is raised. So, following will suffice:\n\ndef test_foo3():\n    foo(7)\n\nIf you want to be explicit and write an assert statement for this, you can do:\n\ndef test_foo3():\n    try:\n        foo(7)\n    except MyError:\n        pytest.fail(\"Unexpected MyError ..\")","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/20274987/how-to-use-pytest-to-check-that-error-is-not-raised","votes":215,"created_at":"2026-04-19T04:52:04.237405+00:00","updated_at":"2026-04-19T04:52:04.237405+00:00"}