Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pytest discovery fails if something is printed to stderr #18431

Closed
1st opened this issue Feb 3, 2022 · 31 comments
Closed

Pytest discovery fails if something is printed to stderr #18431

1st opened this issue Feb 3, 2022 · 31 comments
Assignees
Labels
area-testing bug Issue identified by VS Code Team member as probable bug

Comments

@1st
Copy link

1st commented Feb 3, 2022

Can I get any help with pytest discovery failure?

> /usr/local/bin/python ~/.vscode-server/extensions/ms-python.python-2022.0.1786462952/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear
cwd: .
[ERROR 2022-1-3 23:36:9.283]: Error discovering pytest tests:
 [r [Error]: Graceful shutdown completed in 0.000 seconds.

	at ChildProcess.<anonymous> (/root/.vscode-server/extensions/ms-python.python-2022.0.1786462952/out/client/extension.js:32:39235)
	at Object.onceWrapper (events.js:422:26)
	at ChildProcess.emit (events.js:315:20)
	at maybeClose (internal/child_process.js:1048:16)
	at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)]

Tried many different options with "python.testing.cwd" and "python.testing.pytestArgs" but without luck.

I used unit tests in the past and they work fine in VS Code.

Also I use VS Code with "Remote Container" and work inside the Docker container and run tests inside it.

Hope that you can solve this issue soon, because with pytest it doesn't work for me. And I have no clear vision why. Thanks.

@1st 1st added triage-needed Needs assignment to the proper sub-team feature-request Request for new features or functionality labels Feb 3, 2022
@1st
Copy link
Author

1st commented Feb 3, 2022

Hi @kimadeline

Please let me know if I can provide any useful details that may help to identify the issue. Thanks

@1st
Copy link
Author

1st commented 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 .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?

@1st 1st mentioned this issue Feb 4, 2022
22 tasks
@calebho
Copy link

calebho commented Feb 4, 2022

Getting a similar error, however it seems like it's because the environment location is messed up

> conda run -n onedevex-dev --no-capture-output python ~/.vscode-server/extensions/ms-python.python-2022.0.1786462952/pythonFiles/get_output_via_markers.py ~/.vscode-server/extensions/ms-python.python-2022.0.1786462952/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear .
cwd: .
[ERROR 2022-1-4 19:17:3.378]: Error discovering pytest tests:
 [r [Error]: 
EnvironmentLocationNotFound: Not a conda environment: /private/home/calebh/miniconda3/envs/onedevex-dev/envs/onedevex-dev


	at ChildProcess.<anonymous> (/private/home/calebh/.vscode-server/extensions/ms-python.python-2022.0.1786462952/out/client/extension.js:32:39235)
	at Object.onceWrapper (events.js:422:26)
	at ChildProcess.emit (events.js:315:20)
	at maybeClose (internal/child_process.js:1048:16)
	at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)

@brianoflondon
Copy link

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.

usage: hivewatcher [options]
hivewatcher: error: unrecognized arguments: discover pytest -- --rootdir /Users/gbishko/Documents/Python-iMac/PodcastIndex/podping-hivewatcher -s --cache-clear tests

Running pytest on the command line works fine.

> ~/Library/Caches/pypoetry/virtualenvs/podping-hivewatcher-YKYAFVom-py3.8/bin/python ~/.vscode/extensions/ms-python.python-2022.0.1786462952/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests
cwd: .
[ERROR 2022-1-5 14:29:48.180]: Error discovering pytest tests:
 [r [Error]: ============================= test session starts ==============================
platform darwin -- Python 3.8.9, pytest-5.4.3, py-1.11.0, pluggy-0.13.1
rootdir: /Users/gbishko/Documents/Python-iMac/PodcastIndex/podping-hivewatcher
usage: hivewatcher [options]
hivewatcher: error: unrecognized arguments: discover pytest -- --rootdir /Users/gbishko/Documents/Python-iMac/PodcastIndex/podping-hivewatcher -s --cache-clear tests
collected 0 items / 1 error

==================================== ERRORS ====================================
________ ERROR collecting tests/integration/test_podping_hivewatcher.py ________
tests/integration/test_podping_hivewatcher.py:2: in <module>
    from podping_hivewatcher.hivewatcher import allowed_op_id, get_allowed_accounts
src/podping_hivewatcher/hivewatcher.py:10: in <module>
    from podping_hivewatcher.config import Config
src/podping_hivewatcher/config/__init__.py:164: in <module>
    args = my_parser.parse_args()
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/argparse.py:1771: in parse_args
    self.error(msg % ' '.join(argv))
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/argparse.py:2521: in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/argparse.py:2508: in exit
    _sys.exit(status)
E   SystemExit: 2
=========================== short test summary info ============================
ERROR tests/integration/test_podping_hivewatcher.py - SystemExit: 2
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.46s ===============================

Traceback (most recent call last):
  File "/Users/gbishko/.vscode/extensions/ms-python.python-2022.0.1786462952/pythonFiles/testing_tools/run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "/Users/gbishko/.vscode/extensions/ms-python.python-2022.0.1786462952/pythonFiles/testing_tools/adapter/__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "/Users/gbishko/.vscode/extensions/ms-python.python-2022.0.1786462952/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 2)

	at ChildProcess.<anonymous> (/Users/gbishko/.vscode/extensions/ms-python.python-2022.0.1786462952/out/client/extension.js:32:39235)
	at Object.onceWrapper (events.js:422:26)
	at ChildProcess.emit (events.js:315:20)
	at maybeClose (internal/child_process.js:1048:16)
	at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)]

@ianhelle
Copy link

ianhelle commented 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:

> f:\anaconda\condabin\conda.bat run -p F:\anaconda\envs\msticpy --no-capture-output python ~\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\get_output_via_markers.py ~\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests

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):

(msticpy) E:\src\microsoft\msticpy>f:\anaconda\condabin\conda.bat run -v -v -v -p F:\anaconda\envs\msticpy --no-capture-output python %userprofile%\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\get_output_via_markers.py %userprofile%\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests 
DEBUG conda.gateways.logging:set_verbosity(231): verbosity set to 3
DEBUG conda.gateways.subprocess:subprocess_call(71): executing>> C:\WINDOWS\system32\cmd.exe /d /c F:\anaconda\envs\msticpy\.tmpzij4q0j9.bat
>>>PYTHON-EXEC-OUTPUT
usage: C:\Users\Ian\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\testing_tools\run_adapter.py [-h] {discover} ...
C:\Users\Ian\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\testing_tools\run_adapter.py: error: argument cmd: invalid choice: 'C:\\Users\\Ian\\.vscode\\extensions\\ms-python.python-2022.1.1779589815-dev\\pythonFiles\\testing_tools\\run_adapter.py' (choose from 'discover')
TRACE conda.gateways.subprocess:subprocess_call(108): $ C:\WINDOWS\system32\cmd.exe /d /c F:\anaconda\envs\msticpy\.tmpzij4q0j9.bat
==> cwd: E:\src\microsoft\msticpy <==
==> exit code: 2 <==
==> stdout <==
None
==> stderr <==
None

ERROR conda.cli.main_run:execute(33): Subprocess for 'conda run ['python', 'C:\\Users\\Ian\\.vscode\\extensions\\ms-python.python-2022.1.1779589815-dev\\pythonFiles\\get_output_via_markers.py', 'C:\\Users\\Ian\\.vscode\\extensions\\ms-python.python-2022.1.1779589815-dev\\pythonFiles\\testing_tools\\run_adapter.py', 'discover', 'pytest', '--', '--rootdir', '.', '-s', '--cache-clear', 'tests']' command failed.  (See above for error)
TRACE conda.gateways.disk.delete:rm_rf(165): rm_rf F:\anaconda\envs\msticpy\.tmpzij4q0j9.bat

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.

(msticpy) E:\src\microsoft\msticpy>f:\anaconda\condabin\conda.bat run -v -v -v -p F:\anaconda\envs\msticpy --no-capture-output python %userprofile%\.vscode\extensions\ms-python.python-2022.1.1779589815-dev\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests
DEBUG conda.gateways.logging:set_verbosity(231): verbosity set to 3
DEBUG conda.gateways.subprocess:subprocess_call(71): executing>> C:\WINDOWS\system32\cmd.exe /d /c F:\anaconda\envs\msticpy\.tmp39rluiwl.bat
equivalent command: f:\anaconda\python.exe -m pytest --collect-only --rootdir . -s --cache-clear tests
TRACE conda.gateways.subprocess:subprocess_call(108): $ C:\WINDOWS\system32\cmd.exe /d /c F:\anaconda\envs\msticpy\.tmp39rluiwl.bat
==> cwd: E:\src\microsoft\msticpy <==
==> exit code: 120 <==
==> stdout <==
None
==> stderr <==
None

