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

问题描述 投票:2回答:1

我是python的新手,我正在努力找到文件层次结构和import语句的组合,这些组合将在pycharm,命令行上的pytest,在命令行上运行实际程序以及在bamboo中构建。

这是我的层次结构:

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

这是我的代码:

富/咕/古/ bar.py:

greeting = "hello"


def hello():
    return greeting

富/咕/卫生间/ baz.py:

from koo import bar


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

富/咕/ run.py:

import loo.baz as baz


print(baz.greet())

富/测试/ test_bar.py:

import goo.koo.bar as b


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

富/测试/ test_baz.py:

import goo.loo.baz as b


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

富/测试/ 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相似,但没有明显的答案。一个已发布的答案建议将测试文件夹向下移动,但这会在我们的构建服务器上引起问题,而且这里的常见做法似乎是将测试放在顶层。

假设我想将测试保持在最高级别,是否有任何组合的导入将起作用?

python python-3.x python-import
1个回答
1
投票

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

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

然后构造所有导入,就像它们来自foo文件夹一样

© www.soinside.com 2019 - 2024. All rights reserved.