Rocket/examples/config/tests/common/mod.rs

72 lines
2.6 KiB
Rust
Raw Normal View History

use rocket::{self, State};
use rocket::fairing::AdHoc;
use rocket::config::{self, Config, Environment};
use rocket::http::{Method, Status};
2016-12-27 22:35:14 +00:00
use rocket::LoggingLevel;
use rocket::testing::MockRequest;
struct LocalConfig(Config);
#[get("/check_config")]
fn check_config(config: State<LocalConfig>) -> Option<()> {
let environment = match ::std::env::var("ROCKET_ENV") {
Ok(name) => name,
Err(_) => return None
};
2016-12-27 22:35:14 +00:00
let config = &config.0;
match &*environment {
"development" => {
2016-12-27 22:35:14 +00:00
assert_eq!(config.address, "localhost".to_string());
assert_eq!(config.port, 8000);
assert_eq!(config.workers, 1);
2016-12-27 22:35:14 +00:00
assert_eq!(config.log_level, LoggingLevel::Normal);
assert_eq!(config.environment, config::Environment::Development);
2016-12-27 22:35:14 +00:00
assert_eq!(config.extras().count(), 2);
assert_eq!(config.get_str("hi"), Ok("Hello!"));
assert_eq!(config.get_bool("is_extra"), Ok(true));
}
"staging" => {
2016-12-27 22:35:14 +00:00
assert_eq!(config.address, "0.0.0.0".to_string());
assert_eq!(config.port, 80);
assert_eq!(config.workers, 8);
2016-12-27 22:35:14 +00:00
assert_eq!(config.log_level, LoggingLevel::Normal);
assert_eq!(config.environment, config::Environment::Staging);
2016-12-27 22:35:14 +00:00
assert_eq!(config.extras().count(), 0);
}
"production" => {
2016-12-27 22:35:14 +00:00
assert_eq!(config.address, "0.0.0.0".to_string());
assert_eq!(config.port, 80);
assert_eq!(config.workers, 12);
2016-12-27 22:35:14 +00:00
assert_eq!(config.log_level, LoggingLevel::Critical);
assert_eq!(config.environment, config::Environment::Production);
2016-12-27 22:35:14 +00:00
assert_eq!(config.extras().count(), 0);
}
_ => {
panic!("Unknown environment in envvar: {}", environment);
}
2016-12-27 22:35:14 +00:00
}
Some(())
2016-12-27 22:35:14 +00:00
}
pub fn test_config(environment: Environment) {
// Manually set the config environment variable. Rocket will initialize the
// environment in `ignite()`. We'll read this back in the handler to config.
::std::env::set_var("ROCKET_ENV", environment.to_string());
// FIXME: launch fairings aren't run during tests since...the Rocket isn't
// being launch
let rocket = rocket::ignite()
.attach(AdHoc::on_attach(|rocket| {
println!("Attaching local config.");
let config = rocket.config().clone();
Ok(rocket.manage(LocalConfig(config)))
}))
.mount("/", routes![check_config]);
2016-12-27 22:35:14 +00:00
let mut request = MockRequest::new(Method::Get, "/check_config");
let response = request.dispatch_with(&rocket);
assert_eq!(response.status(), Status::Ok);
2016-12-27 22:35:14 +00:00
}