Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to tell Cargo to run its tests on the main thread?

I have been trying to build an OpenGL-based image processing library with GLFW, and need it to be testable. Unfortunately, I ran into this bug - GLFW needs its initialization functions to be called from the main thread, but Cargo tests are run on a background thread.

like image 430
jasongrlicky Avatar asked Apr 17 '17 19:04

jasongrlicky


People also ask

Does cargo test also build?

Target Selection. When no target selection options are given, cargo test will build the following targets of the selected packages: lib — used to link with binaries, examples, integration tests, and doc tests. bins (only if integration tests are built and required features are available)

Does cargo run tests in parallel?

The default behavior of the binary produced by cargo test is to run all the tests in parallel and capture output generated during test runs, preventing the output from being displayed and making it easier to read the output related to the test results.

How do you run a cargo test?

Cargo can run your tests with the cargo test command. Cargo looks for tests to run in two places: in each of your src files and any tests in tests/ . Tests in your src files should be unit tests and documentation tests. Tests in tests/ should be integration-style tests.


1 Answers

No, to the best of my knowledge, it's not easily possible right now. There is a --test-threads argument you can pass to the test harness, but it sets the number of threads in addition to the main thread. So --test-threads=1 results in two threads still.


So you can't really use the default test-harness. Luckily, you can disable it in Cargo.toml. Possibly the best solution is to create a new folder (e.g. gltests) and place all tests that require being run in main thread in there. Then we just have to declare those tests in Cargo.toml:

[[test]]
name = "gltests"
path = "gltests/main.rs"
harness = false

This means that cargo will try to compile gltests/main.rs as an executable (expecting a main() function) and execute this executable, whenever you say cargo test. This way you won't get any of the fancy output you usually get from cargo tests. You just have to do everything yourself in main.rs, but at least you can start tests in the main thread.

like image 154
Lukas Kalbertodt Avatar answered Sep 18 '22 13:09

Lukas Kalbertodt