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

feat(test_utils): Add custom-headers and custom delay support to rustman #2636

Merged
merged 19 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/test_utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Optional fields:
- Use double quotes to specify folder name. If you wish to run multiple folders, separate them with a comma (`,`)
- Example: `--folder "QuickStart"` or `--folder "Health check,QuickStart"`
- `--verbose` -- A boolean to print detailed logs (requests and responses)
- `--custom_headers` -- If you wish to add custom headers to the requests, you can pass them as a string
- Example: `--custom_headers "key1=value,key2=value"`

**Note:** Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository.

Expand Down
29 changes: 27 additions & 2 deletions crates/test_utils/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ use std::process::{exit, Command};
use test_utils::newman_runner;

fn main() {
let mut newman_command: Command = newman_runner::command_generate();
let mut runner: (Command, bool, String) = newman_runner::command_generate();
pixincreate marked this conversation as resolved.
Show resolved Hide resolved

// Execute the newman command
let output = newman_command.spawn();
let output = runner.0.spawn();
let mut child = match output {
Ok(child) => child,
Err(err) => {
Expand All @@ -16,6 +16,31 @@ fn main() {
};
let status = child.wait();

if runner.1 {
let mut cmd = Command::new("git");
let output = cmd
.args([
"checkout",
"HEAD",
"--",
format!("{}/event.prerequest.js", runner.2).as_str(),
])
.output();

match output {
Ok(output) => {
if output.status.success() {
let _ = String::from_utf8_lossy(&output.stdout);
} else {
let _ = String::from_utf8_lossy(&output.stderr);
}
}
Err(e) => {
println!("Error: {}", e);
}
}
}

let exit_code = match status {
Ok(exit_status) => {
if exit_status.success() {
Expand Down
69 changes: 64 additions & 5 deletions crates/test_utils/src/newman_runner.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
use std::{env, process::Command};
use std::{
env,
fs::OpenOptions,
io::{self, Write},
process::Command,
};

use clap::{arg, command, Parser};
use masking::PeekInterface;

use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap};

#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
struct Args {
Expand All @@ -17,6 +21,13 @@ struct Args {
/// Name of the connector
#[arg(short, long = "connector_name")]
connector_name: String,
/// Custom headers
#[arg(long = "custom_headers")]
custom_headers: Option<String>,
/// Minimum delay to be added before sending a request
/// By default, 7 milliseconds will be the delay
#[arg(short, long = "delay_request", default_value_t = 7)]
delay_request: u32,
/// Folder name of specific tests
#[arg(short, long = "folder")]
folders: Option<String>,
Expand All @@ -32,7 +43,25 @@ fn get_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}

pub fn command_generate() -> Command {
// This function currently allows you to add only custom headers.
// In future, as we scale, this can be modified based on the need
fn insert_content(dir: &String, content_to_insert: &str) -> io::Result<bool> {
let file_name = "event.prerequest.js";
pixincreate marked this conversation as resolved.
Show resolved Hide resolved
let file_path = format!("{}/{}", dir, file_name);

// Open the file in write mode or create it if it doesn't exist
let mut file = OpenOptions::new()
.write(true)
.create(true)
.open(file_path)?;

pixincreate marked this conversation as resolved.
Show resolved Hide resolved
// Write the content to the file
file.write_all(content_to_insert.as_bytes())?;

Ok(true)
}

pub fn command_generate() -> (Command, bool, String) {
let args = Args::parse();

let connector_name = args.connector_name;
Expand Down Expand Up @@ -129,7 +158,10 @@ pub fn command_generate() -> Command {
]);
}

newman_command.arg("--delay-request").arg("7"); // 7 milli seconds delay
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);

newman_command.arg("--color").arg("on");

Expand All @@ -151,5 +183,32 @@ pub fn command_generate() -> Command {
newman_command.arg("--verbose");
}

newman_command
let mut modified = false;
if args.custom_headers.is_some() {
if let Some(headers) = &args.custom_headers {
let individual_headers: Vec<String> =
headers.split(',').map(|s| s.trim().to_string()).collect();

let mut content_to_insert = String::new();

for (index, header) in individual_headers.iter().enumerate() {
let kv_pair: Vec<&str> = header.splitn(2, '=').collect();
pixincreate marked this conversation as resolved.
Show resolved Hide resolved

content_to_insert.push_str(&format!(
"pm.request.headers.add({{key: \"{}\", value: \"{}\"}});",
kv_pair[0], kv_pair[1]
));
pixincreate marked this conversation as resolved.
Show resolved Hide resolved

if index < individual_headers.len() - 1 {
content_to_insert.push('\n'); // Add a newline between headers
}
}
pixincreate marked this conversation as resolved.
Show resolved Hide resolved

if insert_content(&collection_path, &content_to_insert).is_ok() {
modified = true;
}
}
}

(newman_command, modified, collection_path)
}
Loading