python unit test is not covering code inside the except block

  pytest, python, unit-testing

Below is a code snippet for which I am trying to write unit tests. I have also copied the unit tests I have written. I am new to unit testing but from what I understand in test_main_version_exception unit test the compare_version.version_match() function would raise an exception and ideally this exception should get caught by the except block. But for some reason the flow is not going into except block.
(1st one seems to be working fine)

Could someone please help me with this? Any suggestions to improve theses tests are also welcome.

main.py file

try:
  is_version_same = compare_version.version_match()
  if is_version_same:
    LOGGER.info("Upgrade not required")
    sys.exit()
except compare_version.VersionError as error: #custom error
    #### these two statements  are not getting covered when I run test_main_version_exception(mocker):
    LOGGER.exception("Exception occurred in compare_version: %s", error) 
    sys.exit(f"Exception occurred in compare_version: {error}")

UNIT TESTS:

def test_main_same_version(mocker):
    mocker.patch(
        "compare_version.version_match",
        return_value=True,
    )
    with pytest.raises(SystemExit) as ex:
        main.main()
    assert ex.type == SystemExit

def test_main_version_exception(mocker):
    mocker.patch(
        "compare_version.version_match",
        side_effect=VersionError,
    )
    with pytest.raises(VersionError) as ex:
        main.main()
    assert ex.type == VersionError

Source: Python Questions

LEAVE A COMMENT