我无法使用VS Code在docker容器中设置py.test代码的调试。
研究以下内容后:https://code.visualstudio.com/docs/python/debugging 这是How to remote debug python code in a Docker Container with VS Code
我在vscode中进行了以下调试配置设置:
{
"name": "Python: Attach",
"type": "python",
"request": "attach",
"localRoot": "${workspaceFolder}",
"remoteRoot": "/capi",
"port": 3000,
"secret": "secret_text",
"host": "localhost"
}
我已将此位导入到我的测试文件中:
import ptvsd
ptvsd.enable_attach("secret_text", address = ('0.0.0.0', 3000))
ptvsd.wait_for_attach()
我确保在docker-compose文件中打开了3000端口:
ports:
- 3000:3000
我再次检查端口是否打开:
nmap -p 3000 localhost
Starting Nmap 7.60 ( https://nmap.org ) at 2018-07-19 10:53 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000074s latency).
PORT STATE SERVICE
3000/tcp open ppp
Nmap done: 1 IP address (1 host up) scanned in 0.11 seconds
似乎是这样。当我从容器运行pytest文件时,它将启动并等待调试器连接:
===================================================== test session starts =====================================================
platform linux2 -- Python 2.7.15, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
rootdir: /capi, inifile:
plugins: requests-mock-1.5.0, xdist-1.14, metadata-1.7.0, html-1.16.1, cov-2.5.1
collecting 0 items
但是当我从VS Code运行此配置时,似乎什么也没发生。
我为一个简单的hello-world.py控制台应用程序设置了远程调试,仅用于测试,它似乎可以工作。因此,我的假设是它与我要调试pytest的事实有关。
有人设法做到这一点吗?我将不胜感激。
答案 0 :(得分:4)
我遇到了同样的问题,您的帖子几乎解决了问题。 当我尝试实施您的解决方案时,遇到以下问题:
ImportError while loading conftest '/app/tests/conftest.py'.
tests/conftest.py:36: in <module>
ptvsd.enable_attach("secret_text", address=("0.0.0.0", 5678))
E TypeError: enable_attach() got multiple values for argument 'address'
删除“ secret_text”值使我可以击中wait_for_attach()
点并将调试器成功附加到代码上。我可以在测试中达到断点。谢谢!
.vscode / launch.json
{
"name": "Python: Attach",
"type": "python",
"request": "attach",
"localRoot": "${workspaceFolder}/path/to/code",
"remoteRoot": "/app",
"port": 5678,
"host": "localhost"
}
docker-compose.yml
ports:
- "5678:5678"
conftest.py
import ptvsd
ptvsd.enable_attach(address=("0.0.0.0", 5678))
ptvsd.wait_for_attach()
注意:ptvsd行位于所有导入之后。
执行测试的CLI命令:
import subprocess
import click
@click.command()
def cli():
return subprocess.call("pytest test", shell=True)
调试测试的顺序:
docker-compose up
(使容器运行)docker-compose exec MODULE CONTAINER_NAME FUNCTION_THAT_EXECUTES_TEST
测试将执行并击中您设置的任何断点。