ERROR conda.cli.main_run:execute(33): Subprocess for 'conda run ['python', 'C:\\Users\\Ian\\.vscode\\extensions\\ms-python.python-2022.1.1779589815-dev\\pythonFiles\\testing_tools\\run_adapter.py', 'discover', 'pytest', '--', '--rootdir', '.', '-s', '--cache-clear', 'tests']' command failed.  (See above for error)
TRACE conda.gateways.disk.delete:rm_rf(165): rm_rf F:\anaconda\envs\msticpy\.tmp39rluiwl.bat

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

equivalent command: f:\anaconda\python.exe -m pytest --collect-only --rootdir . -s --cache-clear tests

The result is the same with or without the -v flags.

@karthiknadig karthiknadig added area-testing bug Issue identified by VS Code Team member as probable bug triage and removed feature-request Request for new features or functionality triage-needed Needs assignment to the proper sub-team labels Feb 7, 2022
@kimadeline
Copy link

Hi everyone, a couple of things here:

  • 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.

@1st and @brianoflondon, please provide a sample repo that I can use to try and replicate your issues.

@kimadeline kimadeline added the info-needed Issue requires more information from poster label Feb 8, 2022
@brianoflondon
Copy link

@1st and @brianoflondon, please provide a sample repo that I can use to try and replicate your issues.

Thanks for taking a look @kimadeline !

This is the repo I've got which I can't get discovery working on. It was set up with Poetry and I think I can trace the problem to the point where I ran poetry install and it installed this project within itself (does that make sense?). My problem distinctly comes from the discovery process trying to run hivewatcher but with no command line options and not liking the result.

Installing the current project: podping-hivewatcher (1.0.0)

I'm somewhat new to packaging and trying to publish on Pypi.

https://github.com/brianoflondon/podping-hivewatcher

@pstjohn
Copy link

pstjohn commented Feb 12, 2022

I'm running into issues that might be related to the conda run problems. This is on a mac with mambaforge's anaconda; conda version 4.11.

I created the python environment with the following yaml file (conda env create -f environment.yml)

name: graphenv
channels:
  - conda-forge
  - defaults
dependencies:
  - python=3.9
  - pytest

Running pytest . from the vscode terminal runs fine, but the pytest discovery suite gives this odd error message:

