Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

debugging - How to debug Rust unit tests on Windows?

I'm developing code for the Codingame problems using VS Code on Windows with Rust and the Visual Studio toolchain.

I have found multiple guides explaining how to debug the executable generated by cargo build, the best being Debug Rust on Windows with Visual Studio Code and the MSVC Debugger.

However, when I face problems, I tend to write unit tests (I've done that in Java, JavaScript, Ruby, ...), which I then debug. Unfortunately, I can't find any way to do that in Rust. How do I configure my environment to debug my tests?

I'm not talking about adding println! statements in my tests, as I already know how to do that. I'm also not talking about adding new assertions, because those reside in the test, not in the tested code.

What I want is to use the VS Code Debugger on the code called by my test.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Rust unit tests are compiled as separate binaries, which means you debug them exactly the same as any other binary. Once compiled, they are located at ./target/debug/$name-$hash.

Visual Studio Code

Here's modified versions of the VS Code configuration files that allow me to debug a unit test.

tasks.json

{
    "type": "shell",
    "label": "cargo test build",
    "command": "cargo",
    "args": [
        "test", "--no-run"
    ],
    "problemMatcher": [
        "$rustc"
    ]
}

launch.json

{
    "name": "Run Test Debugger",
    "type": "cppvsdbg",
    "request": "launch",
    "program": "${workspaceFolder}/target/debug/buggin-70708b3916187eeb.exe",
    "args": [],
    "stopAtEntry": false,
    "cwd": "${workspaceFolder}",
    "environment": [],
    "externalConsole": true,
    "preLaunchTask": "cargo test build",
}

Working

VS Code debugger running on a test

Windbg

Build your tests:

cargo test --no-run

Open the built executable in Windbg and open the source file.

Windbg on Rust test


Finding the hash is the most annoying aspect. The best solution I know of is to write a small script that builds the tests and then finds the test executable based on which is newest. My Powershell skills are not adequate to the task, nor do I know how to directly integrate this with VS Code or Windbg.

There are open issues for Cargo to help with identifying the file:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...