Wrong order of output from c++ function when it is used in rust tests

Hi everyone,

I added c++ library to my rust code and I want to use it in tests. My issue is that output from this library displayed before main output (but expected result is opposite). This is how c++ function was added:

#[cfg(test)]
mod tests {
    // ...
    extern "C" {
        #[link(name="srp6_dir", kind="static")]
        fn test_srp6(B_str: *const c_char, s_str: *const c_char, account_str: *const c_char);
    }
}

and next I use it in one of my tests:

#[test]
fn test_proof() {
    // ... rest of calculations and output
    let B_str = CString::new(format!("{:?}", B)).expect("Failed to create CString for B");
    let s_str = CString::new(format!("{:?}", _salt)).expect("Failed to create CString for s");
    let account_str = CString::new(account.to_string()).expect("Failed to create CString for account");

    unsafe {
        println!("C++ code result");
        test_srp6(B_str.as_ptr(), s_str.as_ptr(), account_str.as_ptr());
    }
}

Expected result:

... rest of calculations and output
C++ code result
... output from test_srp6

Actual result:

... output from test_srp6
... rest of calculations and output
C++ code result

Could somebody explain why this happen and how to fix it ?

I think it's because stdout in Rust is buffered. To test this, try putting a call to flush it before your call to test_srp6:

println!("C++ code result");
std::io::stdout().flush()?; // <<<
test_srp6(...);
2 Likes

unfortunately, the output is the same after I run tests with cargo test

Hmm, maybe it's buffered by cargo test.

probably I can try anything else ?

You could try:
cargo test -- --nocapture

2 Likes

Yeah, libtest will by default buffer the rust stdout/stderr for the thread of each individual test to only print when a test fails. It can't buffer it for non-rust code.

1 Like

This works, thank you very much for explanation

1 Like

I'm not sure if it will also work, but there's also

cargo test -- --show-output

You can also bypass Rust's output buffering using something close to the approach here, but it sounds like you won't have to resort to that.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.