运行pytest时如何获取VSCode以正确激活conda?

时间:2019-07-30 15:15:08

标签: python visual-studio-code conda

在Windows 10上使用Anaconda和VSCode时,VSCode调试器在我运行/调试时会正确激活环境。但是当我使用测试模块时,它会失败。

这是一个示例设置:

我使用以下命令创建环境:conda create -n sqlite_test python=3.7.3

我的文件夹设置如下:

./src/
  sql.py
  test_sql.py

我打开一个新的VSCode窗口,然后打开src文件夹。

sql.py的源代码为:

import sqlite3
import os

def do_sql():
    db_path = os.path.join(os.environ['TEMP'], 'test.db')
    conn = sqlite3.connect(db_path)

    print("SQL code ran successfully")
    return True


do_sql()

test_sql.py的源代码为:

import pytest
from sql import do_sql

def test_do_sql():
    assert do_sql()

在VSCode中,我在sqlite_test Conda env中选择了python解释器。

如果我只运行sql.py,则不会出现任何错误,并且print语句将打印到控制台。

如果我使用VSCode从pytest运行测试(VSCode使用Pip将pytest安装到sqlite_test环境中),则会出现以下错误:

________________________ ERROR collecting test_sql.py _________________________
ImportError while importing test module 'c:\Users\UserName\Documents\src\tmp\sqllite\test_sql.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test_sql.py:2: in <module>
    from sql import do_sql
sql.py:1: in <module>
    import sqlite3
..\..\..\..\Anaconda3\envs\sqllite\lib\sqlite3\__init__.py:23: in <module>
    from sqlite3.dbapi2 import *
..\..\..\..\Anaconda3\envs\sqllite\lib\sqlite3\dbapi2.py:27: in <module>
    from _sqlite3 import *
E   ImportError: DLL load failed: The specified module could not be found.
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!

如果我从命令行运行pytest(激活了conda环境),则可以通过一个成功的测试:

>pytest
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\UserName\Documents\src\tmp\sqllite
collected 1 item

test_sql.py .                                                                                                    [100%]

============================================== 1 passed in 0.04 seconds ===============================================

3 个答案:

答案 0 :(得分:1)

原来这是一个已知的错误:https://github.com/microsoft/vscode-python/issues/4300

答案 1 :(得分:0)

对于Linux上的你们,我找到了可能的解决方案:

在项目目录中,创建.vscode/conda-pytest.sh

#!/usr/bin/env bash
. /path/to/miniconda3/etc/profile.d/conda.sh
conda activate my_env && pytest "$@"

,然后在项目的.vscode/settings.json中:

{
    "python.testing.pytestPath": "/path/to/project/.vscode/conda-pytest.sh"
}

请记住,将conda-pytest.sh设置为可执行文件。

对于Windows,我确定可以编写等效的批处理/ powershell脚本来代替conda-pytest.sh

答案 2 :(得分:0)

关注 GitHub 上的问题:https://github.com/microsoft/vscode-python/issues/10668

我使用远程 WSL2 解决 VS Code 的工作是引导测试执行以确保从正确激活的 conda 环境启动 VS Code 实例:

.vscode/test-wrapper.sh

#!/bin/bash
echo "PyTest Wrapper Starting Bootstrap"

current_env=`conda info | grep "active environment :" | awk '{print $4}'`
if [ "${current_env}" == "pyspark" ]; then
    pytest "$@"
else
    echo "PySpark is not the current environment. Launch vscode from an activated environment."
    echo "Track this issue here: https://github.com/microsoft/vscode-python/issues/10668"
    echo "Using a native terminal: "
    echo "  conda activate pyspark"
    echo "  code"
    echo 
fi

相关设置: .vscode/settings.json

{
  "python.testing.unittestEnabled": false,
  "python.testing.nosetestsEnabled": false,
  "python.testing.pytestEnabled": true,
  "python.testing.pytestPath": ".vscode/test-wrapper.sh",
  "python.terminal.activateEnvironment": true,
  "python.pythonPath": "${env:HOME}/anaconda3/envs/pyspark/bin/python",
  "python.linting.pylintPath": "/${env:HOME}/anaconda3/bin/pylint",
  "python.condaPath": "${env:HOME}/anaconda3/condabin/conda"
}

对于不知道的人,在您设置并重新加载窗口后,请确保选择正确的解释器,在我的情况下它称为 pyspark:cntrl + shift + p Python: Select Interpreter ~/anaconda3/envs/pyspark/bin/python

如果您怀疑自己没有加载正确的 conda 环境,您可以使用 test-wrapper.sh 通过 conda env list 调试问题

选择了错误的环境,因为代码不是从使用所需环境的本机终端会话启动的:

conda env list
# conda environments:
#
base                  *  /home/name/anaconda3
pyspark                  /home/name/anaconda3/envs/pyspark