Skip to content

How can I mock an import failure? #11247

Discussion options

You must be logged in to vote

Hi,

Mocking things that happen at import time is tricky due to how Python import works.

If you can change the original code, one solution would be to split that code into functions:

def _import_version() -> str
    from module._version import version 
    return version


def _handle_version() -> str:  
    """Return the module._version string, which is generated by setuptools_scm."""  
    # Note: we use this indirection to be able to test the fallback code.
    try:
        return _import_version()
    except ModuleNotFoundError:
        raise FileNotFoundError(
            'Install setuptools_scm and run `python setup.py --version` '
            'to create version.py'
        )

__vers…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@aSeriesofNumbers
Comment options

Answer selected by aSeriesofNumbers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants