Python relative paths for unit tests

让人想犯罪 __ 提交于 2021-02-10 14:35:23

问题


Given the directory structure:

/home/user/python/mypacakge/src/foo.py
/home/user/python/mypacakge/tests
/home/user/python/mypacakge/tests/fixtures
/home/user/python/mypacakge/tests/fixtures/config.json.sample
/home/user/python/mypacakge/tests/foo_tests.py
/home/user/python/mypacakge/README.md

Where src contains the source code, and test contains the unit tests, how do I setup a "package" so that my relative imports that are used in the unit tests located in test/ can load classes in src/?

Similar questions: Python Relative Imports and Packages and Python: relative imports without packages or modules, but the first doesn't really answer my question (or I don't understand it) and the second relies on symlinks to hack it together (respectively).


回答1:


I figured it out.

You have to have __init__.py in each of the folders like so:

/home/user/python/mypackage/src/__init__.py
/home/user/python/mypackage/src/Foo.py
/home/user/python/mypackage/tests
/home/user/python/mypackage/tests/fixtures
/home/user/python/mypackage/tests/fixtures/config.json.sample
/home/user/python/mypackage/tests/foo_test.py
/home/user/python/mypackage/tests/__init__.py
/home/user/python/mypackage/README.md
/home/user/python/mypackage/__init__.py

This tells python that we have "a package" in each of the directories including the top level directory. So, at this point, I have the following packages:

mypackage
mypackage.test
mypackage.src

So, because python will only go "down into" directories, we have to execute the unit tests from the root of the top-most package, which in this case is:

/home/user/python/mypackage/

So, from here, I can execute python and tell it to execute the unittest module and then specify which tests I want it to perform by specifying the module using the command line options

python -m unittest tests.foo_test.TestFoo

This tells python:

  1. Execute python and load the module unittest
  2. Tell unit test to run the tests contained in the class TestFoo, which is in the file foo_test.py, which is in the test directory.

Python is able to find it because __init__.py in each of these directories promotes them to a package that python and unittest can work with.

Lastly, foo_test.py must contain an import statement like:

from src import Foo

Because we are executing from the top level directory, AND we have packages setup for each of the subdirectories, the src package is available in the namespace, and can be loaded by a test.



来源:https://stackoverflow.com/questions/42678513/python-relative-paths-for-unit-tests

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