简体   繁体   中英

How do you write test assertions inside of tokio::run futures?

How do you test your futures which are meant to be run in the Tokio runtime?

fn fut_dns() -> impl Future<Item = (), Error = ()> {
    let f = dns::lookup("www.google.de", "127.0.0.1:53");
    f.then(|result| match result {
        Ok(smtptls) => {
            println!("{:?}", smtptls);
            assert_eq!(smtptls.version, "TLSRPTv1");
            assert!(smtptls.rua.len() > 0);
            assert_eq!(smtptls.rua[0], "mailto://...");
            ok(())
        }
        Err(e) => {
            println!("error: {:?}", e);
            err(())
        }
    })
}

#[test]
fn smtp_log_test() {
    tokio::run(fut_dns());
    assert!(true);
}

The future runs and the thread of the future panics on an assert . You can read the panic in the console, but the test doesn't recognize the threads of tokio::run .

The How can I test a future that is bound to a tokio TcpStream? doesn't answer this, because it simply says: A simple way to test async code may be to use a dedicated runtime for each test

I do this!

My question is related to how the test can detect if the future works. The future needs a started runtime environment.

The test is successful although the future asserts or calls err().

So what can I do?

Do not write your assertions inside the future.

As described in How can I test a future that is bound to a tokio TcpStream? , create a Runtime to execute your future. As described in How do I synchronously return a value calculated in an asynchronous Future in stable Rust? , compute your value and then exit the async world:

fn run_one<F>(f: F) -> Result<F::Item, F::Error>
where
    F: IntoFuture,
    F::Future: Send + 'static,
    F::Item: Send + 'static,
    F::Error: Send + 'static,
{
    let mut runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime");
    runtime.block_on(f.into_future())
}

#[test]
fn smtp_log_test() {
    let smtptls = run_one(dns::lookup("www.google.de", "127.0.0.1:53")).unwrap();
    assert_eq!(smtptls.version, "TLSRPTv1");
    assert!(smtptls.rua.len() > 0);
    assert_eq!(smtptls.rua[0], "mailto://...");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM