Create bas logger for basic error and logger for a run file.

This commit is contained in:
jcamiel 2022-08-03 16:23:24 +02:00
parent 919fdb6261
commit 74efc91da3
No known key found for this signature in database
GPG Key ID: 07FF11CFD55356CC
9 changed files with 186 additions and 121 deletions

View File

@ -3,4 +3,4 @@
* insecure: false * insecure: false
* follow redirect: false * follow redirect: false
* max redirect: 50 * max redirect: 50
warning: no entry have been executed for file tests_ok/color.hurl warning: No entry have been executed for file tests_ok/color.hurl

View File

@ -25,7 +25,7 @@ pub use self::options::parse_options;
pub use self::options::{CliOptions, OutputType}; pub use self::options::{CliOptions, OutputType};
pub use self::variables::parse as parse_variable; pub use self::variables::parse as parse_variable;
pub use self::variables::parse_value as parse_variable_value; pub use self::variables::parse_value as parse_variable_value;
pub use crate::util::logger::{error_string, Logger}; pub use crate::util::logger::{error_string, error_string_no_color, Logger};
mod fs; mod fs;
pub mod interactive; pub mod interactive;

View File

@ -16,6 +16,7 @@
* *
*/ */
use crate::cli;
use crate::http::{ use crate::http::{
Cookie, Header, Param, Request, RequestCookie, Response, ResponseCookie, Version, Cookie, Header, Param, Request, RequestCookie, Response, ResponseCookie, Version,
}; };
@ -256,7 +257,7 @@ impl AssertResult {
map.insert("success".to_string(), serde_json::Value::Bool(success)); map.insert("success".to_string(), serde_json::Value::Bool(success));
if let Some(err) = self.clone().error() { if let Some(err) = self.clone().error() {
let message = crate::cli::error_string(filename, content, &err); let message = cli::error_string_no_color(filename, content, &err);
map.insert("message".to_string(), serde_json::Value::String(message)); map.insert("message".to_string(), serde_json::Value::String(message));
} }
map.insert( map.insert(

View File

@ -32,6 +32,7 @@ use hurl::report;
use hurl::report::canonicalize_filename; use hurl::report::canonicalize_filename;
use hurl::runner; use hurl::runner;
use hurl::runner::{HurlResult, RunnerError, RunnerOptions}; use hurl::runner::{HurlResult, RunnerError, RunnerOptions};
use hurl::util::logger::BaseLogger;
use hurl_core::ast::{Pos, SourceInfo}; use hurl_core::ast::{Pos, SourceInfo};
use hurl_core::error::Error; use hurl_core::error::Error;
use hurl_core::parser; use hurl_core::parser;
@ -102,13 +103,12 @@ fn execute(
logger: &Logger, logger: &Logger,
) -> HurlResult { ) -> HurlResult {
if let Some(Progress { current, total }) = progress { if let Some(Progress { current, total }) = progress {
eprintln!("{}: RUNNING [{}/{}]", filename, current + 1, total); logger.info(format!("{}: RUNNING [{}/{}]", filename, current + 1, total).as_str());
} }
match parser::parse_hurl_file(content) { match parser::parse_hurl_file(content) {
Err(e) => { Err(e) => {
let error_message = cli::error_string(filename, content, &e); logger.error_rich(&e);
logger.error(format!("{}\n", &error_message).as_str());
std::process::exit(EXIT_ERROR_PARSING); std::process::exit(EXIT_ERROR_PARSING);
} }
Ok(hurl_file) => { Ok(hurl_file) => {
@ -212,7 +212,7 @@ fn execute(
pre_entry, pre_entry,
post_entry, post_entry,
}; };
let result = runner::run(&hurl_file, filename, content, &mut client, &options, logger); let result = runner::run(&hurl_file, filename, &mut client, &options, logger);
if cli_options.progress { if cli_options.progress {
let status = match (result.success, cli_options.color) { let status = match (result.success, cli_options.color) {
(true, true) => "SUCCESS".green().to_string(), (true, true) => "SUCCESS".green().to_string(),
@ -220,7 +220,7 @@ fn execute(
(false, true) => "FAILURE".red().to_string(), (false, true) => "FAILURE".red().to_string(),
(false, false) => "FAILURE".to_string(), (false, false) => "FAILURE".to_string(),
}; };
eprintln!("{}: {}", filename, status); logger.info(format!("{}: {}", filename, status).as_str());
} }
result result
} }
@ -232,17 +232,20 @@ fn execute(
/// # Arguments /// # Arguments
/// ///
/// * result - Something to unwrap /// * result - Something to unwrap
/// * log_error_message - A function to log error message if unwrap fail /// * logger - A logger to log the error
fn unwrap_or_exit<T>(result: Result<T, CliError>, logger: &Logger) -> T { fn unwrap_or_exit<T>(result: Result<T, CliError>, code: i32, logger: &BaseLogger) -> T {
match result { match result {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => exit(&e.message, code, logger),
logger.error(e.message.as_str());
std::process::exit(EXIT_ERROR_UNDEFINED);
}
} }
} }
/// Prints an error message and exits the current process with an exit code.
fn exit(message: &str, code: i32, logger: &BaseLogger) -> ! {
logger.error(message);
std::process::exit(code);
}
/// Executes Hurl entry point. /// Executes Hurl entry point.
fn main() { fn main() {
let version_info = format!( let version_info = format!(
@ -258,8 +261,9 @@ fn main() {
|| cli::has_flag(&matches, "very_verbose") || cli::has_flag(&matches, "very_verbose")
|| cli::has_flag(&matches, "interactive"); || cli::has_flag(&matches, "interactive");
let color = cli::output_color(&matches); let color = cli::output_color(&matches);
let logger = Logger::new(color, verbose); let base_logger = BaseLogger::new(color, verbose);
let cli_options = unwrap_or_exit(cli::parse_options(&matches), &logger); let cli_options = cli::parse_options(&matches);
let cli_options = unwrap_or_exit(cli_options, EXIT_ERROR_UNDEFINED, &base_logger);
let mut filenames = vec![]; let mut filenames = vec![];
if let Some(values) = cli::get_strings(&matches, "INPUT") { if let Some(values) = cli::get_strings(&matches, "INPUT") {
@ -272,11 +276,12 @@ fn main() {
} }
if filenames.is_empty() && atty::is(Stream::Stdin) { if filenames.is_empty() && atty::is(Stream::Stdin) {
if app.clone().print_help().is_err() { let error = if app.clone().print_help().is_err() {
panic!("panic during printing help"); "Panic during printing help"
} } else {
println!(); ""
std::process::exit(EXIT_ERROR_COMMANDLINE); };
exit(error, EXIT_ERROR_COMMANDLINE, &base_logger);
} else if filenames.is_empty() { } else if filenames.is_empty() {
filenames.push("-".to_string()); filenames.push("-".to_string());
} }
@ -284,8 +289,11 @@ fn main() {
let current_dir = match std::env::current_dir() { let current_dir = match std::env::current_dir() {
Ok(c) => c, Ok(c) => c,
Err(error) => { Err(error) => {
logger.error(error.to_string().as_str()); exit(
std::process::exit(EXIT_ERROR_PARSING); error.to_string().as_str(),
EXIT_ERROR_UNDEFINED,
&base_logger,
);
} }
}; };
let current_dir = current_dir.as_path(); let current_dir = current_dir.as_path();
@ -293,7 +301,7 @@ fn main() {
None => None, None => None,
Some(filename) => { Some(filename) => {
let result = cookies_output_file(&filename, filenames.len()); let result = cookies_output_file(&filename, filenames.len());
let filename = unwrap_or_exit(result, &logger); let filename = unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
Some(filename) Some(filename)
} }
}; };
@ -308,16 +316,10 @@ fn main() {
"hurl: cannot access '{}': No such file or directory", "hurl: cannot access '{}': No such file or directory",
filename filename
); );
logger.error(&message); exit(&message, EXIT_ERROR_PARSING, &base_logger);
std::process::exit(EXIT_ERROR_PARSING);
} }
let content = match cli::read_to_string(filename) { let content = cli::read_to_string(filename);
Ok(v) => v, let content = unwrap_or_exit(content, EXIT_ERROR_PARSING, &base_logger);
Err(e) => {
logger.error(e.message.as_str());
std::process::exit(EXIT_ERROR_PARSING);
}
};
let progress = if cli_options.progress { let progress = if cli_options.progress {
Some(Progress { Some(Progress {
@ -327,6 +329,8 @@ fn main() {
} else { } else {
None None
}; };
let logger = Logger::new(color, verbose, filename, &content);
let hurl_result = execute( let hurl_result = execute(
filename, filename,
&content, &content,
@ -362,19 +366,19 @@ fn main() {
match response.uncompress_body() { match response.uncompress_body() {
Ok(bytes) => bytes, Ok(bytes) => bytes,
Err(e) => { Err(e) => {
logger.error( // FIXME: we convert to a runner::Error to be able to use fixme
runner::Error { // method. Can we do otherwise (without creating an artificial
source_info: SourceInfo { // error a first character).
start: Pos { line: 0, column: 0 }, let error = runner::Error {
end: Pos { line: 0, column: 0 }, source_info: SourceInfo {
}, start: Pos { line: 0, column: 0 },
inner: RunnerError::from(e), end: Pos { line: 0, column: 0 },
assert: false, },
} inner: RunnerError::from(e),
.fixme() assert: false,
.as_str(), };
); let message = error.fixme();
std::process::exit(EXIT_ERROR_RUNTIME); exit(&message, EXIT_ERROR_RUNTIME, &base_logger);
} }
} }
} else { } else {
@ -382,7 +386,7 @@ fn main() {
}; };
output.append(&mut body.clone()); output.append(&mut body.clone());
let result = write_output(&output, &cli_options.output); let result = write_output(&output, &cli_options.output);
unwrap_or_exit(result, &logger); unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
} else { } else {
logger.info("No response has been received"); logger.info("No response has been received");
} }
@ -401,7 +405,7 @@ fn main() {
let serialized = serde_json::to_string(&json_result).unwrap(); let serialized = serde_json::to_string(&json_result).unwrap();
let s = format!("{}\n", serialized); let s = format!("{}\n", serialized);
let result = write_output(&s.into_bytes(), &cli_options.output); let result = write_output(&s.into_bytes(), &cli_options.output);
unwrap_or_exit(result, &logger); unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
} }
if cli_options.junit_file.is_some() { if cli_options.junit_file.is_some() {
let testcase = report::Testcase::from_hurl_result(&hurl_result, &content); let testcase = report::Testcase::from_hurl_result(&hurl_result, &content);
@ -410,32 +414,32 @@ fn main() {
} }
if let Some(filename) = cli_options.junit_file.clone() { if let Some(filename) = cli_options.junit_file.clone() {
logger.debug(format!("Writing Junit report to {}", filename).as_str()); base_logger.debug(format!("Writing Junit report to {}", filename).as_str());
let result = report::create_junit_report(filename, testcases); let result = report::create_junit_report(filename, testcases);
unwrap_or_exit(result, &logger); unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
} }
if let Some(dir_path) = cli_options.html_dir { if let Some(dir_path) = cli_options.html_dir {
logger.debug(format!("Writing html report to {}", dir_path.display()).as_str()); base_logger.debug(format!("Writing html report to {}", dir_path.display()).as_str());
let result = report::write_html_report(dir_path.clone(), hurl_results.clone()); let result = report::write_html_report(dir_path.clone(), hurl_results.clone());
unwrap_or_exit(result, &logger); unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
for filename in filenames { for filename in filenames {
let result = format_html(filename.as_str(), &dir_path); let result = format_html(filename.as_str(), &dir_path);
unwrap_or_exit(result, &logger); unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
} }
} }
if let Some(file_path) = cookies_output_file { if let Some(file_path) = cookies_output_file {
logger.debug(format!("Writing cookies to {}", file_path.display()).as_str()); base_logger.debug(format!("Writing cookies to {}", file_path.display()).as_str());
let result = write_cookies_file(&file_path, &hurl_results); let result = write_cookies_file(&file_path, &hurl_results);
unwrap_or_exit(result, &logger); unwrap_or_exit(result, EXIT_ERROR_UNDEFINED, &base_logger);
} }
if cli_options.summary { if cli_options.summary {
let duration = start.elapsed().as_millis(); let duration = start.elapsed().as_millis();
let summary = get_summary(duration, &hurl_results); let summary = get_summary(duration, &hurl_results);
eprintln!("{}", summary.as_str()); base_logger.info(summary.as_str());
} }
std::process::exit(exit_code(&hurl_results)); std::process::exit(exit_code(&hurl_results));

View File

@ -40,7 +40,7 @@ impl Testcase {
let mut errors = vec![]; let mut errors = vec![];
for error in hurl_result.errors() { for error in hurl_result.errors() {
let message = cli::error_string(&hurl_result.filename, content, &error); let message = cli::error_string_no_color(&hurl_result.filename, content, &error);
if error.assert { if error.assert {
failures.push(message); failures.push(message);
} else { } else {

View File

@ -19,7 +19,7 @@ use std::collections::HashMap;
use std::time::Instant; use std::time::Instant;
use crate::cli::Logger; use crate::cli::Logger;
use crate::{cli, http}; use crate::http;
use hurl_core::ast::*; use hurl_core::ast::*;
use super::core::*; use super::core::*;
@ -57,7 +57,7 @@ use super::entry;
/// // Create an HTTP client /// // Create an HTTP client
/// let options = http::ClientOptions::default(); /// let options = http::ClientOptions::default();
/// let mut client = http::Client::init(options); /// let mut client = http::Client::init(options);
/// let logger = Logger::default(); /// let logger = Logger::new(false, false, filename, s);
/// ///
/// // Define runner options /// // Define runner options
/// let variables = std::collections::HashMap::new(); /// let variables = std::collections::HashMap::new();
@ -76,7 +76,6 @@ use super::entry;
/// let hurl_results = runner::run( /// let hurl_results = runner::run(
/// &hurl_file, /// &hurl_file,
/// filename, /// filename,
/// s,
/// &mut client, /// &mut client,
/// &options, /// &options,
/// &logger, /// &logger,
@ -88,7 +87,6 @@ use super::entry;
pub fn run( pub fn run(
hurl_file: &HurlFile, hurl_file: &HurlFile,
filename: &str, filename: &str,
content: &str,
http_client: &mut http::Client, http_client: &mut http::Client,
options: &RunnerOptions, options: &RunnerOptions,
logger: &Logger, logger: &Logger,
@ -131,8 +129,7 @@ pub fn run(
for entry_result in entry_results.clone() { for entry_result in entry_results.clone() {
for e in entry_result.errors.clone() { for e in entry_result.errors.clone() {
let error_message = cli::error_string(filename, content, &e); logger.error_rich(&e);
logger.error(format!("{}\n", &error_message).as_str());
} }
entries.push(entry_result.clone()); entries.push(entry_result.clone());
} }

View File

@ -19,42 +19,105 @@
use colored::*; use colored::*;
use hurl_core::error::Error; use hurl_core::error::Error;
/// A logger holds logger functions. A logger function is just a function that takes a string /// A simple logger to log app related event (start, high levels error, etc...).
/// slice parameter. /// When we run an [`hurl_core::ast::HurlFile`], user has to provide a dedicated Hurl logger (see [`Logger`]).
pub struct Logger { pub struct BaseLogger {
info: fn(&str), pub info: fn(&str),
debug: fn(&str), pub debug: fn(&str),
warning: fn(&str), pub error: fn(&str),
error: fn(&str),
} }
impl Logger { impl BaseLogger {
pub fn new(color: bool, verbose: bool) -> BaseLogger {
match (color, verbose) {
(true, true) => BaseLogger {
info: log_info,
debug: log_debug,
error: log_error,
},
(false, true) => BaseLogger {
info: log_info,
debug: log_debug_no_color,
error: log_error_no_color,
},
(true, false) => BaseLogger {
info: log_info,
debug: nop,
error: log_error,
},
(false, false) => BaseLogger {
info: log_info,
debug: nop,
error: log_error_no_color,
},
}
}
pub fn info(&self, message: &str) {
(self.info)(message)
}
pub fn debug(&self, message: &str) {
(self.debug)(message)
}
pub fn error(&self, message: &str) {
(self.error)(message)
}
}
/// A Hurl dedicated logger for an Hurl file. Contrary to [`BaseLogger`], this logger can display
/// rich error for parsing and runtime errors. As the rich errors can display user content,
/// this logger should have access to the content of the file being run.
pub struct Logger<'a> {
pub info: fn(&str),
pub debug: fn(&str),
pub warning: fn(&str),
pub error: fn(&str),
pub error_rich: fn(&str, &str, &dyn Error),
pub content: &'a str,
pub filename: &'a str,
}
impl<'a> Logger<'a> {
/// Creates a new logger. /// Creates a new logger.
pub fn new(color: bool, verbose: bool) -> Logger { pub fn new(color: bool, verbose: bool, filename: &'a str, content: &'a str) -> Logger<'a> {
match (color, verbose) { match (color, verbose) {
(true, true) => Logger { (true, true) => Logger {
info: log_info, info: log_info,
debug: log_debug, debug: log_debug,
warning: log_warning, warning: log_warning,
error: log_error, error: log_error,
error_rich: log_error_rich,
content,
filename,
}, },
(false, true) => Logger { (false, true) => Logger {
info: log_info, info: log_info,
debug: log_debug_no_color, debug: log_debug_no_color,
warning: log_warning_no_color, warning: log_warning_no_color,
error: log_error_no_color, error: log_error_no_color,
error_rich: log_error_rich_no_color,
content,
filename,
}, },
(true, false) => Logger { (true, false) => Logger {
info: log_info, info: log_info,
debug: nop, debug: nop,
warning: log_warning, warning: log_warning,
error: log_error, error: log_error,
error_rich: log_error_rich,
content,
filename,
}, },
(false, false) => Logger { (false, false) => Logger {
info: log_info, info: log_info,
debug: nop, debug: nop,
warning: log_warning_no_color, warning: log_warning_no_color,
error: log_error_no_color, error: log_error_no_color,
error_rich: log_error_rich_no_color,
content,
filename,
}, },
} }
} }
@ -74,11 +137,9 @@ impl Logger {
pub fn error(&self, message: &str) { pub fn error(&self, message: &str) {
(self.error)(message) (self.error)(message)
} }
}
impl Default for Logger { pub fn error_rich(&self, error: &dyn Error) {
fn default() -> Self { (self.error_rich)(self.filename, self.content, error)
Logger::new(true, false)
} }
} }
@ -120,6 +181,16 @@ fn log_error_no_color(message: &str) {
eprintln!("error: {}", message); eprintln!("error: {}", message);
} }
fn log_error_rich(filename: &str, content: &str, error: &dyn Error) {
let message = error_string(filename, content, error);
log_error(format!("{}\n", &message).as_str())
}
fn log_error_rich_no_color(filename: &str, content: &str, error: &dyn Error) {
let message = error_string_no_color(filename, content, error);
log_error_no_color(format!("{}\n", &message).as_str())
}
/// Returns an `error` as a string, given `lines` of content and a `filename`. /// Returns an `error` as a string, given `lines` of content and a `filename`.
pub fn error_string(filename: &str, content: &str, error: &dyn Error) -> String { pub fn error_string(filename: &str, content: &str, error: &dyn Error) -> String {
let lines: Vec<&str> = regex::Regex::new(r"\n|\r\n") let lines: Vec<&str> = regex::Regex::new(r"\n|\r\n")
@ -199,6 +270,10 @@ pub fn error_string(filename: &str, content: &str, error: &dyn Error) -> String
) )
} }
pub fn error_string_no_color(filename: &str, content: &str, error: &dyn Error) -> String {
error_string(filename, content, error)
}
fn add_line_prefix(s: &str, prefix: String) -> String { fn add_line_prefix(s: &str, prefix: String) -> String {
let lines: Vec<&str> = regex::Regex::new(r"\n|\r\n").unwrap().split(s).collect(); let lines: Vec<&str> = regex::Regex::new(r"\n|\r\n").unwrap().split(s).collect();
lines lines

View File

@ -53,7 +53,7 @@ fn default_get_request(url: String) -> RequestSpec {
#[test] #[test]
fn test_hello() { fn test_hello() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://localhost:8000/hello".to_string()); let request_spec = default_get_request("http://localhost:8000/hello".to_string());
assert_eq!( assert_eq!(
client.curl_command_line(&request_spec), client.curl_command_line(&request_spec),
@ -96,7 +96,7 @@ fn test_hello() {
#[test] #[test]
fn test_put() { fn test_put() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Put, method: Method::Put,
url: "http://localhost:8000/put".to_string(), url: "http://localhost:8000/put".to_string(),
@ -132,7 +132,7 @@ fn test_put() {
#[test] #[test]
fn test_patch() { fn test_patch() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Patch, method: Method::Patch,
url: "http://localhost:8000/patch/file.txt".to_string(), url: "http://localhost:8000/patch/file.txt".to_string(),
@ -188,7 +188,7 @@ fn test_patch() {
#[test] #[test]
fn test_custom_headers() { fn test_custom_headers() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Get, method: Method::Get,
url: "http://localhost:8000/custom-headers".to_string(), url: "http://localhost:8000/custom-headers".to_string(),
@ -233,7 +233,7 @@ fn test_custom_headers() {
#[test] #[test]
fn test_querystring_params() { fn test_querystring_params() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Get, method: Method::Get,
url: "http://localhost:8000/querystring-params".to_string(), url: "http://localhost:8000/querystring-params".to_string(),
@ -282,7 +282,7 @@ fn test_querystring_params() {
#[test] #[test]
fn test_form_params() { fn test_form_params() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Post, method: Method::Post,
url: "http://localhost:8000/form-params".to_string(), url: "http://localhost:8000/form-params".to_string(),
@ -352,7 +352,7 @@ fn test_form_params() {
#[test] #[test]
fn test_redirect() { fn test_redirect() {
let request_spec = default_get_request("http://localhost:8000/redirect".to_string()); let request_spec = default_get_request("http://localhost:8000/redirect".to_string());
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let mut client = default_client(); let mut client = default_client();
let (request, response) = client.execute(&request_spec, &logger).unwrap(); let (request, response) = client.execute(&request_spec, &logger).unwrap();
assert_eq!(request.method, "GET".to_string()); assert_eq!(request.method, "GET".to_string());
@ -370,7 +370,7 @@ fn test_redirect() {
#[test] #[test]
fn test_follow_location() { fn test_follow_location() {
let request_spec = default_get_request("http://localhost:8000/redirect".to_string()); let request_spec = default_get_request("http://localhost:8000/redirect".to_string());
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let options = ClientOptions { let options = ClientOptions {
follow_location: true, follow_location: true,
..Default::default() ..Default::default()
@ -422,7 +422,7 @@ fn test_max_redirect() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://localhost:8000/redirect/15".to_string()); let request_spec = default_get_request("http://localhost:8000/redirect/15".to_string());
assert_eq!( assert_eq!(
@ -456,7 +456,7 @@ fn test_max_redirect() {
#[test] #[test]
fn test_multipart_form_data() { fn test_multipart_form_data() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Post, method: Method::Post,
url: "http://localhost:8000/multipart-form-data".to_string(), url: "http://localhost:8000/multipart-form-data".to_string(),
@ -519,7 +519,7 @@ fn test_multipart_form_data() {
#[test] #[test]
fn test_post_bytes() { fn test_post_bytes() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Post, method: Method::Post,
url: "http://localhost:8000/post-base64".to_string(), url: "http://localhost:8000/post-base64".to_string(),
@ -550,7 +550,7 @@ fn test_post_bytes() {
#[test] #[test]
fn test_expect() { fn test_expect() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Post, method: Method::Post,
url: "http://localhost:8000/expect".to_string(), url: "http://localhost:8000/expect".to_string(),
@ -587,7 +587,7 @@ fn test_basic_authentication() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Get, method: Method::Get,
url: "http://localhost:8000/basic-authentication".to_string(), url: "http://localhost:8000/basic-authentication".to_string(),
@ -646,7 +646,7 @@ fn test_cacert() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("https://localhost:8001/hello".to_string()); let request_spec = default_get_request("https://localhost:8001/hello".to_string());
let (_, response) = client.execute(&request_spec, &logger).unwrap(); let (_, response) = client.execute(&request_spec, &logger).unwrap();
assert_eq!(response.status, 200); assert_eq!(response.status, 200);
@ -657,7 +657,7 @@ fn test_cacert() {
#[test] #[test]
fn test_error_could_not_resolve_host() { fn test_error_could_not_resolve_host() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request = default_get_request("http://unknown".to_string()); let request = default_get_request("http://unknown".to_string());
let error = client.execute(&request, &logger).err().unwrap(); let error = client.execute(&request, &logger).err().unwrap();
assert!(matches!(error, HttpError::Libcurl { .. })); assert!(matches!(error, HttpError::Libcurl { .. }));
@ -676,7 +676,7 @@ fn test_error_could_not_resolve_host() {
#[test] #[test]
fn test_error_fail_to_connect() { fn test_error_fail_to_connect() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://localhost:9999".to_string()); let request_spec = default_get_request("http://localhost:9999".to_string());
let error = client.execute(&request_spec, &logger).err().unwrap(); let error = client.execute(&request_spec, &logger).err().unwrap();
assert!(matches!(error, HttpError::Libcurl { .. })); assert!(matches!(error, HttpError::Libcurl { .. }));
@ -719,7 +719,7 @@ fn test_error_could_not_resolve_proxy_name() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://localhost:8000/hello".to_string()); let request_spec = default_get_request("http://localhost:8000/hello".to_string());
let error = client.execute(&request_spec, &logger).err().unwrap(); let error = client.execute(&request_spec, &logger).err().unwrap();
assert!(matches!(error, HttpError::Libcurl { .. })); assert!(matches!(error, HttpError::Libcurl { .. }));
@ -739,7 +739,7 @@ fn test_error_could_not_resolve_proxy_name() {
fn test_error_ssl() { fn test_error_ssl() {
let options = ClientOptions::default(); let options = ClientOptions::default();
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("https://localhost:8001/hello".to_string()); let request_spec = default_get_request("https://localhost:8001/hello".to_string());
let error = client.execute(&request_spec, &logger).err().unwrap(); let error = client.execute(&request_spec, &logger).err().unwrap();
if let HttpError::Libcurl { if let HttpError::Libcurl {
@ -769,7 +769,7 @@ fn test_timeout() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://localhost:8000/timeout".to_string()); let request_spec = default_get_request("http://localhost:8000/timeout".to_string());
let error = client.execute(&request_spec, &logger).err().unwrap(); let error = client.execute(&request_spec, &logger).err().unwrap();
assert!(matches!(error, HttpError::Libcurl { .. })); assert!(matches!(error, HttpError::Libcurl { .. }));
@ -792,7 +792,7 @@ fn test_accept_encoding() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Get, method: Method::Get,
@ -824,7 +824,7 @@ fn test_connect_timeout() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://10.0.0.0".to_string()); let request_spec = default_get_request("http://10.0.0.0".to_string());
assert_eq!( assert_eq!(
client.curl_command_line(&request_spec), client.curl_command_line(&request_spec),
@ -861,7 +861,7 @@ fn test_connect_timeout() {
#[test] #[test]
fn test_cookie() { fn test_cookie() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Get, method: Method::Get,
url: "http://localhost:8000/cookies/set-request-cookie1-valueA".to_string(), url: "http://localhost:8000/cookies/set-request-cookie1-valueA".to_string(),
@ -910,7 +910,7 @@ fn test_cookie() {
#[test] #[test]
fn test_multiple_request_cookies() { fn test_multiple_request_cookies() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = RequestSpec { let request_spec = RequestSpec {
method: Method::Get, method: Method::Get,
url: "http://localhost:8000/cookies/set-multiple-request-cookies".to_string(), url: "http://localhost:8000/cookies/set-multiple-request-cookies".to_string(),
@ -952,7 +952,7 @@ fn test_multiple_request_cookies() {
#[test] #[test]
fn test_cookie_storage() { fn test_cookie_storage() {
let mut client = default_client(); let mut client = default_client();
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = let request_spec =
default_get_request("http://localhost:8000/cookies/set-session-cookie2-valueA".to_string()); default_get_request("http://localhost:8000/cookies/set-session-cookie2-valueA".to_string());
let (request, response) = client.execute(&request_spec, &logger).unwrap(); let (request, response) = client.execute(&request_spec, &logger).unwrap();
@ -997,7 +997,7 @@ fn test_cookie_file() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request( let request_spec = default_get_request(
"http://localhost:8000/cookies/assert-that-cookie2-is-valueA".to_string(), "http://localhost:8000/cookies/assert-that-cookie2-is-valueA".to_string(),
); );
@ -1032,7 +1032,7 @@ fn test_proxy() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
let request_spec = default_get_request("http://localhost:8000/proxy".to_string()); let request_spec = default_get_request("http://localhost:8000/proxy".to_string());
assert_eq!( assert_eq!(
client.curl_command_line(&request_spec), client.curl_command_line(&request_spec),
@ -1052,7 +1052,7 @@ fn test_insecure() {
..Default::default() ..Default::default()
}; };
let mut client = Client::init(options); let mut client = Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, "", "");
assert_eq!(client.options.curl_args(), vec!["--insecure".to_string()]); assert_eq!(client.options.curl_args(), vec!["--insecure".to_string()]);
let request_spec = default_get_request("https://localhost:8001/hello".to_string()); let request_spec = default_get_request("https://localhost:8001/hello".to_string());
assert_eq!( assert_eq!(

View File

@ -35,7 +35,7 @@ fn test_hurl_file() {
let variables = HashMap::new(); let variables = HashMap::new();
let options = http::ClientOptions::default(); let options = http::ClientOptions::default();
let mut client = http::Client::init(options); let mut client = http::Client::init(options);
let logger = Logger::default(); let logger = Logger::new(false, false, filename, &content);
let options = RunnerOptions { let options = RunnerOptions {
fail_fast: false, fail_fast: false,
@ -48,14 +48,7 @@ fn test_hurl_file() {
post_entry: || true, post_entry: || true,
}; };
let _hurl_log = runner::run( let _hurl_log = runner::run(&hurl_file, filename, &mut client, &options, &logger);
&hurl_file,
filename,
&content,
&mut client,
&options,
&logger,
);
} }
#[cfg(test)] #[cfg(test)]
@ -123,12 +116,14 @@ fn hello_request() -> Request {
fn test_hello() { fn test_hello() {
let options = http::ClientOptions::default(); let options = http::ClientOptions::default();
let mut client = http::Client::init(options); let mut client = http::Client::init(options);
let logger = Logger::default();
// We construct a Hurl file ast "by hand", with fake source info. // We construct a Hurl file ast "by hand", with fake source info.
// In this particular case, the raw content is empty as the Hurl file hasn't // In this particular case, the raw content is empty as the Hurl file hasn't
// been built from a text content. // been built from a text content.
let content = ""; let content = "";
let filename = "filename";
let logger = Logger::new(false, false, filename, content);
let source_info = SourceInfo { let source_info = SourceInfo {
start: Pos { line: 1, column: 1 }, start: Pos { line: 1, column: 1 },
end: Pos { line: 1, column: 1 }, end: Pos { line: 1, column: 1 },
@ -178,12 +173,5 @@ fn test_hello() {
post_entry: || true, post_entry: || true,
}; };
runner::run( runner::run(&hurl_file, "filename", &mut client, &options, &logger);
&hurl_file,
"filename",
content,
&mut client,
&options,
&logger,
);
} }