There are already two posts on stack overflow on this topic; however, none of them have resolved or addressed my specific situation.
I have installed pytest via pip install pytest
. I am able to import the library in Python as well.
The problem is that when I try to use the py.test
command in Terminal, I get py.test: command not found
.
Does anyone have any insight as to why I am not able to use the command in the terminal?
EDIT: It even shows up as an installed package:
$ pip list
cycler (0.9.0)
matplotlib (1.5.1)
numpy (1.10.1)
pip (8.1.0)
py (1.4.31)
pyparsing (2.0.7)
pytest (2.9.0)
python-dateutil (2.4.2)
pytz (2015.7)
scipy (0.17.0)
setuptools (7.0)
six (1.10.0)
tensorflow (0.5.0)
vboxapi (1.0)
wheel (0.26.0)
asked Mar 14, 2016 at 22:05
E. OteroE. Otero
8411 gold badge8 silver badges13 bronze badges
1
using python -m pytest
will work for you.
Or if you using virtual environment and installed pytest on virtualenv you should then run py.test alongside your virtual environment.
Check this website can be useful:http://pythontesting.net/framework/pytest/pytest-introduction/
Jason
8,8185 gold badges35 silver badges35 bronze badges
answered Mar 15, 2016 at 9:14
Ehsan MaiqaniEhsan Maiqani
1,5541 gold badge13 silver badges16 bronze badges
3
I already had the latest version of pytest on macOS with Homebrew-installed Python 2.7 and this fixed it:
pip uninstall pytest
pip install pytest
answered Jan 2, 2017 at 12:44
HugoHugo
27.1k8 gold badges83 silver badges97 bronze badges
Are you on a mac with homebrew by any chance?
I had the same issue and it basically came down to permissions/conflict with the mac os base installed python. pip install would not install or link stuff into /usr/local/bin (it happened with both virtualenv and pytest).
- I uninstalled python 2.7 completely with homebrew (
brew uninstall python
). - Next, I reinstalled python with homebrew to fix pip (it was not a symlink in /usr/local/bin/pip where it should have been linked to Cellar) —
brew install python
- Then I uninstalled pip with sudo —
sudo python -m pip uninstall pip
to remove the pip owned by root - Now I uninstalled and reinstalled python with homebrew again to reinstall pip with the correct permissions
brew uninstall python && brew install python
- Next I fixed the python symlinks
brew link python
- Finally,
pip install pytest
worked! (and so didpip install virtualenv
)
I found the information in the chosen answer from this post very helpful:
https://superuser.com/questions/915810/pip-not-working-on-hombrew-python-2-7-install.
If you’re not on a mac, sorry for the noise…
answered Aug 3, 2016 at 19:43
UgtarUgtar
3002 silver badges7 bronze badges
2
I may be late, but while exploring this I noticed that this can be because the Scripts folder for python is not present in the PATH.
For me this is my scripts folder:
C:Python38Scripts
If the path is a problem then running pip install pytest
should actually you give you the warning with the path it was added to.
This should be present in the path. If on windows, edit the environment variables and this location to the PATH.
For me the path was incorrect because of an improper installation of python
answered Nov 14, 2019 at 7:54
I had the same issue. I had pytest v2.8.3 installed and the binary was on my path but under the name py.test
. Upgrading to v3.0.3 added the regular pytest
executable to the path.
answered Oct 4, 2016 at 4:44
toestoes
5835 silver badges13 bronze badges
I had the same problem. I have changed the Python installed folder permission to full access. And then uninstalled the pytest and installed again.
pip uninstall pytest
answered Jul 13, 2020 at 18:56
In my case, I had a similar issue in ubuntu 20.04. The below solution worked for me.
Cause: Shell remembers the previous version or previously used Path
, hence we need to force the shell to ‘forget’ the old location — with -r
hash -r pytest
Then execute the tests it should work fine.
answered Jan 21, 2021 at 6:50
use the command, pip install -U pytest and install it in your cmd prompt, it will solve the issueenter image description here
answered Sep 3, 2022 at 5:45
I used macbook air m2, and the way I deal with this problem is:
Command in terminal in macbook:
which pytest
/opt/anaconda3/bin/pytest -> my terminal shows this
Then you got the path of pytest, in the «Command», before «pytest», add its path and following with the path of python file you wanna test.
/opt/anaconda3/bin/pytest /Users/cindyng/Desktop/Testing.py
Done, and if you cannot find the path of python in macbook, «which python» also helps, and you can put it in «Home» and «Custom Python Builder».
Hope that helps, good luck!
answered Sep 29, 2022 at 16:29
CindyCindy
11 bronze badge
I Fixed this issue via below steps.
1.First uninstall existing pytest.
2.Check python version.
3.then verify pytest version is supported with python version or not via github issue tracker.
4. via sudo install pytest
sudo pip install pytest
5. verify pytest version and insatlled correctly or not.
pip list
pytest —version
6.run any test using pytest test_abc.py
answered Mar 17, 2019 at 11:29
jayeshjayesh
2,9771 gold badge17 silver badges7 bronze badges
I encounter the same problem, python -m pytest
works for me.
answered Sep 15, 2021 at 7:05
1
There are already two posts on stack overflow on this topic; however, none of them have resolved or addressed my specific situation.
I have installed pytest via pip install pytest
. I am able to import the library in Python as well.
The problem is that when I try to use the py.test
command in Terminal, I get py.test: command not found
.
Does anyone have any insight as to why I am not able to use the command in the terminal?
EDIT: It even shows up as an installed package:
$ pip list
cycler (0.9.0)
matplotlib (1.5.1)
numpy (1.10.1)
pip (8.1.0)
py (1.4.31)
pyparsing (2.0.7)
pytest (2.9.0)
python-dateutil (2.4.2)
pytz (2015.7)
scipy (0.17.0)
setuptools (7.0)
six (1.10.0)
tensorflow (0.5.0)
vboxapi (1.0)
wheel (0.26.0)
asked Mar 14, 2016 at 22:05
E. OteroE. Otero
8411 gold badge8 silver badges13 bronze badges
1
using python -m pytest
will work for you.
Or if you using virtual environment and installed pytest on virtualenv you should then run py.test alongside your virtual environment.
Check this website can be useful:http://pythontesting.net/framework/pytest/pytest-introduction/
Jason
8,8185 gold badges35 silver badges35 bronze badges
answered Mar 15, 2016 at 9:14
Ehsan MaiqaniEhsan Maiqani
1,5541 gold badge13 silver badges16 bronze badges
3
I already had the latest version of pytest on macOS with Homebrew-installed Python 2.7 and this fixed it:
pip uninstall pytest
pip install pytest
answered Jan 2, 2017 at 12:44
HugoHugo
27.1k8 gold badges83 silver badges97 bronze badges
Are you on a mac with homebrew by any chance?
I had the same issue and it basically came down to permissions/conflict with the mac os base installed python. pip install would not install or link stuff into /usr/local/bin (it happened with both virtualenv and pytest).
- I uninstalled python 2.7 completely with homebrew (
brew uninstall python
). - Next, I reinstalled python with homebrew to fix pip (it was not a symlink in /usr/local/bin/pip where it should have been linked to Cellar) —
brew install python
- Then I uninstalled pip with sudo —
sudo python -m pip uninstall pip
to remove the pip owned by root - Now I uninstalled and reinstalled python with homebrew again to reinstall pip with the correct permissions
brew uninstall python && brew install python
- Next I fixed the python symlinks
brew link python
- Finally,
pip install pytest
worked! (and so didpip install virtualenv
)
I found the information in the chosen answer from this post very helpful:
https://superuser.com/questions/915810/pip-not-working-on-hombrew-python-2-7-install.
If you’re not on a mac, sorry for the noise…
answered Aug 3, 2016 at 19:43
UgtarUgtar
3002 silver badges7 bronze badges
2
I may be late, but while exploring this I noticed that this can be because the Scripts folder for python is not present in the PATH.
For me this is my scripts folder:
C:Python38Scripts
If the path is a problem then running pip install pytest
should actually you give you the warning with the path it was added to.
This should be present in the path. If on windows, edit the environment variables and this location to the PATH.
For me the path was incorrect because of an improper installation of python
answered Nov 14, 2019 at 7:54
I had the same issue. I had pytest v2.8.3 installed and the binary was on my path but under the name py.test
. Upgrading to v3.0.3 added the regular pytest
executable to the path.
answered Oct 4, 2016 at 4:44
toestoes
5835 silver badges13 bronze badges
I had the same problem. I have changed the Python installed folder permission to full access. And then uninstalled the pytest and installed again.
pip uninstall pytest
answered Jul 13, 2020 at 18:56
In my case, I had a similar issue in ubuntu 20.04. The below solution worked for me.
Cause: Shell remembers the previous version or previously used Path
, hence we need to force the shell to ‘forget’ the old location — with -r
hash -r pytest
Then execute the tests it should work fine.
answered Jan 21, 2021 at 6:50
use the command, pip install -U pytest and install it in your cmd prompt, it will solve the issueenter image description here
answered Sep 3, 2022 at 5:45
I used macbook air m2, and the way I deal with this problem is:
Command in terminal in macbook:
which pytest
/opt/anaconda3/bin/pytest -> my terminal shows this
Then you got the path of pytest, in the «Command», before «pytest», add its path and following with the path of python file you wanna test.
/opt/anaconda3/bin/pytest /Users/cindyng/Desktop/Testing.py
Done, and if you cannot find the path of python in macbook, «which python» also helps, and you can put it in «Home» and «Custom Python Builder».
Hope that helps, good luck!
answered Sep 29, 2022 at 16:29
CindyCindy
11 bronze badge
I Fixed this issue via below steps.
1.First uninstall existing pytest.
2.Check python version.
3.then verify pytest version is supported with python version or not via github issue tracker.
4. via sudo install pytest
sudo pip install pytest
5. verify pytest version and insatlled correctly or not.
pip list
pytest —version
6.run any test using pytest test_abc.py
answered Mar 17, 2019 at 11:29
jayeshjayesh
2,9771 gold badge17 silver badges7 bronze badges
I encounter the same problem, python -m pytest
works for me.
answered Sep 15, 2021 at 7:05
1
Comments
Whenever I run the tests, I always getting this strange error:
Detail: Unable to read file (Error: File not found
I really don’t have a c
file in my project. But where is it coming from?
This seems to happen due to inline >>>
tests, actually.
ghost
removed
the
triage-needed
Needs assignment to the proper sub-team
label
Jul 11, 2019
I’m getting a similar error:
Environment data
- VS Code version: 1.36.1
- Extension version (available under the Extensions sidebar): 2019.6.24221
- OS and version: Windows 10
- Python version (& distribution if applicable, e.g. Anaconda): 3.7.3
- Type of virtual environment used (N/A | venv | virtualenv | conda | …): venv
- Relevant/affected Python packages and their versions: pytest version 5.0.1
Expected behaviour
no «file not found» errors being displayed in the output channel when running tests
Actual behaviour
«file not found» error is displayed in the output channel. In the case below, for some reason the «tests» folder is being ignored in the file path:
Steps to reproduce:
-
Open a folder with tests following this structure:
-
Have at least one of the tests methods fail
-
Make sure you have a pytest.ini file in the tests folder (in this case I only had
[pytest] addopts = -s -v
in it) -
Reload the window and run all tests. Watch the following error appear:
Logs
Output for Python
in the Output
panel (View
→Output
, change the drop-down the upper-right of the Output
panel to Python
)
python C:Usersluabud.vscodeextensionsms-python.python-2019.6.24221pythonFilestesting_toolsrun_adapter.py discover pytest -- -s --cache-clear tests
============================= test session starts =============================
platform win32 -- Python 3.7.3, pytest-4.6.3, py-1.8.0, pluggy-0.12.0 -- C:UsersluabudAppDataLocalProgramsPythonPython37python.exe
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('c:\Users\luabud\Apps\vscode\.hypothesis\examples')
rootdir: c:UsersluabudAppsvscodetests, inifile: pytest.ini
plugins: hypothesis-4.24.4
collecting ... collected 8 items
testsonetest_a.py::test_a_1 PASSED
testsonetest_a.py::test_a_2 PASSED
testsonetest_b.py::test_b_1 PASSED
testsonetest_b.py::test_b_2 PASSED
teststwotest_c.py::test_c_1 PASSED
teststwotest_c.py::test_c_2 PASSED
teststwotest_d.py::test_d_1 PASSED
teststwotest_d.py::test_d_2 FAILED
================================== FAILURES ===================================
__________________________________ test_d_2 ___________________________________
def test_d_2():
> assert 0 == 1
E assert 0 == 1
E -0
E +1
teststwotest_d.py:6: AssertionError
- generated xml file: C:UsersluabudAppDataLocalTemptmp-15700c0uP9mjmCb59.xml -
===================== 1 failed, 7 passed in 0.08 seconds ======================
Error: Error: cannot open file:///c%3A/Users/luabud/Apps/vscode/two/test_d.py. Detail: Unable to read file (Error: File not found (c:UsersluabudAppsvscodetwotest_d.py))
Output from Console
under the Developer Tools
panel (toggle Developer Tools on under Help
; turn on source maps to make any tracebacks be useful by running Enable source map support for extension debugging
)
This seems to happen due to inline
>>>
tests, actually.
Can you please paste the directory structure and content, like @luabud did. Will help to reproduce the issue.
@luabud I can confirm that if test directory contains an pytest.ini
, and file path for the files in the test directory are being incorrectly calculated while running tests.
For eg.
Expected path: c:UsersluabudAppsvscodeteststwotest_d.py
Actual path: c:UsersluabudAppsvscodetwotest_d.py
Not sure if it the same bug or not. Getting File not found
on Mac OS for pytest when click on shaded Run Test
above the test. The file and the test obviously exist. Error is below.
============================= test session starts ==============================
platform darwin -- Python 3.7.3, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: /Users/vistatest/Git/vista
plugins: postgresql-1.4.0, flask-0.14.0, mock-1.10.4, flask-sqlalchemy-1.0.2
collected 0 items
- generated xml file: /var/folders/lv/_hsxgz4926343l7tn7tc43wm0000gn/T/tmp-1213osfyIlUdGERC.xml -
========================= no tests ran in 0.01 seconds =========================
ERROR: file not found: ./git_work/test_fsrepo.py::test_fsrepo_local_stats
i have the exactly same issue as following when the file is actually in the folder, «d:workspacenebula_datafolderabcteststest_china_stock_basics.py»
Error Detail: Unable to read file (Error: File not found (d:workspacenebula_datateststest_china_stock_basics.py))
seems the pytest incorrectly calculated the path of file by ignoring its parently folder, but it wired that actually other test files in the same folder works well.
I’m seeing the same issue with the most basic of tests. Running from the terminal from within VS Code works fine. Using the test runner appears to work okay from the test run (it says the 1 test passed), but generates an error that appears to keep the output from been sent to the test summary window.
Test and class file are just directly in a folder that I have opened as the workspace.
Output from test output window:
python C:Users210068178.vscodeextensionsms-python.python-2019.8.30787pythonFilestesting_toolsrun_adapter.py discover pytest -- -s --cache-clear . ============================= test session starts ============================= platform win32 -- Python 3.7.4, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: C:Codepythonps_unit_testing_with_python collected 1 item test_phonebook.py . [100%] - generated xml file: C:Users210068~1AppDataLocalTemptmp-25948AQtNhyZ0M6Ak.xml - ============================== 1 passed in 0.05s ============================== Error: TypeError: Cannot read property '$' of undefined
Output when running from terminal:
$ py -m pytest ======================================== test session starts ========================================= platform win32 -- Python 3.7.4, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: C:Codepythonps_unit_testing_with_python collected 1 item test_phonebook.py . [100%] ========================================= 1 passed in 0.04s ========================================== (.venv) 210068178@GCXLSHV2E MINGW64 /c/Code/python/ps_unit_testing_with_python (module_3_basic-examples-with-pytest) $
VS Code Help Info:
Version: 1.37.1 (user setup)
Commit: f06011ac164ae4dc8e753a3fe7f9549844d15e35
Date: 2019-08-15T16:17:55.855Z
Electron: 4.2.7
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Windows_NT x64 10.0.17763
@LightCC thanks for reporting this ! The issue you’re seeing seems to be this one: #6990, and it’s related to pytest 5.1. We’re working hard to get it fixed.
fwiw, I was seeing the issue #6990 but then i downgraded to pytest 5.01 and that issue went away. but i still have this issue (file not found on all tests i execute).
luabud
added
the
important
users impacted; must be fixed prior to next release
label
Sep 9, 2019
I have met similar problem with @luabud . And the werid thing is that it works fine when I start tests by clicking the button from the side panel.
and fails for all the other situation.
Copy link
CMLL
commented
Sep 18, 2019
•
edited by ericsnowcurrently
CMLL
commented
Sep 18, 2019
•
edited by ericsnowcurrently
I’ve also ran into the above issue.
Log output:
-------------- generated xml file: /tmp/tmp-25268acIAnO16YeGR.xml --------------
========================= no tests ran in 0.00 seconds =========================
ERROR: file not found: ./unit/dashboards/test_widget_timescale.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.15+, pytest-4.4.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/cllamach/Panopta/classic
plugins: xdist-1.28.0, sugar-0.9.2, pythonpath-0.7.3, forked-1.0.2, env-0.6.2, pylama-7.7.1
-------------- generated xml file: /tmp/tmp-25268YJtfJRChbkNv.xml --------------
========================= no tests ran in 0.00 seconds =========================
ERROR: file not found: ./unit/dashboards/test_widget_timescale.py::test_parse_returns_timescale_at_right_timezeone
File Structure:
src/
tests/
unit/
dashboards/
test_widget_timescale.py
Settings:
"python.testing.pytestArgs": [
"src/tests/"
],
As has already been noted, if there is a pytest.ini file in the test root then we run into this problem. I was able to verify that this is not a problem if the file is in any other directory, even a sub-directory of the test root.
I also found that this bug is impacted by test discovery. The following two cases indicate that test execution is tied to test discovery:
- remove pytest.ini after discovery
- add pytest.ini in the test root
- discover tests
- remove pytest.ini
- run tests (the bug happens unexpectedly)
- add pytest.ini after discovery
- discover tests
- add pytest.ini in the test root
- run tests (the bug does not happen…unexpectedly)
Running with «—cache-clear» did not make a difference.
I also found that running a single test fails because it tries to use a path relative to the test root rather than CWD (the workspace root). This is basically the same problem.
Finally, I was able to reproduce the problem at revision b4aa1f0, which predates the recent refactoring of the XUnit parser (#7263/#7265 for #6990).
The key problem is that, with pytest.ini in the test root, pytest returns filenames (for both discovery and execution) that are relative to the test root. In all other cases they are relative to the workspace root. However, the extension code makes the assumption that the relative filenames are always relative to the workspace root.
In the case of a failed test we do a lookup using the absolute filename (see TestMessageService.getLocationStack()
).
This will be resolved if we do one of the following:
- where used, always resolve the filename relative to the discovered test root
- during discovery (and execution) store the relative filename correctly resolved to the workspace root (based on the test root)
- during discovery (and execution) store the absolute filename (merge the given one with the test root, which is always absolute)
I prefer (3).
In the case of running individual tests, that will be resolved if we do one of the following:
- during discovery store the correct relative filename in «fileToRun» (i.e. relative to workspace root)
- during discovery store the absolute filename in fileToRun (may not be right)
- during execution, resolve «fileToRun» against the workspace root (as necessary)
(Note that «fileToRun» is not modified during execution, at least for pytest.)
I prefer (1).
It turns out this is the defined behavior for pytest. It will walk up the directory tree, starting at the given directory/file, and set the first ancestor directory with a pytest.ini file as the root. That is exactly what everyone is seeing. The problem is that the extension isn’t coping well with this behavior. It’s going to take some cleverness to get this right.
This was referenced
Oct 7, 2019
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
✅ Validated using version 2019.11.41015-dev
of the extension and this folder structure (all passing tests):
Tests are being discovered and run correctly:
lock
bot
locked as resolved and limited conversation to collaborators
Oct 16, 2019
If you are using Pytest to test Python code and accidentally get the “ModuleNotFoundError: No module named ‘pytest’” in Python, let’s read this article carefully. It will help you fix the above error in the simplest way.
What is Pytest?
Unlike most programming languages, Python uses a built-in library for testing called pytest. Pytest is a framework that makes building simple and scalable tests easy.
When does the ModuleNotFoundError: No module named ‘pytest’ in Python occur? And how to fix it?
Import pytest, but not installed
“ModuleNotFoundError: No module named ‘pytest’” in Python appears when we import pytest and run the test while we don’t have the pytest module installed. See the code below for how the error occurs:
# Import pytest but not installed
import pytest
def sum(a, b):
return a + b
def test_function():
assert sum(3, 5) == 8
Output:
ModuleNotFoundError: No module named 'pytest'
To fix it, install pytest by opening a terminal and typing the following command:
pip install pytest
Now all we need to do is importing and using pytest:
import pytest
def sum(a, b):
return a + b
def test_function():
assert sum(3, 5) == 8
Output:
Import with the wrong name
Some libraries must capitalize the first letter in Python when importing, but pytest is different. We do not need to capitalize the first letter of the pytest.
# Import wrong name
import Pytest
def sum(a, b):
return a + b
def test_function():
assert sum(3, 5) == 8
Output:
ModuleNotFoundError: No module named 'Pytest'
Because pytest and Pytest are different modules, so you can fix this error by using import pytest instead of import Pytest.
import pytest
def sum(a, b):
return a + b
def test_function():
assert sum(3, 5) == 8
Output:
Install pytest manually but forgot to run setup.py
This error also appears when you install pytest using the package downloaded here. And forgot to run the command:
python setup.py install
Below is the complete guide to help you install pytest manually:
After downloading the installation package, open the terminal and type:
where python
The returned result will be the path to the Python installation directory. As below:
You go to the Python310 directory as the above path. Then continue to go to the folder: Libsite-packages
.
Here, you paste the pytest installation file and extract it. After extracting, you will get the folder like this:
You’re mistaken if you think we have successfully installed pytest in this step. Here is an example if you use pytest in this step.
# Haven't run setup.py
import pytest
def sum(a, b):
return a + b
def test_function():
assert sum(3, 5) == 8
Output:
ModuleNotFoundError: No module named 'pytest'
As you can see, the error ModuleNotFoundError: No module named ‘pytest’ still appears.
To complete the installation, move to the pytest folder and open a terminal, and type:
python setup.py install
If you see the following message:
Finished processing dependencies for pytest==7.1.3
That means you have successfully installed it. Now you can use pytest without the “ModuleNotFoundError: No module named ‘pytest’”.
import pytest
def sum(a, b):
return a + b
def test_function():
assert sum(3, 5) == 8
Output:
Summary
That’s for the “ModuleNotFoundError: No module named ‘pytest’” in Python. If you have any questions, please leave us a comment. We will respond as possible. Thank you for reading!
Have a nice day!
Maybe you are interested:
- AttributeError: ‘set’ object has no attribute ‘items’ in Python
- How To ModuleNotFoundError: No Module Named ‘absl’ In Python
- ModuleNotFoundError: No module named ‘tensorflow’ in python
Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java