19

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Riduidel
  • 22,052
  • 14
  • 85
  • 185

1 Answers1

22

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 3
    If anyone is having trouble getting this to work then make sure you click on the debug tab on the left (the icon with the little bug on it) and change the dropdown (to the right of the DEBUG play sign) to Run Test Debugger. You then execute the test by pressing F5 instead of running your test build task directly. Thanks Shepmaster for the instructions above!! – David Sep 30 '18 at 10:26