问题:pytest无法导入模块,而python可以
我正在使用Python开发包。我使用virtualenv。我在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
但是,如果我尝试使用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
我有点疑惑,它看起来像是一个导入错误,但是Python很好,所以为什么PyTest特有问题?对原因/补救措施有什么建议(问题2)?我用谷歌搜索并堆栈溢出了PyTest的“ ImportError:无法导入”错误,但是我得到的结果与缺少python路径有关,并且对此有补救措施,这似乎不是这里的问题。有什么建议?
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):
(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:
(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?
回答 0
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.
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.
回答 1
我不能说我理解为什么会这样,但是我遇到了同样的问题,如果运行,测试也可以正常工作python -m pytest
。
我在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
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
.
I’m in a virtualenv, with pytest also available globally:
(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
回答 2
我只是通过删除项目根目录中的__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
I just solved this by removing the __init__.py in my project root:
.
├── __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
回答 3
我遇到了同样的问题,但是由于上述原因之外的另一个原因:
我在全局安装了py.test,而软件包则安装在虚拟环境中。
解决方案是pytest
在虚拟环境中安装。(如果您的shell像Bash一样哈希可执行文件,请使用hash -r
,或使用的完整路径py.test
)
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.
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
)
回答 4
如果您有一个tests.py
文件和一个带有的测试文件夹,则会发生此问题tests/__init__.py
。
在收集过程中,pytest会找到文件夹,但是当尝试从文件夹中导入测试文件时,tests.py
文件会导致导入问题。
要解决此问题,只需删除tests.py
文件,然后将所有测试放在tests/
文件夹中即可。
对于您的特定情况,修复将精确地是:
- 删除文件
/home/zz/Desktop/GitFolders/rc/tests.py
- 确保
/home/zz/Desktop/GitFolders/rc/tests/__init__.py
存在
This problem will happen if you have a tests.py
file and a tests folder with 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.
To fix simply remove the tests.py
file and put all your tests inside the tests/
folder.
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
回答 5
我有一个类似的问题,完全相同的错误,但原因不同。我正在运行测试代码,但是使用的是模块的旧版本。在我的代码的先前版本中,一个类存在,而另一个不存在。更新代码后,我应该运行以下命令进行安装。
sudo pip install ./ --upgrade
安装更新的模块后,运行pytest会产生正确的结果(因为我使用的是正确的代码库)。
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
Upon installing the updated module running pytest produced the correct results (because i was using the correct code base).
回答 6
在我的情况下,发生导入错误是因为程序包指向另一个具有相同名称的程序包/目录,并且其路径在我实际想要的文件夹上方一层。我认为这也解释了为什么有些人需要删除_ init _.py而另一些人需要重新添加。
我只是在控制台和脚本中print(the_root_package.__path__)
(在之后import the_root_package
)放置以比较差异python
pytest
底线:执行此操作时python
,导入的包可能与运行时的包不同pytest
。
In my case, the import error occurred because the package is pointing to another package/directory with the same name and 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.
I just put print(the_root_package.__path__)
(after import the_root_package
) in both python
console and pytest
scripts to compare the difference
BOTTOM LINE: When you do python
, the package you import may be different from the package when you run pytest
.
回答 7
将软件包安装到您的虚拟环境中。
然后启动一个新的Shell并再次获取您的虚拟环境。
Install the packages into Your virtual environment.
Then start a new shell and source Your virtual environment again.
回答 8
上面的答案对我不起作用。我只是通过将未找到的模块的绝对路径附加到(您的测试模块)的sys.path
顶部来解决它test_xxx.py
,例如:
import sys
sys.path.append('path')
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:
import sys
sys.path.append('path')
回答 9
如果它与最初在python 2.7中开发,现在迁移到python 3.x的python代码有关,则该问题可能与导入问题有关。
例如,从base
同一目录中的文件导入对象时,它将在python 2.x中工作:
from base import MyClass
在python 3.x中,您应该替换为base
完整路径,否则.base
将导致上述问题。所以尝试:
from .base import MyClass
If it is related to python code that was originally developed in python 2.7 and now migrated into python 3.x than the problem is probably related to an import issue.
e.g.
when importing an object from a file: base
that is located in the same directory this will work in python 2.x:
from base import MyClass
in python 3.x you should replace with base
full path or .base
not doing so will cause the above problem.
so try:
from .base import MyClass
回答 10
我今天遇到了这个问题,并通过python -m pytest
从项目目录的根目录进行调用来解决了。
pytest
从同一位置拨打电话仍然会引起问题。
我的项目目录组织为:
api/
- server/
- tests/
- test_routes.py
- routes/
- routes.py
- app.py
该模块routes
以我的test_routes.py
身份导入:from server.routes.routes import Routes
希望有帮助!
I was experiencing this issue today and solved it by calling python -m pytest
from the root of my project directory.
Calling pytest
from the same location still caused issues.
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
Hope that helps!
回答 11
另一个特殊情况:
我在使用毒药时遇到了问题。因此,我的程序运行良好,但是通过Tox进行的单元测试一直在抱怨。安装软件包(程序需要)之后,您需要另外在tox.ini中指定单元测试中使用的软件包。
[testenv]
deps =
package1
package2
...
Another special case:
I had the problem using tox. So my program ran fine, but unittests via tox kept complaining. After installing packages (needed for the program) you need to additionally specify the packages used in the unittests in the tox.ini
[testenv]
deps =
package1
package2
...
回答 12
我正在使用VSCode来获得它。我有一个conda环境。我不认为VScode python扩展可以看到我所做的更新。
python c:\Users\brig\.vscode\extensions\ms-python.python-2019.9.34911\pythonFiles\testing_tools\run_adapter.py discover pytest -- -s --cache-clear test
Test Discovery failed:
我必须跑步 pip install ./ --upgrade
I was getting this using VSCode. I have a conda environment. I don’t think the VScode python extension could see the updates I was making.
python c:\Users\brig\.vscode\extensions\ms-python.python-2019.9.34911\pythonFiles\testing_tools\run_adapter.py discover pytest -- -s --cache-clear test
Test Discovery failed:
I had to run pip install ./ --upgrade
回答 13
编辑您的conftest.py并添加以下代码行:
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), '..')))
如果尝试通过终端运行测试用例,请使用以下示例:
python -m pytest test_some_step_file_steps.py --html=HTML_step_file_output.html --self-contained-html
Edit your conftest.py and add following lines of code:
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), '..')))
And if trying to run the test case through terminal, use following ex:
python -m pytest test_some_step_file_steps.py --html=HTML_step_file_output.html --self-contained-html
回答 14
Python的导入系统又获得了一次巨大的胜利。我认为,没有达成共识的原因是,有效的方法可能取决于您的环境以及在其上使用的工具。
我正在VS Code中使用它,它是在conda环境下Windows的Python 3.8中的测试资源管理器中使用的。
我要工作的设置是:
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
在这种设置下,智能感知将起作用,测试发现也将起作用。
请注意,我最初试图以下,推荐这里。
src/
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
我找不到从VS Code上src
使它起作用的方法,因为该文件夹使导入系统无所适从。我可以想象有一种方法可以从命令行运行它。作为一种相对较新的Python编程转换,它带给我怀旧的使用COM的感觉,但是却没有那么有趣。
Yet another massive win for Python’s import system. I think the reason there is no consensus is that what works probably depends on your environment and the tools you are using on top of it.
I’m using this from VS Code, in the test explorer under Windows in a conda environment, Python 3.8.
The setup I have got to work is:
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
Under this setup intellisense works and so does test discovery.
Note that I originally tried the following, as recommended here.
src/
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
I could find no way of getting this to work from VS Code because the src
folder just blew the mind of the import system. I can imagine there is a way of getting this to work from the command line. As a relatively new convert to Python programming it gives me a nostalgic feeling of working with COM, but being slightly less fun.
回答 15
如果不使用虚拟环境,我为此付出的2美分:pytest会偶然失败。有时它会工作,有时则不会。
因此,解决方案是:
- 用pip卸载删除pytest
- 创建您的venv
- 激活你的venv
- pip以可编辑模式安装项目路径,因此pytest会将其视为模块(否则,pytest将找不到您的内部导入)。您将需要一个setup.py文件
- 安装您的软件包,包括pytest
- 最后,运行测试
使用Windows PowerShell的代码:
pip uninstall pytest
python.exe -m venv my_env
.\my_env\Scripts\activate
(my_env) pip install -e .
(my_env) pip install pytest pytest-html pandas numpy
然后最后
(my_env) pytest --html="my_testing_report.html"
用于pip install -e的setup.py示例:
import setuptools
setuptools.setup(
name='my_package',
version='devel',
author='erickfis',
author_email='erickfis@gmail.com',
description='My package',
long_description='My gooood package',
packages=setuptools.find_packages(),
classifiers=[
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
],
include_package_data=True
)
My 2 cents on this: pytest will fail at chance if you are not using virtual environments. Sometimes it will just work, sometimes not.
Therefore, the solution is:
- remove pytest with pip uninstall
- create your venv
- activate your venv
- pip install your project path in editable mode, so it will be treated by pytest as a module (otherwise, pytest wont find your internal imports). You will need a setup.py file for that
- install your packages, including pytest
- finally, run your tests
The code, using windows PowerShell:
pip uninstall pytest
python.exe -m venv my_env
.\my_env\Scripts\activate
(my_env) pip install -e .
(my_env) pip install pytest pytest-html pandas numpy
Then finally
(my_env) pytest --html="my_testing_report.html"
An example of setup.py, for pip install -e:
import setuptools
setuptools.setup(
name='my_package',
version='devel',
author='erickfis',
author_email='erickfis@gmail.com',
description='My package',
long_description='My gooood package',
packages=setuptools.find_packages(),
classifiers=[
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
],
include_package_data=True
)
回答 16
我不同意这些帖子,说您必须删除所有__init__.py
文件。您必须要做的是更改sys.path
。
在sys.path
正常运行代码的情况下,在您进行打印的地方进行实验。然后sys.path
在通过pytest运行代码的同时进行打印。我认为您会发现这两条路径之间存在差异,因此pytest为什么会中断。
要解决此问题,请将第一个实验的路径插入第二个实验的第0个索引。
我们'/usr/exampleUser/Documents/foo'
是第一个元素print(sys.path)
的实验1。
以下是应该解决您问题的代码:
import sys
sys.path[0] = '/usr/exampleUser/Documents/foo'
在实际导入语句之前,将此内容放在文件顶部。
资料来源:我本人正在处理,上述过程解决了它。
I disagree with the posts saying that you must remove any __init__.py
files. What you must instead do is alter the sys.path
.
Run an experiment where you print sys.path
when running the code normally.
Then print sys.path
while running the code via pytest. I think you will find that there is a difference between these two paths, hence why pytest breaks.
To fix this, insert the path from the first experiment at the 0th index of the second.
Let '/usr/exampleUser/Documents/foo'
be the first element of print(sys.path)
for experiment 1.
Below is code that should fix your issue:
import sys
sys.path[0] = '/usr/exampleUser/Documents/foo'
Put this at the top of your file, before your actual import statement.
Source: I was dealing with this myself and the above process solved it.
回答 17
一切都保持相同,只是增加了在根文件夹中的空白测试文件..解决它
这是调查结果,这个问题确实困扰了我一段时间。我的文件夹结构是
mathapp/
- server.py
- configuration.py
- __init__.py
- static/
- home.html
tests/
- functional
- test_errors.py
- unit
- test_add.py
pytest会抱怨ModuleNotFoundError并给出提示-确保您的测试模块/软件包具有有效的Python名称。
我在与mathsapp和tests目录相同的级别引入了模拟测试文件。该文件不包含任何内容。现在pytest不会抱怨。
没有文件的结果
$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error
=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
from mathapp.service import sum
E ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================
结果与文件
$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items
tests\functional\test_func.py . [ 50%]
tests\unit\test_unit.py . [100%]
============================== 2 passed in 0.11s ==============================
Kept everything same and just added a blank test file at the root folder .. Solved it
Here are the findings, this problem really bugged me for a while. My folder structure was
mathapp/
- server.py
- configuration.py
- __init__.py
- static/
- home.html
tests/
- functional
- test_errors.py
- unit
- test_add.py
and pytest would complain with the ModuleNotFoundError and gives the HINT – make sure your test modules/packages have valid Python names.
I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.
Result without the file
$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error
=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
from mathapp.service import sum
E ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================
Results with the file
$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items
tests\functional\test_func.py . [ 50%]
tests\unit\test_unit.py . [100%]
============================== 2 passed in 0.11s ==============================
回答 18
我通过PYTHONPATH
为运行测试的特定配置设置环境变量解决了我的问题。
在PyCharm上查看测试文件时:
Ctrl
+ Shift
+A
- 类型
Edit Configurations
PYTHONPATH
在环境>环境变量下设置。
I solved my problem by setting the PYTHONPATH
in Environment Variables for the specific configuration I’m running my tests with.
While you’re viewing the test file on PyCharm:
Ctrl
+Shift
+A
- Type
Edit Configurations
- Set your
PYTHONPATH
under Environment > Environment variables.
回答 19
只需将一个空conftest.py
文件放在项目根目录中,因为当pytest
发现conftest.py时,它将修改sys.path以便可以从conftest
模块中导入内容。常规目录结构可以是:
Root
├── conftest.py
├── module1
│ ├── __init__.py
│ └── sample.py
└── tests
└── test_sample.py
Simply put an empty conftest.py
file in the project root directory, because when pytest
discovers a conftest.py, it modifies sys.path so it can import stuff from the conftest
module.
A general directory structure can be:
Root
├── conftest.py
├── module1
│ ├── __init__.py
│ └── sample.py
└── tests
└── test_sample.py
回答 20
有一个类似的问题,当我__init__.py
在tests目录下添加文件时,它可以工作。
Had a similar issue and it worked when I added __init__.py
file under tests directory.
回答 21
可能是因为Pytest并未将Python包作为Python模块读取(可能是由于路径问题)。尝试更改pytest脚本的目录或将模块显式添加到PYTHONPATH。
也可能是您的计算机上安装了两个版本的Python。检查您的Python源是否有pytest和您运行的python shell。如果它们不同(例如,Python 2 vs 3),请使用source activate
来确保您正在为安装模块的相同python运行pytest。
It could be that Pytest is not reading the package as a Python module while Python is (likely due to path issues). Try changing the directory of the pytest script or adding the module explicitly to your PYTHONPATH.
Or it could be that you have two versions of Python installed on your machine. Check your Python source for pytest and for the python shell that you run. If they are different (i.e. Python 2 vs 3), use source activate
to make sure that you are running the pytest installed for the same python that the module is installed in.
回答 22
对于任何尝试了一切但仍然出错的人,我都有解决方法。
在安装pytest的文件夹中,转到pytest-env文件夹。
打开 pyvenv.cfg文件。
在文件中,将include-system-site-packages从false更改为true。
home = /usr/bin
include-system-site-packages = true
version = 3.6.6
希望它能起作用。不要忘记投票。
For anyone who tried everything and still getting error,I have a work around.
In the folder where pytest is installed,go to pytest-env folder.
Open pyvenv.cfg file.
In the file change include-system-site-packages from false to true.
home = /usr/bin
include-system-site-packages = true
version = 3.6.6
Hope it works .Don’t forget to up vote.
回答 23
如果您已经有.pyc文件,请尝试将其删除。
今天,我遇到了这个问题,这是发生了什么:
首先,我在Mac中运行pytest(这将生成pyc文件),然后启动安装了项目目录的docker容器(操作系统为alpine),然后尝试在容器中运行pytest时,发生ImportError。清除所有pyc文件后,再也没有错误。
希望这会有所帮助。
If you already have .pyc files, try to delete them.
Today, I encounter this problem, here is what happend:
first I run pytest in mac (this will generate pyc files) then I launch a docker container (the os is alpine), with project dir mounted, and then when I try to run pytest in container, ImportError happens. after cleaning all pyc files, no error any more.
Hope this may be helpful.
回答 24
如果您的文件夹中需要一个init .py文件,请制作该文件夹的副本,然后删除其中的init .py来运行您的测试,该测试适用于本地项目。如果需要定期运行测试,请查看是否可以将init .py移到单独的文件中。
if you need a init.py file in your folder make a copy of the folder and delete init.py in that one to run your tests it works for local projects. If you need to run test regularly see if you can move your init.py to a separate file.
回答 25
[解决]在直接进入删除/添加的解决方案之前__init__.py
,我们可能还想看一下如何在您的类中完成导入。实际上,我只是__init__.py
想着这可能是问题的原因,所以迷失了一天。)但是,那确实很有用。
就我而言,这是将类从一个python类调用到另一个正在抛出的python类的错误方式 ImportError
。修复了类/模块的调用方式,它就像魅力一样工作。希望这对其他人也有帮助。
是的,对于类似的错误,根据代码的编写方式,我们可能有不同的解决方案。最好花更多时间进行自我调试。获得的经验:)编码愉快!!!
[Resolved]
Before directly jumping into the solution of removing/ adding __init__.py
, we might also want to look at how the imports are been done in your classes. Actually, I lost a day playing around with just __init__.py
thinking that might be the problem :) However, that was quite informative.
In my case, it was the wrong way of calling classes from one python class to another python class which was throwing ImportError
. Fixed the way classes/ modules to be called and it worked like charm. Hope, this helps others as well.
And yes, for similar error, we might have different solutions depending on how the code is written. Better to spend more time on self debugging. Lesson Learnt :) Happy coding!!!
回答 26
就我而言,我在一个容器中工作,不幸的是pytest倾向于使用python2.7而不是我选择的python3解释器。
就我而言,这可行:
python3 -m pytest
我的文件夹结构
/
app/
-module1.py
-module2.py
-tests/
--test_module1.py
--test_module2.py
requirements.txt
README.md
In my case I am working in a container and unfortuantely pytest has the tendency to use python2.7 rather than my python3 interpreter of choice.
In my case this worked:
python3 -m pytest
My folder structure
/
app/
-module1.py
-module2.py
-tests/
--test_module1.py
--test_module2.py
requirements.txt
README.md
回答 27
我已经将所有测试放在一个tests文件夹中,并且得到了相同的错误。我通过在该文件夹中添加init .py 来解决此问题,如下所示:
.
|-- Pipfile
|-- Pipfile.lock
|-- README.md
|-- api
|-- app.py
|-- config.py
|-- migrations
|-- pull_request_template.md
|-- settings.py
`-- tests
|-- __init__.py <------
|-- conftest.py
`-- test_sample.py
I had placed all my tests in a tests folder and was getting the same error. I solved this by adding an init.py in that folder like so:
.
|-- Pipfile
|-- Pipfile.lock
|-- README.md
|-- api
|-- app.py
|-- config.py
|-- migrations
|-- pull_request_template.md
|-- settings.py
`-- tests
|-- __init__.py <------
|-- conftest.py
`-- test_sample.py
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。