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

前端 未结 20 2387
孤独总比滥情好
孤独总比滥情好 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:40

    My solution:

    create the conftest.py file in the test directory containing:

    import os
    import sys
    sys.path.insert(0,os.path.dirname(os.path.realpath(__file__)) + "/relative/path/to/code/")
    

    This will add the folder of interest to the python path without modifying every test file, setting env variable or messing with absolute/relative paths.

    0 讨论(0)
  • 2020-11-22 07:44

    I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.

    https://github.com/jeffmacdonald/pytest_test

    Specifically: You have to tell py.test and tox where to find the modules you are including.

    With py.test you can do this:

    PYTHONPATH=. py.test
    

    And with tox, add this to your tox.ini:

    [testenv]
    deps= -r{toxinidir}/requirements.txt
    commands=py.test
    setenv =
        PYTHONPATH = {toxinidir}
    
    0 讨论(0)
  • 2020-11-22 07:44

    I had the same problem in Flask.

    When I added:

    __init__.py
    

    to tests folder, problem disappeared :)

    Probably application couldn't recognize folder tests as module

    0 讨论(0)
  • 2020-11-22 07:45

    You can run with PYTHONPATH in project root

    PYTHONPATH=. py.test
    

    Or use pip install as editable import

    pip install -e .   # install package using setup.py in editable mode
    
    0 讨论(0)
  • 2020-11-22 07:48

    Very often the tests were interrupted due to module being unable to be imported,After research, I found out that the system is looking at the file in the wrong place and we can easily overcome the problem by copying the file, containing the module, in the same folder as stated, in order to be properly imported. Another solution proposal would be to change the declaration for the import and show MutPy the correct path of the unit. However, due to the fact that multiple units can have this dependency, meaning we need to commit changes also in their declarations, we prefer to simply move the unit to the folder.

    0 讨论(0)
  • 2020-11-22 07:49

    I fixed it by removing the top-level __init__.py in the parent folder of my sources.

    0 讨论(0)
提交回复
热议问题