pytest 不能导入模块,而 python 可以
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41748464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pytest cannot import module while python can
提问by Zorglub29
I am working on a package in Python. I use virtualenv. I set the path to the root of the module in a .pth path in my virtualenv, so that I can import modules of the package while developing the code and do testing (Question 1: is it a good way to do?). This works fine (here is an example, this is the behavior I want):
我正在使用 Python 开发一个包。我使用虚拟环境。我在我的 virtualenv 的 .pth 路径中设置了模块根的路径,这样我就可以在开发代码和进行测试时导入包的模块(问题 1:这是一个好方法吗?)。这很好用(这是一个例子,这是我想要的行为):
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python
Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rc import ns
>>> exit()
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python tests/test_ns.py
issued command: echo hello
command output: hello
However, if I try to use PyTest, I get some import error messages:
但是,如果我尝试使用 PyTest,则会收到一些导入错误消息:
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ pytest
=========================================== test session starts ============================================
platform linux2 -- Python 2.7.12, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /home/zz/Desktop/GitFolders/rc, inifile:
collected 0 items / 1 errors
================================================== ERRORS ==================================================
________________________________ ERROR collecting tests/test_ns.py ________________________________
ImportError while importing test module '/home/zz/Desktop/GitFolders/rc/tests/test_ns.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_ns.py:2: in <module>
from rc import ns
E ImportError: cannot import name ns
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
========================================= 1 error in 0.09 seconds ==========================================
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ which pytest
/home/zz/Desktop/VirtualEnvs/VEnvTestRc/bin/pytest
I am a bit puzzled, it looks like this indicates an import error, but Python does it fine so why is there a problem specifically with PyTest? Any suggestion to the reason / remedy (Question 2)? I googled and stack-overflowed the 'ImportError: cannot import' error for PyTest, but the hits I got were related to missing python path and remedy to this, which does not seem to be the problem here. Any suggestions?
我有点困惑,看起来这表示导入错误,但是 Python 做得很好,那么为什么 PyTest 会出现问题?对原因/补救措施有什么建议(问题2)?我用谷歌搜索并堆栈溢出了 PyTest 的“ImportError:无法导入”错误,但我得到的命中与缺少 python 路径和对此进行补救有关,这似乎不是这里的问题。有什么建议?
采纳答案by Zorglub29
Found the answer:
找到答案:
DO NOT put a __init__.py
file in a folder containing TESTS if you plan on using pytest. I had one such file, deleting it solved the problem.
__init__.py
如果您打算使用 pytest,请勿将文件放在包含 TESTS 的文件夹中。我有一个这样的文件,删除它解决了问题。
This was actually buried in the comments to the second answer of PATH issue with pytest 'ImportError: No module named YadaYadaYada'so I did not see it, hope it gets more visibility here.
这实际上隐藏在对pytest 'ImportError: No module named YadaYadaYada' PATH 问题的第二个答案的评论中,所以我没有看到它,希望它在这里得到更多的关注。
回答by Tom
I can't say I understand why this works, but I had the same problem and the tests work fine if I run python -m pytest
.
我不能说我理解为什么会这样,但是我遇到了同样的问题,如果我运行python -m pytest
.
I'm in a virtualenv, with pytest also available globally:
我在一个 virtualenv 中,pytest 也可以在全球范围内使用:
(proj)tom@neon ~/dev/proj$ type -a python
python is /home/tom/.virtualenvs/proj/bin/python
python is /usr/bin/python
(proj)tom@neon ~/dev/proj$ python -V
Python 3.5.2
(proj)tom@neon ~/dev/proj$ type -a pytest
pytest is /home/tom/.virtualenvs/proj/bin/pytest
pytest is /usr/bin/pytest
(proj)tom@neon ~/dev/proj$ pytest --version
This is pytest version 3.5.0, imported from /home/tom/.virtualenvs/proj/lib/python3.5/site-packages/pytest.py
回答by Aaron McMillin
I just solved this by removing the __init__.py in my project root:
我刚刚通过删除项目根目录中的 __init__.py 解决了这个问题:
.
├── __init__.py <--- removed
├── models
│?? ├── __init__.py
│?? ├── address.py
│?? ├── appointment.py
│?? └── client.py
├── requirements.txt
├── setup.cfg
├── tests
│?? ├── __init__.py
│?? ├── models
│?? │?? ├── __init__.py
│?? │?? ├── appointment_test.py
│?? │?? └── client_test.py
│?? └── other_test.py
└── script.py
回答by Mark
I had the same problem but for another reason than the ones mentioned:
我遇到了同样的问题,但出于其他原因而不是提到的原因:
I had py.test installed globally, while the packages were installed in a virtual environment.
我在全局安装了 py.test,而软件包安装在虚拟环境中。
The solution was to install pytest
in the virtual environment. (In case your shell hashes executables, as Bash does, use hash -r
, or use the full path to py.test
)
解决方案是安装pytest
在虚拟环境中。(如果您的 shell 散列可执行文件,就像 Bash 那样,请使用hash -r
或使用完整路径到py.test
)
回答by lucasamaral
This problem will happen if you have a tests.py
file and a tests folder with tests/__init__.py
.
如果您有一个tests.py
文件和一个带有tests/__init__.py
.
During the collection pytest finds the folder, but when it tries to import the test files from the folder, tests.py
file will cause the import problem.
pytest在收集过程中找到了文件夹,但是当它试图从文件夹中导入测试文件时,tests.py
文件会导致导入问题。
To fix simply remove the tests.py
file and put all your tests inside the tests/
folder.
要修复,只需删除tests.py
文件并将所有测试放在tests/
文件夹中。
For your specific case the fix will be precisely:
对于您的具体情况,修复将精确地:
- Remove the file
/home/zz/Desktop/GitFolders/rc/tests.py
- Make sure
/home/zz/Desktop/GitFolders/rc/tests/__init__.py
is present
- 删除文件
/home/zz/Desktop/GitFolders/rc/tests.py
- 确保
/home/zz/Desktop/GitFolders/rc/tests/__init__.py
存在
回答by rustysys-dev
I had a similar issue, exact same error, but different cause. I was running the test code just fine, but against an old version of the module. In the previous version of my code one class existed, while the other did not. After updating my code, I should have run the following to install it.
我有一个类似的问题,完全相同的错误,但不同的原因。我运行测试代码很好,但是针对旧版本的模块。在我的代码的先前版本中,一个类存在,而另一个不存在。更新我的代码后,我应该运行以下命令来安装它。
sudo pip install ./ --upgrade
sudo pip install ./ --upgrade
Upon installing the updated module running pytest produced the correct results (because i was using the correct code base).
安装更新的模块后,运行 pytest 产生了正确的结果(因为我使用了正确的代码库)。
回答by Kjeld Flarup
Install the packages into Your virtual environment.
Then start a new shell and source Your virtual environment again.
将软件包安装到您的虚拟环境中。
然后启动一个新的 shell 并再次获取您的虚拟环境。
回答by JoeyZhao
In my case, the import error occurred because the package is pointing to another package/directory with the same nameand its path is one level above the folder I actually wanted. I think this also explains why some people need to remove _ init_.py while others need to add back.
在我的情况下,发生导入错误是因为包指向另一个同名的包/目录,并且其路径比我实际想要的文件夹高一级。我认为这也解释了为什么有些人需要删除 _ init_.py 而其他人需要重新添加。
I just put print(the_root_package.__path__)
(after import the_root_package
) in both python
console and pytest
scripts to compare the difference
我只是把print(the_root_package.__path__)
(after import the_root_package
) 放在python
控制台和pytest
脚本中来比较差异
BOTTOM LINE: When you do python
, the package you import may be different from the package when you run pytest
.
底线:当你这样做时python
,你导入的包可能与你运行时的包不同pytest
。
回答by ZYX
The answer above not work for me. I just solved it by appending the absolute path of the module which not found to the sys.path
at top of the test_xxx.py
(your test module), like:
上面的答案对我不起作用。我只是通过将未找到的模块的绝对路径附加到(您的测试模块)sys.path
顶部来解决它test_xxx.py
,例如:
import sys
sys.path.append('path')
回答by matt6frey
I was experiencing this issue today and solved it by calling python -m pytest
from the root of my project directory.
我今天遇到了这个问题,并通过python -m pytest
从我的项目目录的根调用来解决它。
Calling pytest
from the same location still caused issues.
pytest
从同一位置呼叫仍然会导致问题。
My Project dir is organized as:
我的项目目录组织为:
api/
- server/
- tests/
- test_routes.py
- routes/
- routes.py
- app.py
The module routes
was imported in my test_routes.py
as: from server.routes.routes import Routes
该模块routes
在我的导入test_routes.py
为:from server.routes.routes import Routes
Hope that helps!
希望有帮助!