如何使用Docker容器作为从IDE运行Python测试的虚拟机



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

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

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

摘要

是的,有办法做到这一点。通过配置远程Python解释器和"sidecar"Docker容器。

此Docker容器将具有:

  • 装入源代码的卷(此后为/code(
  • SSH设置
  • 为root启用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. 点击"项目口译员"下拉菜单旁的齿轮图标>添加
  3. 选择"SSH解释器">主机:localhost,端口:9922,用户名:root>密码:密码>解释器:/usr/local/bin/python,同步文件夹:Project root->/code,禁用"自动上传…">
  4. 确认更改并等待PyCharm更新索引

设置Visual Studio代码

  1. 安装Python扩展
  2. 安装Remote-Containers扩展
  3. 打开Command Palette并键入Remote Containers,然后选择Attach to Running Container。。。并选择正在运行的docker容器VS代码将重新启动并重新加载
  4. 在Explorer侧边栏上,单击打开文件夹按钮,然后输入/code(这将从远程容器加载(
  5. 在Extensions侧边栏上,选择Python扩展并将其安装在容器上
  6. 当提示在哪个interpreter上使用时,选择/usr/local/bin/python
  7. 打开Command Palette并键入Python:Configure Tests,然后选择unittest框架

TDD启用

现在您可以直接从IDE运行测试了,请使用它来尝试测试驱动开发!它的一个关键点是快速反馈循环,不必等待完整的测试套件完成执行,只为了看看你的新测试是否通过,这太棒了!只要写下来,马上就跑!

参考

此答案的内容也可在本GIST中获得。

最新更新