无法从我的测试文件夹导入模块服务器

时间:2019-07-03 10:02:52

标签: python-3.x flask pytest

我正在编写一个遵循以下文件夹结构的flask应用。

backend
  server.py
  __init__.py
    test
      __init__.py
      servertest.py

"""Server ping test for flask"""

import flask
import pytest
from server import app

@pytest.fixture()
def client():
    yield testing.TestClient(app)


def test_ping_resource(client):
    doc = "Flask GET service is working"
    result = client.simulate_get("/api/ping")
    assert result.status_code == 200
    assert result.json == doc

这是我的测试文件。当我运行文件时。它给出了

   from server import app
E   ImportError: No module named 'server'

我在做什么错,这使得服务器模块对于测试模块不可见?

2 个答案:

答案 0 :(得分:0)

Python从路径列表中导入模块:

import sys
sys.path

您必须提供Python查找server.py的方法:

  • 您可以从backend目录运行代码,因为当前路径自动发生在sys.pathcd backend; pytest
  • 您可以将backend的完整路径添加到PYTHONPATH

有时,您需要阅读the doc about import

此外,要自然使用pytest,您的测试文件必须以test开头。

答案 1 :(得分:0)

运行python文件时,其父文件夹将添加到python path中,但其父文件夹(此处是您的根文件夹)却没有添加!

您可以做的是:

  • 从根文件夹运行测试(首选)
  • 使用relative imports,在这里:from ..server import app
  • 修改您的python路径(不建议
相关问题