You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Pytest discovery fails if something is printed to stderr #18431
What I may say, in my current project it's two apps in one codebase. Depending on the env variable (that is set in the .env file) - it may be run in one or another way.
When I run the tests, I do it like this APP_ENV=test APP_NAME=backend pytest backend and it runs only the tests for the part of the project. If I need to run other part of tests - I do APP_ENV=test APP_NAME=frontend pytest frontend
I did not find how make the test discovery that is used by VS Code to specify env variables.
All what I need from VS Code discovery - just to show me a list of all tests I have in the codebase. And also to have a "run" icon near each test function.
Currently I do run tests manually. I have defined in my launch.json next snippet. I change it to run individual test, if I do not need to run all tests in the file:
{
"name": "Run current test",
"type": "python",
"request": "launch",
"module": "pytest",
"env": {
"APP_ENV": "test",
"APP_NAME": "backend",
},
"justMyCode": false,
"args": [
"--no-cov",
// Test current file
"${file}",
// Filter tests by name
"-k test_some_feature_name",
],
"console": "integratedTerminal",
},
It works to me fine. Only thing that I do often - opening the launch.json file and change the -k flag each time when I need to run other test. And it's annoying.
Maybe it's a way to make Test Discovery works fine with pytest for such a project?
Perhaps I'm getting something similar which seems to stem from the discovery process trying to run my module itself with bad command line options. I'm really new to setting up a new project here so very unsure if this is my problem or similar to what others have reported here.
This bit puzzles me, why is discovery trying to run podping-hivewatcher (my project) with pytest command line options.
Not sure if something in conda is able to interpret ~\.vscode\extens... as %userprofile%\.vscode\extens... (I'm running on Windows where "~" doesn't resolve to anything).
If I try to copy that command (and replace the "~" with userprofile path), it fails as follows
(I've added -v flags to conda run to try to get more info):
I also tried removing the get_output_via_markers.py component of the command - still no success. But I noticed that
it seemed to be trying to execute pytest from the conda base environment rather than the current conda env.
Issues with conda are most likely related to Debugging does not work with a conda environment #18436, since we recently changed how we run tools when in a conda environment. We hope to make a hotfix release today or tomorrow, please try it out whenever it comes out, and if it still doesn't work please open a separate issue;
When creating a conda environment, make sure you create it with the python=3.XXX argument, or the extension won't recognize it as a conda environment;
We currently do not support setting environment variables in the test runner, we have an open feature request for it: Support setting environmental variables for the test runner #17171. Please upvote it to show your interest and help us prioritize it! A workaround for now would be to specify your environment variables in a .env file.
I struggle with a similar issue and I think it depends on a similar problem with printing to stderr.
At the moment one of my tests is failing and terminal output looks as following:
❯ pytest
================================================== test session starts ===================================================
platform linux -- Python 3.10.4, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- /run/media/makanu/Daten/GIT/boxsup_pytorch/.venv/bin/python
cachedir: .pytest_cache
rootdir: /run/media/makanu/Daten/GIT/boxsup_pytorch, configfile: pyproject.toml
plugins: cov-2.12.1
collected 4 items
tests/test_boxsup_pytorch.py::test_project_info PASSED [ 25%]
tests/test_losses.py::test_overlapping_1 PASSED [ 50%]
tests/test_losses.py::test_inter_o_union_even PASSED [ 75%]
tests/test_losses.py::test_inter_o_union_uneven FAILED [100%]
======================================================== FAILURES ========================================================
_______________________________________________ test_inter_o_union_uneven ________________________________________________
bounding_box = array([[0, 1],
[0, 0]])
full_overlap_cands = array([[[0, 1],
[0, 0]],
[[0, 1],
[0, 0]],
[[0, 1],
[0, 0]]])
def test_inter_o_union_uneven(bounding_box:np.array, full_overlap_cands:np.array):
"""test 1: uneven overlapping"""> print(inter_o_union(bounding_box, full_overlap_cands))
tests/test_losses.py:135:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
pred = array([[0, 1],
[0, 0]])
target = array([[[0, 1],
[0, 0]],
[[0, 1],
[0, 0]],
[[0, 1],
[0, 0]]])
def inter_o_union(pred:np.array, target:np.array):
"""calculates Intersection over Union Args: pred (np.array): The prediction(s) px array target (np.array): The target(s) px array Returns: float: the divison of sum of intersection px by union px"""
axis = None
if len(pred.shape) == 3 or len(target.shape) == 3: # More than 1 pred
axis = (1,2)
inter = np.sum(np.logical_and(pred, target), axis=axis)
union = np.sum(np.logical_or(pred, target), axis=axis)
print('inter: ', inter)
print('union: ', union)
>return union and inter / union or 0
E ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
boxsup_pytorch/losses.py:27: ValueError
-------------------------------------------------- Captured stdout call --------------------------------------------------
inter: [1 1 1]
union: [1 1 1]
---------- coverage: platform linux, python 3.10.4-final-0 -----------
Name Stmts Miss Branch BrPart Cover Missing
------------------------------------------------------------------------------
boxsup_pytorch/__init__.py 5 0 0 0 100%
boxsup_pytorch/boxsup_pytorch.py 0 0 0 0 100%
boxsup_pytorch/losses.py 12 0 2 0 100%
------------------------------------------------------------------------------
TOTAL 17 0 2 0 100%
Required test coverage of 100% reached. Total coverage: 100.00%
================================================ short test summary info =================================================
FAILED tests/test_losses.py::test_inter_o_union_uneven - ValueError: The truth value of an array with more than one ele...
============================================== 1 failed, 3 passed in 0.38s ===============================================
The issue happend as I started with pytest.fixtures decorators. I deleted a test which used yielding fixture. but the discover still tracked it. So deleted all caches in project directory but now the discovery fails.
The Output for python:
> ./.venv/bin/python ~/.vscode/extensions/ms-python.python-2022.6.0/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests
cwd: .
[ERROR 2022-4-6 23:20:19.95]: Error discovering pytest tests:
[n [Error]: �[1m=============================test session starts ==============================�[0m
platform linux -- Python 3.10.4, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- /run/media/makanu/Daten/GIT/boxsup_pytorch/.venv/bin/python
cachedir: .pytest_cache
rootdir: /run/media/makanu/Daten/GIT/boxsup_pytorch, configfile: pyproject.toml
plugins: cov-2.12.1
�[1mcollecting ... �[0mcollected 4 items
<Package tests>
tests namespace.
<Module test_boxsup_pytorch.py>
Test module for boxsup_pytorch.
<Function test_project_info>
Test __author__ value.
<Module test_losses.py>
Test Module for losses.
test scenario for overlapping_loss:
The loss formula:
$\Epsilon_o = {1\over N} \sum (1 - IoU(B,S)\delta (l_B, l_S)$
we test with following inputs:
Grid size is always 2x2
test 1:
- bounding_box: count 1, label 1
- candidates: count 3, label 1, no overlapping
expected result = 0
test 2:
- bounding_box: count 1, label 1
- candidates: count 1, label 1, no overlapping
- candidates: count 1, label 1, overlapping
- candidates: count 1, label 1, full overlapping
expected result = 1/2
test 3:
- bounding_box: count 1, label 1
- candidates: count 3, label 1, full overlapping
expected result = 1
test 4:
- bounding_box: count 1, label 1
- candidates: count 3, label 2, full overlapping
expected result = 0
<Function test_overlapping_1>test 1: no overlapping
<Function test_inter_o_union_even>test 1: even overlapping
<Function test_inter_o_union_uneven>test 1: uneven overlapping
---------- coverage: platform linux, python 3.10.4-final-0 -----------
Name Stmts Miss Branch BrPart Cover Missing
------------------------------------------------------------------------------
boxsup_pytorch/__init__.py 5 0 0 0 100%
boxsup_pytorch/boxsup_pytorch.py 0 0 0 0 100%
boxsup_pytorch/losses.py 12 9 2 0 21% 6, 18-27
------------------------------------------------------------------------------
TOTAL 17 9 2 0 42%
�[31m�[1mFAIL Required test coverage of 100% not reached. Total coverage: 42.11%
�[0m�[32m========================== �[32m4 tests collected�[0m�[32m in 0.41s�[0m�[32m ==========================�[0m
Traceback (most recent call last):
File "/home/makanu/.vscode/extensions/ms-python.python-2022.6.0/pythonFiles/testing_tools/run_adapter.py", line 22, in<module>
main(tool, cmd, subargs, toolargs)
File "/home/makanu/.vscode/extensions/ms-python.python-2022.6.0/pythonFiles/testing_tools/adapter/__main__.py", line 100, in main
parents, result = run(toolargs, **subargs)
File "/home/makanu/.vscode/extensions/ms-python.python-2022.6.0/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 44, in discover
raise Exception("pytest discovery failed (exit code {})".format(ec))
Exception: pytest discovery failed (exit code 1)
at ChildProcess.<anonymous> (/home/makanu/.vscode/extensions/ms-python.python-2022.6.0/out/client/extension.js:2:227541)
at Object.onceWrapper (node:events:510:26)
at ChildProcess.emit (node:events:390:28)
at maybeClose (node:internal/child_process:1064:16)
at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)]
The project is completely managed by poetry no conda involved.
I have a different repo with also build with poetry and there the tests run without any problem.
As soon as I import numpy inside anyone of my main package modules the extension breaks. I had no issue by import numpy into my test files.
numpy.__version__ = 1.22.3
I try to downgrade numpy until it is working again and share informations.
EDIT: Update: I managed to downgrade to 1.22.0 with not running into other dependency issues. I also could install the newest release 1.21.6. For all versions I rerun pytest discovery in the test section of vscode, all with the same result.
EDIT: A work around from this post solved the issue for the moment: https://stackoverflow.com/a/62197127/10985257
Since I run coverage via pytest, which caused the issue. A custom error msg with further information about the problem might caused by coverage would be nice for easier handling in the future. In my case the --no-cov was sufficient enough to handle the problem.
Activity
1st commentedon Feb 3, 2022
Hi Kim-Adeline Miguel (@kimadeline)
Please let me know if I can provide any useful details that may help to identify the issue. Thanks
1st commentedon Feb 3, 2022
What I may say, in my current project it's two apps in one codebase. Depending on the env variable (that is set in the
.envfile) - it may be run in one or another way.When I run the tests, I do it like this
APP_ENV=test APP_NAME=backend pytest backendand it runs only the tests for the part of the project. If I need to run other part of tests - I doAPP_ENV=test APP_NAME=frontend pytest frontendI did not find how make the test discovery that is used by VS Code to specify env variables.
All what I need from VS Code discovery - just to show me a list of all tests I have in the codebase. And also to have a "run" icon near each test function.
Currently I do run tests manually. I have defined in my
launch.jsonnext snippet. I change it to run individual test, if I do not need to run all tests in the file:It works to me fine. Only thing that I do often - opening the
launch.jsonfile and change the-kflag each time when I need to run other test. And it's annoying.Maybe it's a way to make Test Discovery works fine with pytest for such a project?
calebho commentedon Feb 4, 2022
Getting a similar error, however it seems like it's because the environment location is messed up
brianoflondon commentedon Feb 5, 2022
Perhaps I'm getting something similar which seems to stem from the discovery process trying to run my module itself with bad command line options. I'm really new to setting up a new project here so very unsure if this is my problem or similar to what others have reported here.
This bit puzzles me, why is discovery trying to run
podping-hivewatcher(my project) with pytest command line options.Running
pyteston the command line works fine.ianhelle commentedon Feb 5, 2022
I'm getting a very similar issue - pytest discovery not working in vscode while pytest from cmd line works fine.
From the code Python output I see:
Not sure if something in conda is able to interpret
~\.vscode\extens...as%userprofile%\.vscode\extens...(I'm running on Windows where "~" doesn't resolve to anything).If I try to copy that command (and replace the "~" with userprofile path), it fails as follows
(I've added -v flags to conda run to try to get more info):
I also tried removing the
get_output_via_markers.pycomponent of the command - still no success. But I noticed thatit seemed to be trying to execute pytest from the conda base environment rather than the current conda env.
This is the line I'm referring to - although not sure if this is a anything to do with the problem - it should be f:\anaconda\envs\msticpy\python.exe
The result is the same with or without the
-vflags.kimadeline commentedon Feb 8, 2022
Hi everyone, a couple of things here:
python=3.XXXargument, or the extension won't recognize it as a conda environment;.envfile.Anton Danylchenko (@1st) and Brian of London (@brianoflondon), please provide a sample repo that I can use to try and replicate your issues.
23 remaining items
1vecera commentedon May 5, 2022
Kim-Adeline Miguel (@kimadeline) #19069
pstjohn commentedon May 5, 2022
Mine is working again seemingly... I'll open up a new issue if it returns
Edit: ah ok, I think I've discovered the source of the error, will open a new issue.
Edit2: Opened as #19090
MaKaNu commentedon May 6, 2022
I struggle with a similar issue and I think it depends on a similar problem with printing to stderr.
At the moment one of my tests is failing and terminal output looks as following:
The issue happend as I started with pytest.fixtures decorators. I deleted a test which used yielding fixture. but the discover still tracked it. So deleted all caches in project directory but now the discovery fails.
The Output for python:
The project is completely managed by poetry no conda involved.
I have a different repo with also build with poetry and there the tests run without any problem.
MaKaNu commentedon May 7, 2022
I discovered the Problem but it is mind blowing:
As soon as I import
numpyinside anyone of my main package modules the extension breaks. I had no issue by importnumpyinto my test files.numpy.__version__ = 1.22.3I try to downgrade numpy until it is working again and share informations.
EDIT: Update: I managed to downgrade to 1.22.0 with not running into other dependency issues. I also could install the newest release 1.21.6. For all versions I rerun pytest discovery in the test section of vscode, all with the same result.
EDIT: A work around from this post solved the issue for the moment: https://stackoverflow.com/a/62197127/10985257
Since I run coverage via pytest, which caused the issue. A custom error msg with further information about the problem might caused by coverage would be nice for easier handling in the future. In my case the
--no-covwas sufficient enough to handle the problem.dariocurr commentedon Nov 21, 2022
I digged in this problem because I was using the
environment.ymlto set env variables and I discoverd the following:the problem semms to be to me that that
condaputs a message on thestderr:Then
vscode-pythoneverytime founds a new message on thestderr, forwards itIn this case, I guess is conda's fault since it writes to the
stderrthis WARNINGBtw, if vscode would activate the environment before, instead of running:
The problem would be fixed
eleanorjboyd commentedon Sep 6, 2023
I believe this is fixed on the rewrite per #18547 but please reopen if not. Thanks