构造适合测试和运行代码的python3代码和导入的正确方法是什么?

时间:2019-04-10 18:06:08

标签: python python-3.x python-import

我对python来说还比较陌生,我正在努力找到将适用于pycharm,在命令行上pytest,在命令行上运行实际程序以及在Bamboo中构建的文件层次结构和import语句的组合。

这是我的等级:

foo
| goo
| __init__.py
| run.py
  | koo
    | __init__.py
    | bar.py
  | loo
    | __init__.py
    | baz.py
| tests
| __init__.py
| test_bar.py
| test_baz.py
| test_file.py
| data
  | text.txt

这是我的代码:

foo / goo / koo / bar.py:

greeting = "hello"


def hello():
    return greeting

foo / goo / loo / baz.py:

from koo import bar


def greet():
    return "the greeting is..." + bar.hello()

foo / goo / run.py:

import loo.baz as baz


print(baz.greet())

foo / tests / test_bar.py:

import goo.koo.bar as b


def test_hello():
    assert b.hello() == "hello"

foo / tests / test_baz.py:

import goo.loo.baz as b


def test_greet():
    assert b.greet() == "the greeting is...hello"

foo / tests / test_file.py:

import os.path
import sys


def test_file():
    f = open(os.path.join(sys.path[0], "tests", "data", "test.txt"), "rt")
    assert f.read() == "hello world"

当我进入foo目录并运行

python goo/run.py

这有效。但是当我跑步

python -m pytest tests

我得到了错误

Traceback:
tests/test_baz.py:1: in <module>
    import goo.loo.baz as b
goo/loo/baz.py:1: in <module>
    from koo import bar
E   ModuleNotFoundError: No module named 'koo'

如果我将baz.py更改为以下内容:

from goo.koo import bar


def greet():
    return "the greeting is..." + bar.hello()

然后所有测试通过,但是运行程序会出现此错误:

Traceback (most recent call last):
  File "goo/run.py", line 1, in <module>
    import loo.baz as baz
  File "/home/me/PycharmProjects/foo/goo/loo/baz.py", line 1, in <module>
    from goo.koo import bar
ModuleNotFoundError: No module named 'goo'

This question类似,但没有明显的答案。一个已发布的答案建议将测试文件夹下移,但这在我们的构建服务器上造成了问题,而且这里的常见做法似乎是将测试放在顶层。

假设我想将测试保持在最高水平,那么导入的组合是否可行?

1 个答案:

答案 0 :(得分:1)

我会结合使用绝对导入,例如from goo.koo import bar并将文件夹foo添加到您的PYTHONPATH中,

export PYTHONPATH=$PYTHONPATH:/path/to/foo

然后将所有导入结构化,就好像它们源自foo文件夹