簡體   English   中英

conftest.py ImportError:沒有名為Foo的模塊

[英]conftest.py ImportError: No module named Foo

我有以下目錄結構

/home/ubuntu/test/
 - Foo/
   - Foo.py
   - __init__.py
 - Test/
   - conftest.py
   - __init__.py
   - Foo/
     - test_Foo.py
     - __init__.py

Foo.py包含

class Foo(object):
  def __init__(self):
    pass

conftest.py包含:

import pytest

import sys
print sys.path

from Foo.Foo import Foo

@pytest.fixture(scope="session")
def foo():
  return Foo()

test_Foo.py包含:

class TestFoo():
  def test___init__(self,foo):
    assert True

如果我運行pytest。 在測試文件夾中,然后我得到一個錯誤,即找不到模塊Foo:

Traceback (most recent call last):
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/_pytest/config.py", line 379, in _importconftest
    mod = conftestpath.pyimport()
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/py/_path/local.py", line 662, in pyimport
    __import__(modname)
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/_pytest/assertion/rewrite.py", line 212, in load_module
    py.builtin.exec_(co, mod.__dict__)
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/py/_builtin.py", line 221, in exec_
    exec2(obj, globals, locals)
  File "<string>", line 7, in exec2
  File "/home/ubuntu/test/Test/conftest.py", line 6, in <module>
    from Foo.Foo import Foo
ImportError: No module named Foo
ERROR: could not load /home/ubuntu/test/Test/conftest.py

在conftest.py中打印出的sys.path似乎包含/ home / ubuntu / test路徑,因此它應該能夠找到Foo.py,對嗎?

問題是,僅當我將conftest.py移至下面的文件夾時,它才起作用。

我運行pytest 3.2.2

該錯誤表明conftest.py由於ImportError而無法加載。 嘗試像這樣在foo固定裝置中移動導入:

import pytest
import sys
print sys.path


@pytest.fixture(scope="session")
def foo():
    from Foo.Foo import Foo
    return Foo()

我建議您做的是設置虛擬環境,然后在虛擬環境中安裝Foo模塊。

pip install virtualenv
virtualenv venv
. ./venv/bin/activate

為了安裝本地模塊,您需要一個setup.py文件:

from setuptools import setup

setup(
    name='foo',
    version='0.0.1',
    author='My Name',
    author_email='my.name@email.com',
    packages=['Foo'],
)

然后,您可以在虛擬環境中安裝Foo模塊: pip install -e . 然后,當您運行測試時,他們將接您的模塊。

有關更完整,更長期的方法,請考慮使用需求文件。 我通常將我需要的模塊放在兩個文件中,分別名為requirements.txt (用於生產)和requirements-test.txt (用於運行測試)。 因此,在requirements.txt放入Foo類所需的內容,例如

json
flask==1.0.2

在哪里指定了flask的版本,但沒有指定json 然后在requirements-test.txt文件中輸入以下內容:

-r requirements.txt
pytest
-e .

第一行意味着,當您安裝requirements-test.txt時,您也將獲得所有requirements.txt -e . 是解決您在此處遇到的問題的靈丹妙葯,即它安裝了Foo模塊(以及此存儲庫中可能包含的任何其他模塊)。

要安裝requirements-test.txt文件,然后運行:

pip install -r requirements-test.txt

現在您可以運行測試,它將找到您的Foo模塊。 這也是解決CI問題的好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM