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

Virtual environment is not fully activated when running tests in non-debug mode #22630

Open
KyleRAnderson opened this issue Dec 12, 2023 · 17 comments
Assignees
Labels
area-testing bug Issue identified by VS Code Team member as probable bug

Comments

@KyleRAnderson
Copy link

KyleRAnderson commented Dec 12, 2023

Type: Bug

Behaviour

Expected vs. Actual

Expected: When I run discovered pytests in non-debug mode via the "testing" tab, it behaves as though I ran pytest with the virtual environment configured for the workspace activated.

Actual: I have a particular test which uses subprocess.run to spawn another script which executes with the Python interpreter using a shebang (#!/usr/bin/env python3). When I run this test in my shell with the Python virtual environment active, the shebang executable resolves to the binary for the active environment, the desired behaviour. However, when I run the same test using the "testing" feature in VSCode, the executable is resolved to the system Python binary and the test fails as a consequence.

It is notable that this does not occur when I run the test in debug mode, there it works properly.

Steps to reproduce:

See the sample repository with steps to reproduce in the README: https://github.com/KyleRAnderson/vscode-python-bug-22630.

Diagnostic data

  • Python version (& distribution if applicable, e.g. Anaconda): 3.11.6
  • Type of virtual environment used (e.g. conda, venv, virtualenv, etc.): Venv
  • Value of the python.languageServer setting: Pylance
Output for Python in the Output panel (ViewOutput, change the drop-down the upper-right of the Output panel to Python)

XXX

User Settings


languageServer: "Pylance"

testing
• cwd: "<placeholder>"
• pytestArgs: "<placeholder>"
• pytestEnabled: true

Extension version: 2023.22.0
VS Code version: Code 1.85.0 (af28b32d7e553898b2a91af498b1fb666fdebe0c, 2023-12-06T20:48:09.019Z)
OS version: Windows_NT x64 10.0.19045
Modes:
Remote OS version: Linux x64 5.15.133.1-microsoft-standard-WSL2
Remote OS version: Linux x64 5.15.133.1-microsoft-standard-WSL2
Connection to 'wsl+ubuntu' could not be established

System Info
Item Value
CPUs 13th Gen Intel(R) Core(TM) i7-13700 (24 x 2112)
GPU Status 2d_canvas: enabled
canvas_oop_rasterization: enabled_on
direct_rendering_display_compositor: disabled_off_ok
gpu_compositing: enabled
multiple_raster_threads: enabled_on
opengl: enabled_on
rasterization: enabled
raw_draw: disabled_off_ok
video_decode: enabled
video_encode: enabled
vulkan: disabled_off
webgl: enabled
webgl2: enabled
webgpu: enabled
Load (avg) undefined
Memory (System) 15.76GB (2.03GB free)
Process Argv --crash-reporter-id aac21859-ebaf-495b-a1ef-a5146502f3a6
Screen Reader no
VM 0%
Item Value
Remote WSL: Ubuntu
OS Linux x64 5.15.133.1-microsoft-standard-WSL2
CPUs 13th Gen Intel(R) Core(TM) i7-13700 (24 x 2111)
Memory (System) 7.64GB (3.55GB free)
VM 0%
Item Value
Remote WSL: Ubuntu
OS Linux x64 5.15.133.1-microsoft-standard-WSL2
CPUs 13th Gen Intel(R) Core(TM) i7-13700 (24 x 2111)
Memory (System) 7.64GB (3.55GB free)
VM 0%

Connection to 'wsl+ubuntu' could not be established

A/B Experiments
vsliv368:30146709
vsreu685:30147344
python383cf:30185419
vspor879:30202332
vspor708:30202333
vspor363:30204092
vslsvsres303:30308271
vserr242cf:30382550
pythontb:30283811
vsjup518:30340749
pythonptprofiler:30281270
vshan820:30294714
vstes263:30335439
vscorecescf:30445987
vscod805cf:30301675
binariesv615:30325510
bridge0708:30335490
bridge0723:30353136
vsaa593:30376534
pythonvs932:30410667
py29gd2263:30899288
vsclangdf:30486550
c4g48928:30535728
dsvsc012cf:30540253
azure-dev_surveyone:30548225
2e4cg342:30602488
89544117:30613380
showlangstatbar:30737416
fixshowwlkth:30771522
showindicator:30805244
pythongtdpath:30769146
i26e3531:30792625
welcomedialog:30910333
pythonnosmt12:30797651
pythonidxpt:30866567
pythonnoceb:30805159
asynctok:30898717
dsvsc013:30795093
dsvsc014:30804076
dsvsc015:30845448
pythontestfixt:30902429
pyreplss1:30897532
pythonmypyd1:30879173
pythoncet0:30885854
2e7ec940:30885897
pythontbext0:30879054
accentitlementst:30887150
dsvsc016:30899300
dsvsc017:30899301
dsvsc018:30899302
aa_t_chat:30882232
dsvsc019:30917259

@github-actions github-actions bot added the triage-needed Needs assignment to the proper sub-team label Dec 12, 2023
@KyleRAnderson
Copy link
Author

Related to #4300, but that one seemingly covers debugging rather than regular runs.

@anthonykim1 anthonykim1 assigned karrtikr and eleanorjboyd and unassigned karrtikr Dec 12, 2023
@eleanorjboyd
Copy link
Member

Hi! Could you try switching from the python extension version 2023.22.0 to 2023.20.0 and see if that makes a difference? I am trying to figure out if this is related to: this issue or if its different. Thanks

@eleanorjboyd eleanorjboyd added the info-needed Issue requires more information from poster label Dec 12, 2023
@KyleRAnderson
Copy link
Author

Hi @eleanorjboyd, thank you for taking a look. I tried out version 2023.20.0 of the Python extension (installed that version, reloaded the window) and can confirm that I am still seeing this issue on that version.

@github-actions github-actions bot removed the info-needed Issue requires more information from poster label Dec 13, 2023
@eleanorjboyd
Copy link
Member

Thanks for checking, ill look into this further

@bonartm
Copy link

bonartm commented Jan 31, 2024

I could reproduce the bug (just note that you need to install pytest in the venv first).

I have a similar issue with unit tests that utilize a local spark cluster. The error message is different but the behavior of the bug is exactly the same. For my case I inspected the environment that is setup when debugging a test vs running a test.

It turned out that you can solve the issue by putting the current env into the PATH variable before running the subprocess (or before creating a local pyspark session as in my case):

import subprocess

def test_main():
    os.environ["PATH"] = os.getcwd() + "/.testvenv/bin:" + os.environ["PATH"]
    result = subprocess.run(("./main_program_under_test",))
    assert result.returncode == 0

Maybe this hint helps to find a general solution for this bug.

@ksamborn
Copy link

ksamborn commented Feb 18, 2024

Hi @eleanorjboyd -

I am experiencing the same problem. Maybe this additional diagnostic will help.

It seems that when executing tests via pytest, the PATH is not set properly as the Virtual Environment does not seem to be activated. By not properly, I mean the .venv/Scripts directory is not included in the PATH.

If the environment is activated, these directories are prepended to the PATH:

c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.1.10451007\pythonFiles\deactivate\powershell;C:\Users\sambornk\source\scratch\venv_activation_test\.venv\Scripts

and there are other environment variables as well, for example, VIRTUAL_ENV and VIRTUAL_ENV_PROMPT. And there are some other differences, like PYTHONPATH and PYTHONSTARTUP.

However, when running under pytest, the directories are missing and so are the additional environment variables.

When doing a normal "Run Python File", everything seems to be working correctly.

Below are two different outputs - one from running just a script and the other running pytest.

You can compare the two environments and how which("python") behaves.

I have highlighted a couple of key differences with "---->".

I also note a couple of other things:

  • the .env file is respected in both cases. Though there is different behavior: for pytest, a directory is added to PYTHONPATH and variable expansion is not done, but for a Python file there is no default PYTHONPATH and variable expansion is
  • Also, pytest does work fine as expected from the command line in an environment activated outside of VS.Code

For what it's worth, we are also working in a pyspark environment and what matters is the PYSPARK_PYTHON environment variable. This is normally set to simply "python" on Windows as this is the name of the executable as found in the PATH. However, if the PATH doesn't include the .venv/Scripts directory, the wrong version of the Python executable can be found incorrectly.

Is there anything I should be doing differently?

Thanks

pytest

with python.testing.pytestArgs includes -s

--

import sys, os
import shutil

def test_venv_activation():
    print()
    print(os.environ["PATH"])
    print(shutil.which("python"))
    
    for name, value in os.environ.items():
        print("{0}: {1}".format(name, value))

    assert 1 == 1

--

CLIENT: Server listening on port 62353...
Received JSON data in run script
Running pytest with args: ['-p', 'vscode_pytest', '--rootdir', 'c:\\Users\\sambornk\\source\\scratch\\venv_activation_test', '-s', 'c:\\Users\\sambornk\\source\\scratch\\venv_activation_test\\unit_test\\test_venv_activation.py::test_venv_activation']
============================= test session starts =============================
platform win32 -- Python 3.10.11, pytest-8.0.1, pluggy-1.4.0
rootdir: c:\Users\sambornk\source\scratch\venv_activation_test
collected 1 item

unit_test\test_venv_activation.py 
C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\dotnet\;C:\Users\sambornk\AppData\Local\Programs\Python\Launcher\;C:\Users\sambornk\AppData\Local\Programs\Python\Python39\Scripts\;C:\Users\sambornk\AppData\Local\Programs\Python\Python39\;C:\Users\sambornk\AppData\Local\Microsoft\WindowsApps;C:\Users\sambornk\AppData\Local\Programs\Git LFS;C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code\bin;
-----> C:\Users\sambornk\AppData\Local\Programs\Python\Python39\python.EXE
ALLUSERSPROFILE: C:\ProgramData
APPDATA: C:\Users\sambornk\AppData\Roaming
APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL: 1
CHROME_CRASHPAD_PIPE_NAME: \\.\pipe\crashpad_33960_JVVWQUYKIVJUKSZJ
COMMONPROGRAMFILES: C:\Program Files\Common Files
COMMONPROGRAMFILES(X86): C:\Program Files (x86)\Common Files
COMMONPROGRAMW6432: C:\Program Files\Common Files
COMPUTERNAME: XXX
COMSPEC: C:\WINDOWS\system32\cmd.exe
DEPLOYMENT.EXPIRATION.CHECK.ENABLED: false
DRIVERDATA: C:\Windows\System32\Drivers\DriverData
ELECTRON_RUN_AS_NODE: 1
GIT_LFS_PATH: C:\Users\sambornk\AppData\Local\Programs\Git LFS
HOMEDRIVE: C:
HOMEPATH: \Users\sambornk
LOCALAPPDATA: C:\Users\sambornk\AppData\Local
LOGONSERVER: \\XXX
NUMBER_OF_PROCESSORS: 8
ONEDRIVE: C:\Users\sambornk\OneDrive - XXX
ONEDRIVECOMMERCIAL: C:\Users\sambornk\OneDrive - XXX
ORIGINAL_XDG_CURRENT_DESKTOP: undefined
OS: Windows_NT
-----> PATH: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\dotnet\;C:\Users\sambornk\AppData\Local\Programs\Python\Launcher\;C:\Users\sambornk\AppData\Local\Programs\Python\Python39\Scripts\;C:\Users\sambornk\AppData\Local\Programs\Python\Python39\;C:\Users\sambornk\AppData\Local\Microsoft\WindowsApps;C:\Users\sambornk\AppData\Local\Programs\Git LFS;C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code\bin;
PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE: AMD64
PROCESSOR_IDENTIFIER: AMD64 Family 23 Model 96 Stepping 1, AuthenticAMD
PROCESSOR_LEVEL: 23
PROCESSOR_REVISION: 6001
PROGRAMDATA: C:\ProgramData
PROGRAMFILES: C:\Program Files
PROGRAMFILES(X86): C:\Program Files (x86)
PROGRAMW6432: C:\Program Files
PSMODULEPATH: C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
PUBLIC: C:\Users\Public
PYTHONIOENCODING: utf-8
-----> PYTHONPATH: c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.0.1\pythonFiles
PYTHONUNBUFFERED: 1
RUN_TEST_IDS_PORT: 62353
SESSIONNAME: Console
SYSTEMDRIVE: C:
SYSTEMROOT: C:\WINDOWS
TEMP: C:\Users\sambornk\AppData\Local\Temp
TEST_PORT: 62125
TEST_UUID: 173125bf-5fde-4d62-b3ab-82fb59a86377
TMP: C:\Users\sambornk\AppData\Local\Temp
USERDNSDOMAIN: XXX.LOCAL
USERDOMAIN: XXX
USERDOMAIN_ROAMINGPROFILE: XXX
USERNAME: sambornk
USERPROFILE: C:\Users\sambornk
VSCODE_AMD_ENTRYPOINT: vs/workbench/api/node/extensionHostProcess
VSCODE_CODE_CACHE_PATH: C:\Users\sambornk\AppData\Roaming\Code\CachedData\903b1e9d8990623e3d7da1df3d33db3e42d80eda
VSCODE_CRASH_REPORTER_PROCESS_TYPE: extensionHost
VSCODE_CWD: C:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code
VSCODE_HANDLES_UNCAUGHT_ERRORS: true
VSCODE_IPC_HOOK: \\.\pipe\d36c370b-1.86.2-main-sock
VSCODE_NLS_CONFIG: {"locale":"en-us","osLocale":"en-gb","availableLanguages":{},"_languagePackSupport":true}
VSCODE_PID: 33960
WINDIR: C:\WINDOWS
PYTEST_CURRENT_TEST: unit_test/test_venv_activation.py::test_venv_activation (call)
.
============================== 1 passed in 0.01s ==============================
Finished running tests!

Run Python Program

--

import sys, os
import shutil

print(sys.version)

print(os.defpath)

print(shutil.which("python"))

for name, value in os.environ.items():
    print("{0}: {1}".format(name, value))

--

PS C:\Users\sambornk\source\scratch\venv_activation_test> & c:/Users/sambornk/source/scratch/venv_activation_test/.venv/Scripts/python.exe c:/Users/sambornk/source/scratch/venv_activation_test/src/path.py
3.10.11 (tags/v3.10.11:7d4cc5a, Apr  5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)]
.;C:\bin
-----> C:\Users\sambornk\source\scratch\venv_activation_test\.venv\Scripts\python.EXE
ALLUSERSPROFILE: C:\ProgramData
APPDATA: C:\Users\sambornk\AppData\Roaming
CHROME_CRASHPAD_PIPE_NAME: \\.\pipe\crashpad_33960_JVVWQUYKIVJUKSZJ
COMMONPROGRAMFILES: C:\Program Files\Common Files
COMMONPROGRAMFILES(X86): C:\Program Files (x86)\Common Files
COMMONPROGRAMW6432: C:\Program Files\Common Files
COMPUTERNAME: XXX
COMSPEC: C:\WINDOWS\system32\cmd.exe
DEPLOYMENT.EXPIRATION.CHECK.ENABLED: false
DRIVERDATA: C:\Windows\System32\Drivers\DriverData
GIT_LFS_PATH: C:\Users\sambornk\AppData\Local\Programs\Git LFS
HOMEDRIVE: C:
HOMEPATH: \Users\sambornk
LOCALAPPDATA: C:\Users\sambornk\AppData\Local
LOGONSERVER: \\XXX
NUMBER_OF_PROCESSORS: 8
ONEDRIVE: C:\Users\sambornk\OneDrive - XXXX
ONEDRIVECOMMERCIAL: C:\Users\sambornk\OneDrive - XXX
ORIGINAL_XDG_CURRENT_DESKTOP: undefined
OS: Windows_NT
-----> PATH: c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.0.1\pythonFiles\deactivate\powershell;C:\Users\sambornk\source\scratch\venv_activation_test\.venv\Scripts;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\dotnet\;C:\Users\sambornk\AppData\Local\Programs\Python\Launcher\;C:\Users\sambornk\AppData\Local\Programs\Python\Python39\Scripts\;C:\Users\sambornk\AppData\Local\Programs\Python\Python39\;C:\Users\sambornk\AppData\Local\Microsoft\WindowsApps;C:\Users\sambornk\AppData\Local\Programs\Git LFS;C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code\bin;
PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL
PROCESSOR_ARCHITECTURE: AMD64
PROCESSOR_IDENTIFIER: AMD64 Family 23 Model 96 Stepping 1, AuthenticAMD
PROCESSOR_LEVEL: 23
PROCESSOR_REVISION: 6001
PROGRAMDATA: C:\ProgramData
PROGRAMFILES: C:\Program Files
PROGRAMFILES(X86): C:\Program Files (x86)
PROGRAMW6432: C:\Program Files
PSMODULEPATH: C:\Users\sambornk\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
PUBLIC: C:\Users\Public
SESSIONNAME: Console
SYSTEMDRIVE: C:
SYSTEMROOT: C:\WINDOWS
TEMP: C:\Users\sambornk\AppData\Local\Temp
TMP: C:\Users\sambornk\AppData\Local\Temp
USERDNSDOMAIN: XXX.LOCAL
USERDOMAIN: XXX
USERDOMAIN_ROAMINGPROFILE: XXX
USERNAME: sambornk
USERPROFILE: C:\Users\sambornk
WINDIR: C:\WINDOWS
PYTHONSTARTUP: c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.0.1\pythonFiles\pythonrc.py
TERM_PROGRAM: vscode
TERM_PROGRAM_VERSION: 1.86.2
LANG: en_US.UTF-8
COLORTERM: truecolor
GIT_ASKPASS: c:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\git\dist\askpass.sh
VSCODE_GIT_ASKPASS_NODE: C:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code\Code.exe
VSCODE_GIT_ASKPASS_EXTRA_ARGS:
VSCODE_GIT_ASKPASS_MAIN: c:\Users\sambornk\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\git\dist\askpass-main.js
VSCODE_GIT_IPC_HANDLE: \\.\pipe\vscode-git-b0e00517ad-sock
-----> VIRTUAL_ENV: C:\Users\sambornk\source\scratch\venv_activation_test\.venv
-----> VIRTUAL_ENV_PROMPT: .venv
VSCODE_INJECTION: 1
PS C:\Users\sambornk\source\scratch\venv_activation_test> 

@ksamborn
Copy link

Hi @eleanorjboyd -

I just figured out that it does work when debugging pytest tests.

Also, in case it helps, there's slightly different behaviour in how .env files are interpreted and preset variables are expanded.

Here's what I have in my .env file:

PYTHONPATH=${env:PYTHONPATH};./main/src
PYSPARK_PYTHON=python

Here's all four cases, along with how environment variables are set

Run Python File:

virtual environment is activated
referenced environment variables from .env are expanded

PATH: c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.0.1\pythonFiles\deactivate\powershell;C:\Users\sambornk\source\repos\xxx-lib\.venv\Scripts; <prepended>
PYSPARK_PYTHON: python
PYTHONPATH: ;./main/src
VIRTUAL_ENV: C:\Users\sambornk\source\repos\xxx-lib\.venv
VIRTUAL_ENV_PROMPT: .venv

Debug Python File:

virtual environment is activated
referenced environment variables from .env are not expanded

PATH: c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.0.1\pythonFiles\deactivate\powershell;C:\Users\sambornk\source\repos\xxx-lib\.venv\Scripts; <prepended>
PYSPARK_PYTHON: python
PYTHONPATH: ${env:PYTHONPATH};./main/src
VIRTUAL_ENV: C:\Users\sambornk\source\repos\xxx-lib\.venv
VIRTUAL_ENV_PROMPT: .venv

Run Test

virtual environment is not activated
referenced environment variables from .env are not expanded
an extra directory is prepeneded to PYTHONPATH

PATH: <nothing prepended>
PYSPARK_PYTHON: python
PYTHONPATH: c:\Users\sambornk\.vscode\extensions\ms-python.python-2024.0.1\pythonFiles;${env:PYTHONPATH};./main/src
VIRTUAL_ENV: <not set>
VIRTUAL_ENV_PROMPT:  <not set>

Debug Test

virtual environment is activated
PYTHONPATH seems to be set twice, once with expansion, once without

PATH: c:\Users\sambornk\source\repos\xxx-lib\.venv\Scripts; <prepended>
PYTHONPATH: ${env:PYTHONPATH};./main/src;;./main/src
PYSPARK_PYTHON: python
VIRTUAL_ENV: c:\Users\sambornk\source\repos\xxx-lib\.venv
VIRTUAL_ENV_PROMPT: (.venv) 

@kartikgupta-db
Copy link

kartikgupta-db commented Feb 27, 2024

Hi @binderjoe. This is blocking users of our Databricks Extension as well, because we install some databricks packages to their virtual envs, which we need activated properly for functions such as "Run Python File in Integrated Terminal", but with the Databricks features enabled.

Is it possible to prioritise this issue?

cc @fjakobs @saadansari-db @ilia-db

@brettcannon
Copy link
Member

With my Python core developer hat on, I want to say that assuming the virtual environment is activated is a bit dangerous as it's actually not necessary for the interpreter to work correctly. The shell scripts are considered a nice-to-have developer feature to make working in the shell easier and not meant to be required for code to function. As such, users can and do launch interpreters in virtual environments w/o ever activating them. And this isn't even covering the case of when people use a shell for which there aren't any activation scripts available.

If you need to know what Python interpreter you are using, sys.executable will always point to the running interpreter.

@github-actions github-actions bot added the info-needed Issue requires more information from poster label Feb 28, 2024
@kartikgupta-db
Copy link

@brettcannon agreed. But the current behaviour is, the terminal is showing that the environment is activated (the python extension changes the PS1 I believe?), but the environment is not actually activated.

Anyway, seems like a combination of vscode update (to 1.86.2) and the latest extension version (v2024.2.0) seems to have fixed the issue for me now atleast.

@ksamborn
Copy link

Hi Brett - just to add to this, it's not so much the running Python execution environment that needs the activation script, it's the PATH for things that are called by Python or in a terminal.

Two examples

  • interactively, if the PATH isn't right, you will get the wrong Python interpreter (or none at all) and possibly run the wrong pip and other commands
  • specifically when using Apache Spark and pyspark, there is an environment variable PYSPARK_PYTHON that depends on python being found in the path for a remote node. (Of course when using Databricks Connect, this isn't necessary)

Agreed on the other environment variables, but the PATH shouldn't be misleading

thanks for looking

@brettcannon
Copy link
Member

But the current behaviour is, the terminal is showing that the environment is activated (the python extension changes the PS1 I believe?), but the environment is not actually activated.

This actually has nothing to do w/ how we run tests. Terminal activation occurs using VS Code APIs and only when you open a terminal (and any prompt issues are due to your shell's design or how some start-up script overrides what our activation does because of how early it occurs). Testing normally occurs in a subprocess and not the terminal (hence the "non-debug mode" in the title of this issue). So the way to get an "activated" subprocess is to either execute using a shell subprocess (which is itself problematic as that requires we do shell escaping and that's really hard as escaping rules are not well documented, vary from shell to shell, etc.), or we calculate what environment variable changes are required and then apply those changes (which is costly for e.g. conda). Chances are we used to do the latter and missed that detail in the testing rewrite.

  • possibly run the wrong pip

Another FYI w/ my core dev hat on, I would advise against running pip directly, or at least use it's --python argument.

@ksamborn
Copy link

thanks, Brett. Just in case it helps diagnostically, I did notice that there are four different behaviors, which are different when running with and without debug. see above.

again, thanks for looking.

Kevin

@LKajan
Copy link

LKajan commented Mar 10, 2024

In my tests I test that templated files passes Ruff check after rendering. I used to have:

import subprocess

import pytest

def test_passes_ruff_check(rendered_project: Path):
    try:
        subprocess.check_output(["ruff", "check", "."], cwd=rendered_project)
    except subprocess.CalledProcessError as exc:
        pytest.fail(exc.output)

After the pythonTestAdapter got defaulted this is failing to FileNotFoundError of ruff executable. This is because the Scripts folder of the venv is not added to PATH. If pytest is run from terminal this works.

This can be "fixed" by changing the subprocess call to:

subprocess.check_output([sys.executable, "-m", "ruff", "check", "."], cwd=rendered_project)

@eleanorjboyd
Copy link
Member

@LKajan thank you for the clear steps- I will investigate.

Copy link

github-actions bot commented Jun 7, 2024

Because we have not heard back with the information we requested, we are closing this issue for now. If you are able to provide the info later on, then we will be happy to re-open this issue to pick up where we left off.

Happy Coding!

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 7, 2024
@eleanorjboyd eleanorjboyd reopened this Jun 7, 2024
Copy link

github-actions bot commented Jul 8, 2024

Because we have not heard back with the information we requested, we are closing this issue for now. If you are able to provide the info later on, then we will be happy to re-open this issue to pick up where we left off.

Happy Coding!

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jul 8, 2024
@eleanorjboyd eleanorjboyd reopened this Jul 8, 2024
@eleanorjboyd eleanorjboyd removed the info-needed Issue requires more information from poster label Jul 8, 2024
@eleanorjboyd eleanorjboyd removed the triage-needed Needs assignment to the proper sub-team label Dec 16, 2024
@karthiknadig karthiknadig added the bug Issue identified by VS Code Team member as probable bug label Dec 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-testing bug Issue identified by VS Code Team member as probable bug
Projects
None yet
Development

No branches or pull requests

9 participants