mike rodent
mike rodent

Reputation: 15652

Use pytest to check that an application file imports a module?

This fails:

def test_main_imports_pathlib():
    print(f'"pathlib" in sys.modules {"pathlib" in sys.modules}') # prints "True"
    if 'pathlib' in sys.modules:
        del sys.modules['pathlib']
    import core.__main__ 
    assert 'pathlib' in sys.modules

but __main__.py looks like this:

import pathlib

NB things are set up with conventional "src" and "tests" top directories and, yes, __main__.py definitely gets imported in the above test.

Is there a way to test whether an application file imports a module using pytest? I'm open to the idea that this might be dismissed an an "implementation detail" and that I should be testing for something bigger. But in fact I think that this is a trivial example of something you might well be justified in checking: what imports what...

In fact I'd like to understand why the above fails.

Upvotes: 1

Views: 353

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

Your problem is most probably that core.__main__ is already loaded, and importing it won't load it again. You have to also remove that module from the module cache, e.g. something like:

def test_main_imports_pathlib():
    if 'pathlib' in sys.modules:
        del sys.modules['pathlib']
    if '__main__' in sys.modules:
        del sys.modules['__main__']
    import core.__main__ 
    assert 'pathlib' in sys.modules

Another possibility would be to force a reload of the imported module instead:

from importlib import reload

def test_main_imports_pathlib():
    if 'pathlib' in sys.modules:
        del sys.modules['pathlib']
    main_loaded = 'core.__main__' in sys.modules
    import core.__main__ 
    if main_loaded:
        reload(core.__main__)
    assert 'pathlib' in sys.modules

As mentioned in the comment, this second version does not rely on the correct name of your module in the module cache, and is therefore more reliable.

Update: Prevent double loading as proposed by mike rodent.

Upvotes: 2

Related Questions