Python project directory structure / pytest trouble

白昼怎懂夜的黑 提交于 2019-11-29 22:58:24
  1. What about the __init__.py in the apple directory... correct? Empty or what should be inside?

Yes, correct. Most frequently empty. If you put foo = 42 in it you can later do from apple import foo while you'll need to do from apple.apple import foo if you put it in apple.py. While it might seem convenient you should use it sparingly.

  1. Is it best practice to call py.test from the root directory? Or py.test tests?

py.test should be able to find your tests regardless, but see below..

  1. So many projects have a __init__.py in their test directory, but that's explicitly said to be wrong in the py.test documentation. So why god why

So you can import a file in tests that provide common test functionality. In py.test that might be better achieved by creating fixtures in a file called tests/conftest.py.

  1. What comes at the top of the test_everything.py file: an import apple or from apple import *? or something else entirely

from apple import apple

  1. Do you call the functions then by eat() or apple.eat()?

apple.eat()

  1. Some even recommend manipulating os.path.dirname in python

That seems very fragile. I would suggest either

(a) set the environment variable PYTHONPATH to point to the folder where README.md is, or better

(b) create a setup.py file (at the same level as your README.md file), here's a minimal one:

from setuptools import setup
setup(name='apple', packages=['apple'])

Run the file like so:

python setup.py develop

now apple is globally available and you should never see a no module named apple problem again, i.e. you can run py.test from the root folder or the tests folder.

You can read more about setup.py in the Python Packaging User Guide at https://python-packaging-user-guide.readthedocs.org/en/latest/index.html

I have arranged an example that works here.

I think naming both package and module apple confusing, perhaps that was one source of confusion. The only non-obvious part IMO is that you must set PYTHONPATH to the current directory if you're not using a proper setup.py distutils package to install your apple package.

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