Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration Tests With Rocket #148

Closed
iot-resister opened this issue Jul 9, 2022 · 0 comments
Closed

Integration Tests With Rocket #148

iot-resister opened this issue Jul 9, 2022 · 0 comments

Comments

@iot-resister
Copy link

iot-resister commented Jul 9, 2022

Hello,
Thank you for the great library. I'm posting this in case someone else finds it useful. I was trying to create a simple integration test with rocket. I was bashing my head until I learned that cfg(test) is false when doing an integration test.

See: rust-lang/rust#45599

I have an e2e flag on my config and used that instead. Anyway here is my lib.rs and integration_test.rs, respectively. (Please excuse the quality, I'm new to rust. Any feedback is appreciated)

mod config;

#[macro_use]
extern crate rocket;

use config::load_config;
use rocket::{Build, Rocket};
use serde::{Deserialize, Serialize};
use std::io;
use std::net::Ipv4Addr;

#[derive(Debug, Serialize, Deserialize)]
pub struct Resp {
    pub origin: Ipv4Addr,
}

#[get("/")]
async fn index() -> io::Result<String> {
    let config = load_config().unwrap();
    let url = match config.e2e {
        true => "https://httpbin.org/ip".to_string(),
        false => mockito::server_url(),
    };
    let res = reqwest::get(url)
        .await
        .unwrap()
        .json::<Resp>()
        .await
        .unwrap();
    Ok(res.origin.to_string())
}

pub fn app() -> Rocket<Build> {
    let config = load_config().unwrap();
    let figment = rocket::Config::figment()
        .merge(("address", &config.host))
        .merge(("port", &config.port))
        .merge(("log_level", "off"));

    rocket::custom(figment).mount("/", routes![index])
}
use rs_101::app;

use mockito::mock;
use rocket::local::asynchronous::Client;

#[tokio::test]
async fn test_with_reqwest() {
    let _m = mock("GET", "/")
        .with_body(r#"{"origin": "0.0.0.0"}"#)
        .create();

    let client = Client::tracked(app()).await.unwrap();
    let resp = client.get("/").dispatch().await;
    assert_eq!("0.0.0.0", resp.into_string().await.unwrap());
}
@iot-resister iot-resister closed this as not planned Won't fix, can't repro, duplicate, stale Jul 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant