How to I organize my pytest tests if I'm not distributing them with my package?

Deadly 提交于 2019-12-04 04:01:06

问题


As suggested in the pytest documentation, I have set up my package with the intent not not distributing my tests along with my package:

setup.py
mypkg/
    __init__.py
    mypkg/
      appmodule.py  
tests/
    test_app.py
    ...

but I am confused about how to ensure that these tests will run correctly when present (e.g. on Travis CI, or in clones of the project directory).

I want the imports in my test scripts to apply to the source in the adjacent mypkg/ directory (and not to any mypkg that might be installed in site-packages), but I'm getting errors that puzzle me.

If I follow the advice in the pytest documentation and don't put an __init__.py in tests/ then with

from __future__ import absolute_import
from mypkg.appmodule import * 

I get

ImportError: No module named mypkg.appmodule

while with

from __future__ import absolute_import
from ..mypkg.appmodule import * 

I get

ValueError: Attempted relative import in non-package

And if I ignore the documentation and include an __init__.py, then with the latter I get

ValueError: Attempted relative import beyond top-level package

Only by including an __init__.py and using

from __future__ import absolute_import
from mypkg.appmodule import * 

will my tests run. But it isn't clear to me that this will import the source from the adjacent mypkg/ directory if a mypkg is installed in site-packages.

What is the correct way to organize my pytest tests so that they are separate from — and not distributed with — my projects source, but always import the adjacent source, and not version of the package that is installed elswehere?


回答1:


The problem is just that python can't find your appmodule when you ask for it to look in the mypkg directory where it doesn't exist.

You've set the directories up correctly with:

setup.py
mypkg/
    __init__.py
    mypkg/
        appmodule.py  
tests/
    test_app.py
    ...

But since you've created another mypkg/ subdirectory to house your appmodule.py, you'll need to place __init__.py in that subdirectory for an import to work. The call would also be changed to:

from mypkg.mypkg.appmodule import *

Hope this helps.



来源:https://stackoverflow.com/questions/33964355/how-to-i-organize-my-pytest-tests-if-im-not-distributing-them-with-my-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!