diff --git a/src/cli.rs b/src/cli.rs index 0c058ce0..23c118e2 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -24,6 +24,23 @@ pub fn parse_n_requests(s: &str) -> Result { } } +pub fn parse_no_color(s: &str) -> Result { + Ok(!s.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::parse_no_color; + + #[test] + fn test_parse_no_color() { + assert!(!parse_no_color("").unwrap()); + assert!(parse_no_color("1").unwrap()); + assert!(parse_no_color("true").unwrap()); + assert!(parse_no_color("false").unwrap()); + } +} + /// An entry specified by `connect-to` to override DNS resolution and default /// port numbers. For example, `example.org:80:localhost:5000` will connect to /// `localhost:5000` whenever `http://example.org` is requested. diff --git a/src/lib.rs b/src/lib.rs index 7cb3545c..db144066 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -282,7 +282,10 @@ Note: if used several times for the same host:port:target_host:target_port, a ra help = "Disable the color scheme.", alias = "disable-color", long = "no-color", - env = "NO_COLOR" + env = "NO_COLOR", + default_value = "", + default_missing_value = "true", + value_parser = cli::parse_no_color )] no_color: bool, #[cfg(unix)] diff --git a/tests/tests.rs b/tests/tests.rs index 73efd042..cf4c50ee 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -11,7 +11,7 @@ use std::{ use axum::{Router, extract::Path, response::Redirect, routing::get}; use bytes::Bytes; -use clap::Parser; +use clap::{CommandFactory, Parser}; use http::{HeaderMap, Request, Response}; use http_body_util::BodyExt; use http_mitm_proxy::MitmProxy; @@ -36,6 +36,35 @@ async fn run<'a>(args: impl Iterator) { oha::run(opts).await.unwrap(); } +#[test] +fn test_no_color_env_convention() { + for value in ["1", ""] { + let status = std::process::Command::new(env!("CARGO_BIN_EXE_oha")) + .args([ + "http://127.0.0.1:9", + "-n", + "1", + "--no-tui", + "--output-format", + "quiet", + ]) + .env("NO_COLOR", value) + .status() + .unwrap(); + + assert!(status.success()); + } +} + +#[test] +fn test_no_color_cli_flag() { + let matches = oha::Opts::command() + .mut_arg("no_color", |arg| arg.env(None)) + .try_get_matches_from(["oha", "--no-color", "http://example.com"]) + .unwrap(); + assert!(matches.get_flag("no_color")); +} + // Port 5111- is reserved for testing static PORT: AtomicU16 = AtomicU16::new(5111);