python - 如何使用 Docker 容器作为 virtualenv 从 IDE 运行 Python 测试?

标签 python docker visual-studio-code pycharm tdd

别误会我的意思,virtualenv(或 pyenv)是一个很棒的工具,虚拟环境的整个概念是对开发人员环境的巨大改进,减轻了整个 Snowflake Server反模式。

但如今 Docker 容器无处不在(有充分的理由),让应用程序在容器上运行,同时还要在 IDE 中设置本地虚拟环境来运行测试等,这感觉很奇怪。

我想知道是否有办法利用 Docker 容器来实现此目的?

最佳答案

摘要

是的,有一种方法可以实现这一目标。通过配置远程 Python 解释器和“sidecar”Docker 容器。

这个 Docker 容器将具有:

  • 安装到源代码的卷(以下称为/code)
  • SSH 设置
  • 为 root:password 凭据启用 SSH,并允许 root 用户登录

准备好 sidecar 容器

这里的想法是复制应用程序的容器并向其添加 SSH 功能。我们将使用 docker-compose 来实现这一点:

docker-compose.yml:

version: '3.3'

services:
  dev:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - 127.0.0.1:9922:22
    volumes:
      - .:/code/
    environment:
      DEV: 'True'
    env_file: local.env

Dockerfile.dev

FROM python:3.7
ENV PYTHONUNBUFFERED 1

WORKDIR /code

# Copying the requirements, this is needed because at this point the volume isn't mounted yet
COPY requirements.txt /code/

# Installing requirements, if you don't use this, you should.
# More info: https://pip.pypa.io/en/stable/user_guide/
RUN pip install -r requirements.txt

# Similar to the above, but with just the development-specific requirements
COPY requirements-dev.txt /code/
RUN pip install -r requirements-dev.txt

# Setup SSH with secure root login
RUN apt-get update \
 && apt-get install -y openssh-server netcat \
 && mkdir /var/run/sshd \
 && echo 'root:password' | chpasswd \
 && sed -i 's/\#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

设置 PyCharm 专业版

  1. 首选项 (CMD + ,) > 项目设置 > 项目解释器
  2. 点击“Project Interpreter”下拉菜单旁边的齿轮图标 > 添加
  3. 选择“SSH解释器” > 主机:localhost,端口:9922,用户名:root > 密码:password > 解释器:/usr/local/bin/python,同步文件夹:项目根目录 ->/code,禁用“自动上传” ...”
  4. 确认更改并等待 PyCharm 更新索引

设置 Visual Studio Code

  1. 安装Python扩展名
  2. 安装Remote - Containers扩展名
  3. 打开 Command Pallet 并输入 Remote-Containers,然后选择 Attach to Running Container... 并选择正在运行的 docker 容器 VS Code 将重新启动并重新加载
  4. 在资源管理器侧边栏上,点击“打开文件夹”按钮,然后输入/code(这将从远程容器加载)
  5. 在“扩展”侧边栏上,选择 Python 扩展并将其安装到容器上
  6. 当提示使用哪个解释器时,选择/usr/local/bin/python
  7. 打开 Command Pallette 并输入 Python:配置测试,然后选择单元测试框架

TDD 支持

现在您可以直接从 IDE 运行测试,使用它来尝试测试驱动开发!它的关键点之一是快速反馈循环,并且不必等待完整的测试套件完成执行只是为了看看您的新测试是否通过,这真是太棒了!只需编写并立即运行即可!

引用

这个答案的内容也可以在这个GIST中找到。 .

关于python - 如何使用 Docker 容器作为 virtualenv 从 IDE 运行 Python 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58855616/

相关文章:

git - 如何删除 GitHub 上已删除但仍显示在 VS Code 中的分支?

debugging - vscode : Unable to start debugging . miDebuggerPath 的值无效

python - QListWidget 和多选

python - doctest 调用哪些函数的顺序?

Python:\n 分割 csv 文件后添加

python - pandas:为列中的每一行计算 numpy 数组的平均值

nginx - 无法在本地 Windows 机器上访问 nginx 容器

linux - 如何在主机本地存储 Elasticsearch 数据?

将网络共享用于数据目录时,MySql docker 容器未启动

python - 如何为 VSCode 安装以前版本的 Python 扩展