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?
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:
I don't know anything about the unshare
command. Use at your own risk.
The intended purpose of this feature is to allow using emulators or remote execution of binaries that cannot be run on the host platform, which is why it allows specifying a target triple or cfg
expression. In this case, we don't actually care about the exact CPU architecture, but it does makes sense to limit the usage of the command to systems that we know have the sudo
and unshare
commands.