PATH issue with pytest 'ImportError: No module named YadaYadaYada'

前端 未结 20 2662
孤独总比滥情好
孤独总比滥情好 2020-11-22 07:10

I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:

repo/
repo/app.py
repo/settings.py
rep         


        
20条回答
  •  醉梦人生
    2020-11-22 07:30

    I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.

    from repo.app import *
    

    However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.

    from app import *
    

    Here's an example of what I had to do with one of my projects:

    Here’s my project structure:

    microbit/
    microbit/activity_indicator/activity_indicator.py
    microbit/tests/test_activity_indicator.py
    

    To be able to access activity_indicator.py from test_activity_indicator.py I needed to:

    • start test_activity_indicatory.py with the correct relative import:
        from microbit.activity_indicator.activity_indicator import *
    
    • put __init__.py files throughout the project structure:
        microbit/
        microbit/__init__.py
        microbit/activity_indicator/__init__.py
        microbit/activity_indicator/activity_indicator.py
        microbit/tests/__init__.py
        microbit/tests/test_activity_indicator.py
    

提交回复
热议问题