ModuleNotFoundError with pytest

后端 未结 6 723
时光说笑
时光说笑 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:21

    Kept everything same and just added a blank test file at the root folder .. Solved

    Here are the findings, this problem really bugged me for a while. My folder structure was

    mathapp/
        - server.py  
        - configuration.py 
        - __init__.py 
        - static/ 
           - home.html  
    tests/            
        - functional 
           - test_errors.py 
        - unit  
           - test_add.py
    

    and pytest would complain with the ModuleNotFoundError.

    I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.

    Result without the file

    $ pytest
    ============================= test session starts =============================
    platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
    rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
    collected 1 item / 1 error
    
    =================================== ERRORS ====================================
    _______________ ERROR collecting tests/functional/test_func.py ________________
    ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    tests\functional\test_func.py:4: in 
        from mathapp.service import sum
    E   ModuleNotFoundError: No module named 'mathapp'
    =========================== short test summary info ===========================
    ERROR tests/functional/test_func.py
    !!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
    ============================== 1 error in 0.24s ===============================
    

    Results with the file

    $ pytest
    ============================= test session starts =============================
    platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
    rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
    collected 2 items
    
    tests\functional\test_func.py .                                          [ 50%]
    tests\unit\test_unit.py .                                                [100%]
    
    ============================== 2 passed in 0.11s ==============================
    

提交回复
热议问题