Using pytest with a src layer

前端 未结 2 817
灰色年华
灰色年华 2020-11-27 19:16

pytest recommends including an additional directory to separate the source code within a project:

my_package
├── src  # <-- no __init__.py on this layer
│          


        
相关标签:
2条回答
  • 2020-11-27 19:27

    Adjusting the PYTHONPATH (as suggested in the comments) is one possibility to solve the import issue. Another is adding an empty conftest.py file in the src directory:

    $ touch src/conftest.py
    

    and pytest will add src to sys.path. This is a simple way to trick pytest into adding codebase to sys.path.

    However, the src layout is usually selected when you intend to build a distribution, e.g. providing a setup.py with (in this case) explicitly specifying the root package dir:

    from setuptools import find_packages, setup
    
    
    setup(
        ...
        package_dir={'': 'src'},
        packages=find_packages(where='src'),
        ...
    )
    

    and installing the package in the development mode (via python setup.py develop or pip install --editable .) while you're still developing it. This way, your package my_package is correctly integrated in the Python's site packages structure and there's no need to fiddle with PYTHONPATH.

    0 讨论(0)
  • 2020-11-27 19:37

    PYTHONPATH updates weren't working for me when using github actions (known prob). Using this pytest-pythonpath install with pytest.ini file worked for me instead:

    pip install pytest-pythonpath # accompany with python_path in pytest.ini, so PYTHONPATH is updated with location for modules under test
    

    With this, basic 'pytest' command happily found all tests in subdirs, and found modules under test based on my pytest.ini (set to match source folders in pycharm)

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