> . ~/mambaforge/bin/activate && conda activate graphenv && echo 'e8b39361-0157-4923-80e1-22d70d46dee6' && python ~/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/printEnvVariables.py
> ~/mambaforge/condabin/conda run -n graphenv --no-capture-output --live-stream python ~/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear
cwd: .
[ERROR 2022-1-12 6:16:4.493]: Error discovering pytest tests:
 [r [Error]: Traceback (most recent call last):
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/get_output_via_markers.py", line 26, in <module>
    runpy.run_path(module, run_name="__main__")
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 252, in run_path
    return _run_module_code(code, init_globals, run_name, path_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/testing_tools/run_adapter.py", line 17, in <module>
    from testing_tools.adapter.__main__ import parse_args, main
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/testing_tools/adapter/__main__.py", line 9, in <module>
    from . import pytest, report
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/testing_tools/adapter/pytest/__init__.py", line 7, in <module>
    from ._discovery import discover
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 8, in <module>
    import pytest
ImportError: No module named pytest

I have no idea why it's pulling files from /System/Library/Frameworks/Python.framework/Versions/2.7, it should be looking at the conda environment in ~/mambaforge/envs/graphenv.

This is with 2022.0.1814523869

@kimadeline
Copy link

Sorry for the delay!

@brianoflondon I cloned your repo, initialized a virtual environment with poetry install and tried running the tests, and they error out with the following message:

============================= test session starts ==============================
platform darwin -- Python 3.9.0, pytest-7.0.0, pluggy-1.0.0
rootdir: /Users/kimiguel/Documents/Sandbox/podping-hivewatcher, configfile: pyproject.toml, testpaths: tests
usage: hivewatcher [options]
hivewatcher: error: unrecognized arguments: discover pytest -- --rootdir . -s --cache-clear tests
collected 0 items / 1 error

Does hivewatcher try to parse arguments? If yes, is there a way for it to ignore anything unrelated to it? The extension executes the following command to discover tests: path/to/poetry/virtualenvs/podping-hivewatcher-AeSuBiZj-py3.9/bin/python ~/.vscode/extensions/ms-python.python-2022.0.1814523869/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests, so hivewatcher should ignore all of it.

@pstjohn when you created your virtual environment, does it appear in the list of available interpreters when you run the Python: Select Interpreter command?

@pstjohn
Copy link

pstjohn commented Mar 2, 2022

It does, and that's actually the currently selected interpreter as well; if that's relevant:
Screen Shot 2022-03-02 at 4 04 56 PM

@kimadeline
Copy link

Do you have a list repro steps (and ideally, a sample repo as well) I could use to try and replicate this issue?

@pstjohn
Copy link

pstjohn commented Mar 4, 2022

I don't expect it's a repo issue -- I'm using zsh as my default mac shell.

I was able to get this to work by

  1. running conda init bash
  2. changing my default system shell to /bin/bash

Oddly the command
> . ~/mambaforge/bin/activate && conda activate graphenv && echo 'e8b39361-0157-4923-80e1-22d70d46dee6' && python ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/printEnvVariables.py

worked in either a zsh terminal outside of vscode, and in the zsh terminal inside vscode. It was only during pytest discovery that the python must have pointed to my default system python and failed.

@pstjohn
Copy link

pstjohn commented Mar 4, 2022

ok, looks like it might have been because I specified a conda executable as ~/mambaforge/condabin/conda. Clearing that setting ("python.condaPath": "") seems to let this work with zsh as my default shell

Apparently its broken again. Seems related to microsoft/vscode#70248, since when I open a new terminal, it doesn't set the python path correctly

Screen Shot 2022-03-07 at 11 27 52 AM

Edit, it seems like even if I set up my vscode terminal such that python points to the correct location

    "terminal.integrated.inheritEnv": false,
    "terminal.integrated.env.osx": {"PATH": ""},
    "terminal.integrated.defaultProfile.osx": "bash"

and the command run by the testing framework works in the integrated terminal;

(graphenv) pstjohn-34731s:graph-env pstjohn$ conda run -n graphenv --no-capture-output --live-stream python ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear
>>>PYTHON-EXEC-OUTPUT
[{"rootid": ".", "root": "/Users/pstjohn/Packages/graph-env", "parents": [{"id": "./test", "kind": "folder", "name": "test", "parentid": ".", "relpath": "./test"}, {"id": "./test/test_hallway.py", "kind": "file", "name": "test_hallway.py", "parentid": "./test", "relpath": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_ppo", "kind": "function", "name": "test_ppo", "parentid": "./test/test_hallway.py"}], "tests": [{"id": "./test/test_hallway.py::test_observation_space", "name": "test_observation_space", "source": "./test/test_hallway.py:21", "markers": [], "parentid": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_next_actions", "name": "test_next_actions", "source": "./test/test_hallway.py:25", "markers": [], "parentid": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_terminal", "name": "test_terminal", "source": "./test/test_hallway.py:33", "markers": [], "parentid": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_reward", "name": "test_reward", "source": "./test/test_hallway.py:39", "markers": [], "parentid": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_graphenv_reset", "name": "test_graphenv_reset", "source": "./test/test_hallway.py:44", "markers": [], "parentid": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_graphenv_step", "name": "test_graphenv_step", "source": "./test/test_hallway.py:50", "markers": [], "parentid": "./test/test_hallway.py"}, {"id": "./test/test_hallway.py::test_ppo[model_classes0]", "name": "test_ppo[model_classes0]", "source": "./test/test_hallway.py:64", "markers": [], "parentid": "./test/test_hallway.py::test_ppo"}, {"id": "./test/test_hallway.py::test_ppo[model_classes1]", "name": "test_ppo[model_classes1]", "source": "./test/test_hallway.py:64", "markers": [], "parentid": "./test/test_hallway.py::test_ppo"}]}]
<<<PYTHON-EXEC-OUTPUT

it still fails in the pytest discovery, clearly picking up the system's python binaries

> conda run -n graphenv --no-capture-output --live-stream python ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear
cwd: .
[ERROR 2022-2-7 16:43:23.272]: Error discovering pytest tests:
 [r [Error]: Traceback (most recent call last):
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/get_output_via_markers.py", line 26, in <module>
    runpy.run_path(module, run_name="__main__")
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 252, in run_path
    return _run_module_code(code, init_globals, run_name, path_name)

@ianhelle
Copy link

ianhelle commented Mar 16, 2022

Is there a way of forcing vscode to operate in the conda environment for pytest discovery?
My experience is exactly the same as @pstjohn. I.e. the extensions is running runpy.py from the base conda environment rather than the conda environment that is activated.
I always start vscode from a terminal where my conda env is activated. I've set the workspace interpreter path explicitly to the python env version.
This has been broken now for weeks.

[ERROR 2022-2-16 15:8:25.952]: Error discovering pytest tests:
 [r [Error]: Traceback (most recent call last):
  File "c:\Users\Ian\.vscode\extensions\ms-python.python-2022.3.10741003\pythonFiles\get_output_via_markers.py", line 26, in <module>
    runpy.run_path(module, run_name="__main__")
  File "f:\anaconda\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "f:\anaconda\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  ....
  File "c:\Users\Ian\.vscode\extensions\ms-python.python-2022.3.10741003\pythonFiles\testing_tools\adapter\pytest\_discovery.py", line 8, in <module>
    import pytest
ModuleNotFoundError: No module named 'pytest'

VS code insiders works though - even not started explicitly from a conda activated terminal

> F:\anaconda\Scripts\conda.exe run -n msticpy --no-capture-output --live-stream python ~\.vscode-insiders\extensions\ms-python.python-2022.3.1931132634-dev\pythonFiles\get_output_via_markers.py ~\.vscode-insiders\extensions\ms-python.python-2022.3.1931132634-dev\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests
cwd: .

@JimBiardClimateAI
Copy link

Similar problem, but it appears that I don't have any of the errors mentioned by others. I am trying to move to VSCODE from PyCharm. So far I'm unimpressed. I have a project where my code is in a folder named 'api' and my tests are in a folder named 'tests'. Pytest runs in PyCharm with no trouble. Pytest runs on the command line with no trouble. PyTest discovery in VSCODE produces the output below.

I'm running on a Mac M1 box with macOS 12.2.

> . ~/opt/miniconda3/bin/activate && conda activate UnifiedWeatherAnalysis && echo '<redacted>' && python ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/printEnvVariables.py
> conda run -n UnifiedWeatherAnalysis --no-capture-output --live-stream python ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.2.1924087327/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear -n auto tests
cwd: .
[ERROR 2022-2-25 17:35:5.94]: Error discovering pytest tests:
 r [Error]: Waiting up to 5 seconds.
Sent all pending logs.

    at ChildProcess.<anonymous> (/Users/jimbiard/.vscode/extensions/ms-python.python-2022.2.1924087327/out/client/extension.js:32:39235)
    at Object.onceWrapper (events.js:422:26)
    at ChildProcess.emit (events.js:315:20)
    at maybeClose (internal/child_process.js:1048:16)
    at Socket.<anonymous> (internal/child_process.js:439:11)
    at Socket.emit (events.js:315:20)
    at Pipe.<anonymous> (net.js:673:12)

@bobwalker99
Copy link

There’s a fundamental issue here in that the extension is always trying to do full discovery before anything is usable/runnable.

In large repositories this is impractical, unhelpful, time-consuming, and unnecessary.
I appreciate this might be due to our repository structure choices, but in a repository such as ours with a 10-year history and many, many sub-folders this is hugely impractical and almost unusable.

With e.g. Eclipse and PyDev I can always select a test file or folder and “just run it” regardless of the state of the rest of the repo. This doesn’t seem that unreasonable, or that unachievable. With a large repo, I largely don’t care about the state of the rest of the repo, I just want to run the test/tests I’m currently working on.

Ultimately, if the the file I’m viewing is called test.py and the function I’m looking at is called test I should be able to run it, without caring about anything else, shouldn’t I?

@1vecera
Copy link

1vecera commented Mar 29, 2022

I am still running into @calebho 's issue. I'm not clear how to resolve this.

image
Python v2022.3.1931132634-dev
Can any1 please assist?

@calebho
Copy link

calebho commented Mar 29, 2022

@1vecera For now I "fixed" the issue by reverting to v2021.12.1559732655

@kimadeline
Copy link

Hi everyone

Is there a way of forcing vscode to operate in the conda environment for pytest discovery?

We recently made some changes to how we discover and use conda environments, please take the newest release of the extension for a spin and report back! If it still doesn't work, please include a sample repo and repro steps that I could use to replicate the issue you're facing.

There’s a fundamental issue here in that the extension is always trying to do full discovery before anything is usable/runnable.

You can try specifying a specific folder in python.testing.pytestArgs in the same way as you'd run pytest test discovery in the terminal. Using python.testing.pytestArgs should be similar to a pytest command, so if there's a way to run the behaviour you're describing in pytest, it should be possible to replicate it with the python.testing.pytestArgs setting. If it doesn't work, feel free to open a feature request as well!

@pstjohn
Copy link

pstjohn commented Apr 2, 2022

Seems to be working for me as of v2022.4.0 of the python extension!

Edit, seems to be broken again for me. Downgrading to v2022.4.0 doesn't seem to solve the problem. Again, it seems to have to do with how $PATH is set in the integrated terminal.
Setting

    "terminal.integrated.inheritEnv": false,
    "terminal.integrated.env.osx": {
        "PATH": ""
    }

seems to solve it for me

Edit2: well, that did solve it for a few hours, but now it's back to not working with the same error...

@1st
Copy link
Author

1st commented Apr 2, 2022

I tried with the lates version, it's the same issue.

Note: I run my VS Code in the Dev Container (Docker container).

When I run this:

pytest --rootdir . -s --cache-clear --no-cov --collect-only

it shows me successful result:

================================================== 1422 tests collected in 2.99s ==================================================

When VS Code runs the test discovery, it fails (taken from the Python output panel):

> /usr/local/bin/python ~/.vscode-server/extensions/ms-python.python-2022.4.0/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear --no-cov --collect-only
cwd: .
[ERROR 2022-3-2 15:55:31.771]: Error discovering pytest tests:
 [r [Error]: Graceful shutdown completed in 0.000 seconds.

	at ChildProcess.<anonymous> (/root/.vscode-server/extensions/ms-python.python-2022.4.0/out/client/extension.js:32:38969)
	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)]

Tried to run the command manually, and it printer the correct list of objects output:

/usr/local/bin/python ~/.vscode-server/extensions/ms-python.python-2022.4.0/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear --no-cov --collect-only

[
  ....
  {"id": "./my_app/tests/test_settings.py::test_one", "name": "test_one", "source": "./my_app/tests/test_settings.py:4", "markers": [], "parentid": "./my_app/tests/test_settings.py"}]}
]
Graceful shutdown completed in 0.000 seconds.

Also I need to pass env variables to this test discovery process. Because depending on the env variable, my app is run in the "Testing" mode or a normal app mode. Didn't find how to pass the env variable to the test discovery process.

@1st
Copy link
Author

1st commented Apr 21, 2022

Finally we found the root of the issue.

Our project has such a file conftest.py in the root directory that contains next code:

from api_b2c2 import configure_settings
pytest_plugins = (
    "common.tests.plugin",
)
configure_settings()

And also this file signals.py:

import atexit
import sys

def shutdown():
     # Some code is omitted from this function. But interestingly - the next piece of code,
     # that prevented VS Code from picking the tests tree during discovery (it writes to the STD ERR)
     print(
         f"Graceful shutdown completed.",
         file=sys.stderr,
     )

atexit.register(shutdown)

When the print to sys.stderr was removed, test discovery started to work like it should.

Please take this edge case from our experience into consideration about how to improve the VS Code to handle such cases, or at least show some helpful debug information about why test discovery can't be done. It may help other projects as well.

@pstjohn
Copy link

pstjohn commented Apr 21, 2022

If I add

assert sys.version_info[0] == 3, "Version: " + sys.version

at https://github.com/microsoft/vscode-python/blob/main/pythonFiles/get_output_via_markers.py#L7;

I get an assertion error when I try to do pytest discovery, since it's clearly using the system's python 2.7:

> conda run -n graphenv --no-capture-output --live-stream python ~/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear tests
cwd: .
[ERROR 2022-3-21 8:26:10.78]: Error discovering pytest tests:
 [r [Error]: Traceback (most recent call last):
  File "/Users/pstjohn/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/get_output_via_markers.py", line 7, in <module>
    assert sys.version_info[0] == 3, "Version: " + sys.version
AssertionError: Version: 2.7.16 (default, Mar 25 2021, 03:11:28) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc-
ERROR conda.cli.main_run:execute(41): `conda run python /Users/pstjohn/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/get_output_via_markers.py /Users/pstjohn/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir /Users/pstjohn/Packages/graph-env -s --cache-clear tests` failed. (See above for error)

interestingly I can run flake8 no problem with that assert statement in place,

> conda run -n graphenv --no-capture-output --live-stream python ~/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/linter.py -p flake8 ~/mambaforge/bin/flake8 --max-line-length=88 --extend-ignore=E203 ./docs/examples/test.py
cwd: .
##########Linting Output - flake8##########

@1vecera
Copy link

1vecera commented Apr 22, 2022

Still stuck on the @calebho issue:
[ERROR 2022-3-22 11:20:49.318]: Error discovering pytest tests:
[n [Error]:
EnvironmentLocationNotFound: Not a conda environment: D:\ProgramData\Anaconda3\envs\swp10\envs\swp10

at ChildProcess.<anonymous> (c:\Users\vadm_daniel1\.vscode\extensions\ms-python.python-2022.5.11111003\out\client\extension.js:2:228488)
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)]

Can someone suggest a version to revert to?
ms-python.python-2022.5.1111100

Version: 1.66.2 (system setup)
Commit: dfd34e8260c270da74b5c2d86d61aee4b6d56977
Date: 2022-04-11T07:46:01.075Z
Electron: 17.2.0
Chromium: 98.0.4758.109
Node.js: 16.13.0
V8: 9.8.177.11-electron.0
OS: Windows_NT x64 10.0.17763

Best

Daniel

@kimadeline kimadeline changed the title Pytest discovery is broken Pytest discovery fails if something is printed to stderr May 3, 2022
@kimadeline kimadeline removed the info-needed Issue requires more information from poster label May 3, 2022
@kimadeline
Copy link

Update:

  • The original issue reported by @1st (discovery failing if something is printed to stderr) should be addressed as part of the refactoring work done in Rewrite testing adapter #17242.
  • @pstjohn and @1vecera, it looks like your discovery problems have a different root cause, please open separate issues with a sample repo, your interpreter info, and repro steps to make it easier for us to track and debug them. Feel free to reference this issue as well.
  • Anybody else, same as above: if your discovery problems are not caused by print statements, please open a separate issue.

Thanks!

@1vecera
Copy link

1vecera commented May 5, 2022

@kimadeline #19069

@pstjohn
Copy link

pstjohn commented 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
Copy link

MaKaNu commented 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:

❯ 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.

@MaKaNu
Copy link

MaKaNu commented May 7, 2022

I discovered the Problem but it is mind blowing:

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.

@dariocurr
Copy link

dariocurr commented Nov 21, 2022

I digged in this problem because I was using the environment.yml to set env variables and I discoverd the following:

the problem semms to be to me that that conda puts a message on the stderr:

Then vscode-python everytime founds a new message on the stderr, forwards it

In this case, I guess is conda's fault since it writes to the stderr this WARNING

Btw, if vscode would activate the environment before, instead of running:

conda run -n env-name --no-capture-output python ~/.vscode/extensions/ms-python.python-2022.18.2/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.18.2/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear

The problem would be fixed

@eleanorjboyd
Copy link
Member

I believe this is fixed on the rewrite per #18547 but please reopen if not. Thanks

@github-actions github-actions bot removed the needs PR Ready to be worked on label Sep 6, 2023
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 7, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-testing bug Issue identified by VS Code Team member as probable bug
Projects
None yet
Development

No branches or pull requests