Relative imports with unittest in Python

自作多情 提交于 2019-12-03 04:20:26

In my experience it is easiest if your project root is not a package, like so:

project/
  test.py
  run.py
  package/
    __init__.py
    main_program.py
    lib/
      __init__.py
      lib_a
      lib_b
    tests/
      __init__.py
      test_a
      test_b

However, as of python 3.2 , the unittest module provides the -t option, which lets you set the top level directory, so you could do (from package/):

python -m unittest discover -t ..

More details at the unittest docs.

I run with the same problem and kai's answer solved it. I just want to complement his answer with the content of test.py (as @gsanta asked). I've only tested it on Python 2.7:

from packages.tests import test_a, test_b
import unittest

# for test_a
unittest.main(test_a)

# for test_b
unittest.main(test_a)

then you can just

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