testingrustrust-cargoisolationlibp2p

How to disable network access for Cargo tests?


I'm writing integration tests for my libp2p project. These are pretty powerful, essentially instantiating the full app and seeing how it interacts with other instances.

While libp2p has utilities to connect "swarms" to each other with a simulated network, the test utils do not permit turning off the actual network. This means that app instances from tests run in parallel see each other over the real network and start interacting.

While not directly crashing my tests, the simple fact that these interactions take time slow down my tests to the point where timeouts are reached.

I've tried running tests with sudo unshare -n cargo test to disable network access, but that breaks the build itself.

I did not find an option within cargo that would enable such isolation (and running test sequentially isn't desirable due to the huge total runtime increase).

Does anybody know of a smarter way to isolate running tests from the network?


Solution

  • Cargo does not currently provide any sandboxing features whatsoever. However, you can interpose a command of your own choice between building and running the test executable, using the target.*.runner configuration.

    Create a file .cargo/config.toml, and put in your choice of command which accepts the test executable as as its last argument:

    [target.'cfg(target_os = "linux")']
    runner = ["sudo", "unshare", "-n"]
    

    Then, a cargo test (or cargo run) will automatically use this command.

    Notes: