ModuleNotFoundError with pytest

后端 未结 6 718
时光说笑
时光说笑 2021-02-12 11:05

I want my tests folder separate to my application code. My project structure is like so

myproject/
  myproject/
    myproject.py
    moduleone.py
  tests/
    my         


        
6条回答
  •  说谎
    说谎 (楼主)
    2021-02-12 11:33

    Solution: use the PYTHONPATH env. var

    PYTHONPATH=. pytest
    

    As mentioned by @J_H, you need to explicitly add the root directory of your project, since pytest only adds to sys.path directories where test files are (which is why @Mak2006's answer worked.)


    Good practice: use a Makefile or some other automation tool

    If you are lazy and do not want to type that long command all the time, one option is to create a Makefile in your project's root dir with, e.g., the following:

    .PHONY: install test
    
    default: test
    
    install:
        pip install --upgrade .
    
    test:
        PYTHONPATH=. pytest
    

    Which allows you to simply run:

    make test
    

    or (even shorter)

    make
    

    Another common alternative is to use some standard testing tool, such as tox.

提交回复
热议问题