use std::sync::LazyLock;
use regex::Regex;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use crate::hurl::{
CommentAnchor, EntryComment, FormField, FormFieldKind, HurlEntry, KvRow, parse_hurl,
};
#[derive(Deserialize, Default)]
#[serde(default)]
struct Collection {
item: Vec<Item>,
variable: Vec<Param>,
auth: Option<Auth>,
#[serde(rename = "protocolProfileBehavior")]
protocol_profile_behavior: Option<Profile>,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct Item {
#[serde(deserialize_with = "de_str")]
name: String,
item: Option<Vec<Item>>,
request: Option<Request>,
auth: Option<Auth>,
event: Vec<Event>,
#[serde(rename = "protocolProfileBehavior")]
protocol_profile_behavior: Option<Profile>,
}
#[derive(Clone, Copy, Default, Deserialize)]
#[serde(default)]
struct Profile {
#[serde(rename = "disableBodyPruning")]
disable_body_pruning: Option<bool>,
#[serde(rename = "strictSSL")]
strict_ssl: Option<bool>,
}
impl Profile {
fn over(self, parent: Profile) -> Profile {
Profile {
disable_body_pruning: self.disable_body_pruning.or(parent.disable_body_pruning),
strict_ssl: self.strict_ssl.or(parent.strict_ssl),
}
}
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct Event {
#[serde(deserialize_with = "de_str")]
listen: String,
script: Script,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct Script {
exec: Vec<String>,
}
#[derive(Deserialize)]
struct Request {
#[serde(default = "get_method", deserialize_with = "de_method")]
method: String,
#[serde(default, deserialize_with = "de_url")]
url: Url,
#[serde(default)]
header: Vec<Param>,
auth: Option<Auth>,
body: Option<Body>,
#[serde(default, deserialize_with = "de_description")]
description: String,
}
fn de_description<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
Ok(match Value::deserialize(d)? {
Value::String(s) => s,
Value::Object(m) => m
.get("content")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
_ => String::new(),
})
}
fn get_method() -> String {
"GET".to_string()
}
fn de_method<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let m = de_str(d)?;
Ok(if m.trim().is_empty() { get_method() } else { m })
}
#[derive(Default)]
struct Url {
raw: String,
fragment: String,
variables: Vec<Param>,
queries: Vec<Param>,
}
fn join_parts(v: Option<&Value>, sep: &str) -> String {
match v {
Some(Value::Array(parts)) => parts
.iter()
.map(|p| match p {
Value::String(s) => s.clone(),
Value::Object(o) => o
.get("value")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
other => other.as_str().unwrap_or_default().to_string(),
})
.filter(|p| !p.is_empty())
.collect::<Vec<_>>()
.join(sep),
Some(Value::String(s)) => s.clone(),
_ => String::new(),
}
}
fn url_from_parts(m: &serde_json::Map<String, Value>) -> String {
let host = join_parts(m.get("host"), ".");
if host.is_empty() {
return String::new();
}
let mut url = String::new();
let protocol = m.get("protocol").and_then(Value::as_str).unwrap_or("");
if !protocol.is_empty() {
url.push_str(protocol);
url.push_str("://");
}
url.push_str(&host);
if let Some(port) = m
.get("port")
.and_then(Value::as_str)
.filter(|p| !p.is_empty())
{
url.push(':');
url.push_str(port);
}
let path = join_parts(m.get("path"), "/");
if !path.is_empty() {
if !path.starts_with('/') {
url.push('/');
}
url.push_str(&path);
}
url
}
fn merge_enabled_queries(raw: &str, queries: &[Param]) -> String {
let existing: Vec<&str> = raw
.split_once('?')
.map(|(_, q)| {
q.split('&')
.map(|p| p.split_once('=').map_or(p, |(k, _)| k))
.collect()
})
.unwrap_or_default();
let missing: Vec<String> = queries
.iter()
.filter(|q| !q.disabled && !q.key.trim().is_empty())
.filter(|q| !existing.contains(&q.key.as_str()))
.map(|q| {
if q.value.is_empty() {
q.key.clone()
} else {
format!("{}={}", q.key, q.value)
}
})
.collect();
if missing.is_empty() {
return raw.to_string();
}
let sep = if raw.contains('?') { '&' } else { '?' };
format!("{raw}{sep}{}", missing.join("&"))
}
fn de_url<'de, D: Deserializer<'de>>(d: D) -> Result<Url, D::Error> {
Ok(match Value::deserialize(d)? {
Value::String(s) => {
let (raw, fragment) = split_fragment(&s);
Url {
raw,
fragment,
variables: Vec::new(),
queries: Vec::new(),
}
}
Value::Object(m) => Url {
raw: String::new(),
fragment: String::new(),
variables: m
.get("variable")
.cloned()
.and_then(|v| serde_json::from_value::<Vec<Param>>(v).ok())
.unwrap_or_default(),
queries: m
.get("query")
.cloned()
.and_then(|v| serde_json::from_value::<Vec<Param>>(v).ok())
.unwrap_or_default(),
}
.with_raw_from(&m),
_ => Url::default(),
})
}
fn split_fragment(url: &str) -> (String, String) {
match url.find('#') {
Some(0) | None => (url.to_string(), String::new()),
Some(i) => (url[..i].to_string(), url[i..].to_string()),
}
}
impl Url {
fn with_raw_from(mut self, m: &serde_json::Map<String, Value>) -> Self {
let raw = m.get("raw").and_then(Value::as_str).unwrap_or("").trim();
let base = if raw.is_empty() {
url_from_parts(m)
} else {
raw.to_string()
};
let (kept, fragment) = split_fragment(&merge_enabled_queries(&base, &self.queries));
self.raw = kept;
self.fragment = fragment;
self
}
}
#[derive(Clone, Deserialize, Default)]
#[serde(default)]
struct Auth {
#[serde(rename = "type", deserialize_with = "de_str")]
kind: String,
basic: Vec<Param>,
bearer: Vec<Param>,
apikey: Vec<Param>,
oauth2: Vec<Param>,
awsv4: Vec<Param>,
}
impl Auth {
fn field(list: &[Param], name: &str) -> String {
list.iter()
.find(|p| p.key == name)
.map(|p| p.value.clone())
.unwrap_or_default()
}
fn is_noauth(&self) -> bool {
self.kind == "noauth"
}
fn inherits(&self) -> bool {
self.kind == "inherit" || self.kind.is_empty()
}
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct Body {
#[serde(deserialize_with = "de_str")]
mode: String,
#[serde(deserialize_with = "de_str")]
raw: String,
urlencoded: Vec<Param>,
formdata: Vec<Param>,
file: FileBody,
graphql: GraphQl,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct FileBody {
#[serde(deserialize_with = "de_str")]
src: String,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct GraphQl {
#[serde(deserialize_with = "de_str")]
query: String,
#[serde(deserialize_with = "de_json_str")]
variables: String,
}
#[derive(Clone, Deserialize, Default)]
#[serde(default)]
struct Param {
#[serde(deserialize_with = "de_str")]
key: String,
#[serde(deserialize_with = "de_str")]
value: String,
disabled: bool,
#[serde(rename = "type", deserialize_with = "de_str")]
kind: String,
#[serde(deserialize_with = "de_str")]
src: String,
#[serde(rename = "contentType")]
content_type: Option<String>,
#[serde(default, deserialize_with = "de_str")]
description: String,
}
fn de_json_str<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
Ok(match Value::deserialize(d)? {
Value::String(s) => s,
v @ (Value::Object(_) | Value::Array(_)) => v.to_string(),
Value::Null => String::new(),
other => other.to_string(),
})
}
fn de_str<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
Ok(match Value::deserialize(d)? {
Value::String(s) => s,
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
Value::Null | Value::Array(_) | Value::Object(_) => String::new(),
})
}
impl Param {
fn enabled_kve(&self) -> Option<KvRow> {
(!self.key.is_empty()).then(|| KvRow {
key: self.key.clone(),
value: self.value.clone(),
enabled: !self.disabled,
desc: self.description.clone(),
})
}
fn form_field(&self) -> Option<FormField> {
if self.disabled || self.key.is_empty() {
return None;
}
Some(if self.kind == "file" {
FormField {
key: self.key.clone(),
value: self.src.clone(),
kind: FormFieldKind::File,
content_type: self.content_type.clone(),
enabled: !self.src.trim().is_empty(),
desc: self.description.clone(),
base64_prefix: None,
}
} else {
FormField {
key: self.key.clone(),
value: self.value.clone(),
kind: FormFieldKind::Text,
content_type: None,
base64_prefix: None,
enabled: true,
desc: self.description.clone(),
}
})
}
}
fn unwrap_envelope(v: Value, key: &str, marker: &str) -> Value {
match v {
Value::Object(mut m) => match m.remove(key) {
Some(inner @ Value::Object(_)) if inner.get(marker).is_some() => inner,
other => {
if let Some(other) = other {
m.insert(key.to_string(), other);
}
Value::Object(m)
}
},
other => other,
}
}
pub fn looks_like_postman(content: &str) -> bool {
serde_json::from_str::<Value>(content)
.map(|v| unwrap_envelope(v, "collection", "item"))
.map(|v| v.get("info").is_some() && v.get("item").is_some())
.unwrap_or(false)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportKind {
Collection,
Environment,
}
pub fn export_kind(content: &str) -> Option<ExportKind> {
if looks_like_postman(content) {
Some(ExportKind::Collection)
} else if postman_env_values(content).is_some() {
Some(ExportKind::Environment)
} else {
None
}
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct PostmanEnv {
values: Vec<EnvValue>,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct EnvValue {
#[serde(deserialize_with = "de_str")]
key: String,
#[serde(deserialize_with = "de_str")]
value: String,
enabled: Option<bool>,
}
pub fn postman_env_values(content: &str) -> Option<Vec<(String, String)>> {
let v = serde_json::from_str::<Value>(content).ok()?;
let v = unwrap_envelope(v, "environment", "values");
if !v.get("values").is_some_and(Value::is_array) || v.get("item").is_some() {
return None;
}
let env = serde_json::from_value::<PostmanEnv>(v).ok()?;
Some(
env.values
.into_iter()
.filter(|v| v.enabled.unwrap_or(true) && !v.key.trim().is_empty())
.map(|v| {
let value = v.value.replace(['\n', '\r'], " ");
(v.key.trim().to_string(), value.trim().to_string())
})
.collect(),
)
}
pub fn parse_collection(content: &str) -> Vec<HurlEntry> {
if looks_like_postman(content) {
import_postman(content)
} else {
parse_hurl(content)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversionNote {
pub item: String,
pub detail: String,
}
#[derive(Debug, Default)]
pub struct ConvertedCollection {
pub entries: Vec<HurlEntry>,
pub variables: Vec<(String, String)>,
pub notes: Vec<ConversionNote>,
}
pub fn import_postman(content: &str) -> Vec<HurlEntry> {
convert_postman(content).entries
}
pub fn convert_postman(content: &str) -> ConvertedCollection {
let root = match serde_json::from_str::<Value>(content)
.map(|v| unwrap_envelope(v, "collection", "item"))
.and_then(serde_json::from_value::<Collection>)
{
Ok(root) => root,
Err(e) => {
return ConvertedCollection {
notes: vec![ConversionNote {
item: String::new(),
detail: format!("collection could not be read: {e}"),
}],
..ConvertedCollection::default()
};
}
};
let mut out = ConvertedCollection {
variables: root
.variable
.iter()
.filter(|v| !v.disabled && !v.key.trim().is_empty())
.map(|v| {
(
v.key.trim().to_string(),
v.value.replace(['\n', '\r'], " ").trim().to_string(),
)
})
.collect(),
..ConvertedCollection::default()
};
let inherited = root.auth.as_ref().filter(|a| !a.inherits());
let mut tokens = OAuthTokens::default();
walk_items(
&root.item,
&mut Vec::new(),
inherited,
&[],
root.protocol_profile_behavior.unwrap_or_default(),
&mut tokens,
&mut out,
);
out
}
fn walk_items(
items: &[Item],
path: &mut Vec<String>,
inherited: Option<&Auth>,
auth_path: &[String],
profile: Profile,
tokens: &mut OAuthTokens,
out: &mut ConvertedCollection,
) {
for it in items {
if let Some(sub) = &it.item {
let here = resolve_auth(it.auth.as_ref(), inherited);
let declares_own = it.auth.as_ref().is_some_and(|a| !a.inherits());
path.push(it.name.clone());
let here_path = if declares_own {
path.clone()
} else {
auth_path.to_vec()
};
let here_profile = it
.protocol_profile_behavior
.unwrap_or_default()
.over(profile);
walk_items(sub, path, here, &here_path, here_profile, tokens, out);
path.pop();
} else if let Some(req) = &it.request {
let title = if path.is_empty() {
it.name.clone()
} else {
format!("{}/{}", path.join("/"), it.name)
};
let auth = resolve_auth(req.auth.as_ref(), inherited);
let declares_own = req.auth.as_ref().is_some_and(|a| !a.inherits());
let token_path: &[String] = if declares_own { path } else { auth_path };
let profile = it
.protocol_profile_behavior
.unwrap_or_default()
.over(profile);
let mut entry = map_request(&title, req, &it.event, auth, profile);
apply_path_variables(&title, &req.url, &mut entry, out);
apply_oauth2(&title, token_path, auth, &mut entry, tokens, out);
note_losses(&title, req, &it.event, auth, profile, &entry, out);
for name in rename_dynamic_variables(&mut entry) {
out.notes.push(ConversionNote {
item: title.clone(),
detail: format!(
"Postman generated `{{{{${name}}}}}` for you; Hurl has no equivalent, so it \
became the variable `{{{{{name}}}}}`, which has to be supplied"
),
});
}
out.entries.push(entry);
}
}
}
struct OAuth2 {
access_token_url: String,
grant_type: String,
client_id: String,
client_secret: String,
username: String,
password: String,
scope: String,
client_authentication: String,
header_prefix: String,
add_token_to: String,
}
impl OAuth2 {
fn read(auth: &Auth) -> Self {
let f = |name: &str| Auth::field(&auth.oauth2, name);
let prefix = match (f("headerPrefix"), f("tokenType")) {
(p, _) if !p.trim().is_empty() => p,
(_, t) if !t.trim().is_empty() => format!("{} ", t.trim()),
_ => "Bearer ".to_string(),
};
OAuth2 {
access_token_url: f("accessTokenUrl"),
grant_type: f("grant_type"),
client_id: f("clientId"),
client_secret: f("clientSecret"),
username: f("username"),
password: f("password"),
scope: f("scope"),
client_authentication: f("client_authentication"),
header_prefix: prefix,
add_token_to: f("addTokenTo"),
}
}
fn identity(&self) -> String {
format!(
"{}|{}|{}|{}|{}|{}|{}|{}",
self.access_token_url,
self.grant_type,
self.client_id,
self.client_secret,
self.username,
self.password,
self.scope,
self.client_authentication
)
}
}
#[derive(Default)]
struct OAuthTokens {
issued: Vec<(String, String)>,
}
impl OAuthTokens {
fn var_for(&self, identity: &str) -> Option<&str> {
self.issued
.iter()
.find(|(id, _)| id == identity)
.map(|(_, var)| var.as_str())
}
fn next_var(&self, taken: &[(String, String)]) -> String {
let used = |name: &str| {
taken.iter().any(|(k, _)| k == name) || self.issued.iter().any(|(_, v)| v == name)
};
if self.issued.is_empty() && !used("access_token") {
return "access_token".to_string();
}
let mut n = self.issued.len().max(1);
loop {
n += 1;
let candidate = format!("access_token_{n}");
if !used(&candidate) {
return candidate;
}
}
}
}
fn apply_oauth2(
title: &str,
path: &[String],
auth: Option<&Auth>,
entry: &mut HurlEntry,
tokens: &mut OAuthTokens,
out: &mut ConvertedCollection,
) {
let Some(auth) = auth.filter(|a| a.kind == "oauth2") else {
return;
};
let cfg = OAuth2::read(auth);
let mut note = |detail: String| {
out.notes.push(ConversionNote {
item: title.to_string(),
detail,
})
};
let already_authorized = if cfg.add_token_to == "queryParams" {
entry.queries.iter().any(|q| q.key == "access_token")
} else {
entry
.headers
.iter()
.any(|h| h.key.eq_ignore_ascii_case("authorization"))
};
if already_authorized {
note(
"this request sets its own Authorization, so the folder's OAuth 2 token was not \
added on top of it"
.into(),
);
return;
}
let var = if cfg.access_token_url.trim().is_empty() {
match tokens.issued.last() {
Some((_, var)) => var.clone(),
None => {
note(
"OAuth 2 auth with no token URL — Postman was holding a token it fetched \
elsewhere, which an export can't carry, so this request has no credentials"
.into(),
);
return;
}
}
} else if !matches!(cfg.grant_type.as_str(), "client_credentials" | "password") {
note(format!(
"the OAuth 2 `{}` grant needs a browser redirect, which a file of requests can't \
perform — fetch a token by hand and put it in a variable",
cfg.grant_type
));
return;
} else {
let identity = cfg.identity();
match tokens.var_for(&identity) {
Some(var) => var.to_string(),
None => {
let var = tokens.next_var(&out.variables);
let (token_entry, missing) = token_request(&cfg, &var, path);
if missing {
note(
"Postman keeps OAuth 2 client credentials outside the export, so the \
generated token request refers to `{{oauth_client_id}}` and \
`{{oauth_client_secret}}` — fill them in alongside the collection"
.into(),
);
}
out.entries.push(token_entry);
tokens.issued.push((identity, var.clone()));
var
}
}
};
if cfg.add_token_to == "queryParams" {
entry
.queries
.push(KvRow::new("access_token", format!("{{{{{var}}}}}")));
} else {
entry.headers.push(KvRow::new(
"Authorization",
format!("{}{{{{{var}}}}}", cfg.header_prefix),
));
}
}
fn token_request(cfg: &OAuth2, var: &str, path: &[String]) -> (HurlEntry, bool) {
let missing = cfg.client_id.trim().is_empty() && cfg.client_secret.trim().is_empty();
let (id, secret) = if missing {
(
"{{oauth_client_id}}".to_string(),
"{{oauth_client_secret}}".to_string(),
)
} else {
(cfg.client_id.clone(), cfg.client_secret.clone())
};
let mut form: Vec<FormField> = Vec::new();
let mut text = |key: &str, value: String| {
form.push(FormField {
key: key.to_string(),
value,
kind: FormFieldKind::Text,
content_type: None,
base64_prefix: None,
enabled: true,
desc: String::new(),
})
};
text("grant_type", cfg.grant_type.clone());
if !cfg.scope.trim().is_empty() {
text("scope", cfg.scope.clone());
}
if cfg.grant_type == "password" {
text("username", cfg.username.clone());
text("password", cfg.password.clone());
}
let basic_auth = if cfg.client_authentication == "body" {
text("client_id", id);
text("client_secret", secret);
None
} else {
Some((id, secret))
};
let title = if path.is_empty() {
"Get access token".to_string()
} else {
format!("{}/Get access token", path.join("/"))
};
let entry = HurlEntry {
title,
method: "POST".to_string(),
url: cfg.access_token_url.clone(),
form_fields: form,
basic_auth,
expected_status: Some(200),
captures: vec![(var.to_string(), "jsonpath \"$.access_token\"".to_string())],
..Default::default()
};
(entry, missing)
}
fn apply_path_variables(
title: &str,
url: &Url,
entry: &mut HurlEntry,
out: &mut ConvertedCollection,
) {
let declared: Vec<&Param> = url
.variables
.iter()
.filter(|v| !v.disabled && !v.key.trim().is_empty())
.collect();
if declared.is_empty() {
return;
}
let (path, query) = match entry.url.split_once('?') {
Some((p, q)) => (p.to_string(), Some(q.to_string())),
None => (entry.url.clone(), None),
};
let rewritten: Vec<String> = path
.split('/')
.map(|seg| match seg.strip_prefix(':') {
Some(name) if declared.iter().any(|v| v.key.trim() == name) => {
format!("{{{{{name}}}}}")
}
_ => seg.to_string(),
})
.collect();
entry.url = match query {
Some(q) => format!("{}?{}", rewritten.join("/"), q),
None => rewritten.join("/"),
};
for var in declared {
let key = var.key.trim().to_string();
let value = var.value.replace(['\n', '\r'], " ").trim().to_string();
match out.variables.iter().find(|(k, _)| *k == key) {
Some((_, existing)) if *existing != value && !value.is_empty() => {
out.notes.push(ConversionNote {
item: title.to_string(),
detail: format!(
"the path variable `{key}` is declared here as `{value}` but is already \
`{existing}` — a `.vars` file holds one value per name, so the first was \
kept"
),
});
}
Some(_) => {}
None => out.variables.push((key, value)),
}
}
}
fn rename_dynamic_variables(entry: &mut HurlEntry) -> Vec<String> {
static DYNAMIC_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\{\{\s*\$([A-Za-z_][A-Za-z0-9_.]*)\s*\}\}").unwrap());
let mut found: Vec<String> = Vec::new();
let mut fix = |text: &mut String| {
if !text.contains("{{") {
return;
}
let replaced = DYNAMIC_RE.replace_all(text, |caps: ®ex::Captures| {
let name = caps[1].replace('.', "_");
if !found.contains(&name) {
found.push(name.clone());
}
format!("{{{{{name}}}}}")
});
if let std::borrow::Cow::Owned(new) = replaced {
*text = new;
}
};
fix(&mut entry.url);
for row in entry
.headers
.iter_mut()
.chain(entry.queries.iter_mut())
.chain(entry.cookies.iter_mut())
{
fix(&mut row.value);
}
for f in &mut entry.form_fields {
fix(&mut f.value);
}
if let Some(body) = entry.body_src.as_mut() {
fix(body);
}
if let Some((user, pass)) = entry.basic_auth.as_mut() {
fix(user);
fix(pass);
}
found
}
fn non_empty(value: String, fallback: &str) -> String {
if value.trim().is_empty() {
fallback.to_string()
} else {
value
}
}
fn resolve_auth<'a>(own: Option<&'a Auth>, inherited: Option<&'a Auth>) -> Option<&'a Auth> {
match own {
Some(a) if a.is_noauth() => None,
Some(a) if !a.inherits() => Some(a),
_ => inherited,
}
}
fn note_losses(
title: &str,
req: &Request,
events: &[Event],
auth: Option<&Auth>,
profile: Profile,
entry: &HurlEntry,
out: &mut ConvertedCollection,
) {
let mut note = |detail: String| {
out.notes.push(ConversionNote {
item: title.to_string(),
detail,
})
};
if let Some(auth) = auth
&& !matches!(
auth.kind.as_str(),
"basic" | "bearer" | "apikey" | "oauth2" | "awsv4"
)
{
note(format!(
"auth type `{}` has no Hurl equivalent and was dropped",
auth.kind
));
}
if let Some(auth) = auth
&& auth.kind == "awsv4"
&& Auth::field(&auth.awsv4, "accessKey").trim().is_empty()
{
note(
"AWS auth carried no keys — real exports keep them in variables or outside the file \
— so the request signs with `{{aws_access_key_id}}` and `{{aws_secret_access_key}}`"
.into(),
);
}
if !req.url.fragment.is_empty() {
note(format!(
"the URL fragment `{}` was left off: a fragment is never sent to the server (Postman \
doesn't send it either), and a `#` on the request line would comment out the rest \
of the URL",
req.url.fragment
));
}
if let Some(auth) = auth
&& auth.kind == "apikey"
&& Auth::field(&auth.apikey, "in") == "query"
{
note("API-key auth is sent in the query string; it was added as a query parameter".into());
}
let pruned =
matches!(req.method.as_str(), "GET" | "HEAD") && profile.disable_body_pruning != Some(true);
if let Some(b) = &req.body
&& pruned
&& !(b.raw.is_empty() && b.mode.is_empty())
{
note(format!(
"the stored {} body was left out, because Postman would not have sent it on a {} \
either — nothing turned its body pruning off",
if b.mode.is_empty() {
"request"
} else {
&b.mode
},
req.method
));
} else if let Some(b) = &req.body {
match b.mode.as_str() {
"" | "raw" | "urlencoded" | "formdata" => {}
"file" if b.file.src.trim().is_empty() => note(
"the body is a file, and Postman never had one chosen — attach it here instead"
.into(),
),
"file" => note(format!(
"the body was the file `{}`; attach it here instead, as PaperBoy sends file \
bodies as form or multipart parts rather than as the whole body",
b.file.src.trim()
)),
"graphql" if b.graphql.query.trim().is_empty() => {
note("the GraphQL body held no query, so there was nothing to send".into())
}
"graphql" => {}
mode => note(format!("body mode `{mode}` was dropped")),
}
}
for f in &entry.form_fields {
if f.kind == FormFieldKind::File && !f.enabled {
note(format!(
"the file part `{}` had no file chosen in Postman, so it is switched off until one is",
f.key
));
}
}
if events
.iter()
.any(|e| e.listen == "prerequest" && !e.script.exec.is_empty())
{
note("a pre-request script was dropped — Hurl has no equivalent".into());
}
let has_tests = events
.iter()
.any(|e| e.listen == "test" && !e.script.exec.is_empty());
if has_tests && entry.captures.is_empty() {
note("a test script was dropped — nothing in it reduced to a [Captures] entry".into());
} else if has_tests {
note("a test script was read for [Captures] only; its assertions were dropped".into());
}
}
fn map_request(
name: &str,
req: &Request,
events: &[Event],
auth: Option<&Auth>,
profile: Profile,
) -> HurlEntry {
let mut headers: Vec<KvRow> = req.header.iter().filter_map(Param::enabled_kve).collect();
let mut queries: Vec<KvRow> = Vec::new();
let mut options: Vec<KvRow> = Vec::new();
let mut basic_auth = None;
if let Some(auth) = auth {
match auth.kind.as_str() {
"basic" => {
let u = Auth::field(&auth.basic, "username");
let p = Auth::field(&auth.basic, "password");
if !u.is_empty() || !p.is_empty() {
basic_auth = Some((u, p));
}
}
"bearer" => {
let t = Auth::field(&auth.bearer, "token");
if !t.is_empty() {
headers.push(KvRow::new("Authorization", format!("Bearer {t}")));
}
}
"apikey" => {
let key = Auth::field(&auth.apikey, "key");
let value = Auth::field(&auth.apikey, "value");
if !key.is_empty() {
let row = KvRow::new(key, value);
if Auth::field(&auth.apikey, "in") == "query" {
queries.push(row);
} else {
headers.push(row);
}
}
}
"awsv4" => {
let f = |name: &str| Auth::field(&auth.awsv4, name);
let mut provider = "aws:amz".to_string();
let (region, service) = (f("region"), f("service"));
if !region.trim().is_empty() {
provider.push(':');
provider.push_str(region.trim());
if !service.trim().is_empty() {
provider.push(':');
provider.push_str(service.trim());
}
}
options.push(KvRow::new("aws-sigv4", provider));
let key = non_empty(f("accessKey"), "{{aws_access_key_id}}");
let secret = non_empty(f("secretKey"), "{{aws_secret_access_key}}");
options.push(KvRow::new("user", format!("{key}:{secret}")));
let session = f("sessionToken");
if !session.trim().is_empty() {
headers.push(KvRow::new("x-amz-security-token", session));
}
}
_ => {}
}
}
let mut form_fields = Vec::new();
let mut body = String::new();
let pruned =
matches!(req.method.as_str(), "GET" | "HEAD") && profile.disable_body_pruning != Some(true);
if let Some(b) = &req.body.as_ref().filter(|_| !pruned) {
match b.mode.as_str() {
"raw" => body = b.raw.clone(),
"urlencoded" => {
form_fields = b.urlencoded.iter().filter_map(Param::form_field).collect()
}
"formdata" => form_fields = b.formdata.iter().filter_map(Param::form_field).collect(),
"graphql" if !b.graphql.query.trim().is_empty() => {
let mut doc = serde_json::Map::new();
doc.insert("query".into(), Value::String(b.graphql.query.clone()));
if let Ok(vars) = serde_json::from_str::<Value>(&b.graphql.variables)
&& !vars.is_null()
{
doc.insert("variables".into(), vars);
}
body = serde_json::to_string_pretty(&Value::Object(doc)).unwrap_or_default();
if !headers
.iter()
.any(|h| h.key.eq_ignore_ascii_case("content-type"))
{
headers.push(KvRow::new("Content-Type", "application/json"));
}
}
_ => {}
}
}
let mut entry = HurlEntry::from_fields(name, &req.method, &req.url.raw, headers, &body);
entry.basic_auth = basic_auth;
entry.form_fields = form_fields;
entry.queries.extend(
req.url
.queries
.iter()
.filter(|q| q.disabled)
.filter_map(Param::enabled_kve),
);
entry.queries.extend(queries);
entry.comments.extend(
req.description
.replace("\r\n", "\n")
.lines()
.map(|line| EntryComment {
anchor: CommentAnchor::Headers,
text: if line.trim().is_empty() {
"#".to_string()
} else {
format!("# {}", line.trim_end())
},
}),
);
entry.options.extend(options);
if profile.strict_ssl == Some(false) {
entry.options.push(KvRow::new("insecure", "true"));
}
entry.captures = captures_from_events(events);
entry
}
static JSON_VAR_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?:var|let|const)\s+(\w+)\s*=\s*pm\.response\.json\s*\(\s*\)").unwrap()
});
static SET_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r#"pm\.(?:environment|collectionVariables|globals|variables)\.set\(\s*['"]([^'"]+)['"]\s*,\s*([^)]+)\)"#,
)
.unwrap()
});
fn captures_from_events(events: &[Event]) -> Vec<(String, String)> {
let script = events
.iter()
.filter(|e| e.listen == "test")
.flat_map(|e| e.script.exec.iter())
.map(|l| l.trim_end_matches('\r'))
.collect::<Vec<_>>()
.join("\n");
if script.is_empty() {
return Vec::new();
}
let (code, in_string) = strip_js_noise(&script);
let mut roots: Vec<String> = JSON_VAR_RE
.captures_iter(&code)
.map(|c| c[1].to_string())
.collect();
if roots.is_empty() {
roots.push("jsonData".to_string());
}
SET_RE
.captures_iter(&code)
.filter(|c| {
c.get(0)
.is_some_and(|m| !in_string.get(m.start()).copied().unwrap_or(false))
})
.filter_map(|c| {
let path = accessor_to_jsonpath(c[2].trim(), &roots)?;
Some((c[1].to_string(), format!("jsonpath \"{path}\"")))
})
.collect()
}
fn strip_js_noise(script: &str) -> (String, Vec<bool>) {
#[derive(PartialEq)]
enum St {
Code,
Line,
Block,
Str(char),
}
let mut out = String::with_capacity(script.len());
let mut in_string = Vec::with_capacity(script.len());
let mut st = St::Code;
let mut escaped = false;
let mut chars = script.chars().peekable();
while let Some(c) = chars.next() {
let (keep, quoted) = match st {
St::Code => match c {
'/' if chars.peek() == Some(&'/') => {
st = St::Line;
(false, false)
}
'/' if chars.peek() == Some(&'*') => {
st = St::Block;
(false, false)
}
'\'' | '"' | '`' => {
st = St::Str(c);
escaped = false;
(true, true)
}
_ => (true, false),
},
St::Line => {
if c == '\n' {
st = St::Code;
(true, false)
} else {
(false, false)
}
}
St::Block => {
if c == '*' && chars.peek() == Some(&'/') {
chars.next();
out.push(' ');
in_string.push(false);
st = St::Code;
}
(c == '\n', false)
}
St::Str(delim) => {
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == delim || (c == '\n' && delim != '`') {
st = St::Code;
}
(true, true)
}
};
let ch = if keep { c } else { ' ' };
out.push(ch);
for _ in 0..ch.len_utf8() {
in_string.push(quoted);
}
}
debug_assert_eq!(out.len(), in_string.len());
(out, in_string)
}
fn accessor_to_jsonpath(expr: &str, roots: &[String]) -> Option<String> {
let mut s = roots.iter().find_map(|r| {
expr.strip_prefix(r.as_str())
.filter(|rest| rest.is_empty() || rest.starts_with(['.', '[']))
})?;
let mut path = String::from("$");
while !s.is_empty() {
if let Some(rest) = s.strip_prefix('.') {
let end = rest
.find(|c: char| !(c.is_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
if end == 0 {
return None;
}
push_key(&mut path, &rest[..end]);
s = &rest[end..];
} else {
let rest = s.strip_prefix('[')?;
let close = rest.find(']')?;
let key = rest[..close].trim();
if let Some(k) = unquote(key) {
push_key(&mut path, k);
} else if !key.is_empty() && key.bytes().all(|b| b.is_ascii_digit()) {
path.push_str(&format!("[{key}]"));
} else {
return None;
}
s = &rest[close + 1..];
}
}
Some(path)
}
fn push_key(path: &mut String, key: &str) {
let simple = !key.is_empty()
&& !key.starts_with(|c: char| c.is_ascii_digit())
&& key.chars().all(|c| c.is_alphanumeric() || c == '_');
if simple {
path.push('.');
path.push_str(key);
} else {
path.push_str(&format!("['{key}']"));
}
}
fn unquote(s: &str) -> Option<&str> {
let b = s.as_bytes();
if b.len() >= 2 && (b[0] == b'\'' || b[0] == b'"') && b[b.len() - 1] == b[0] {
Some(&s[1..s.len() - 1])
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn imports_requests_headers_and_body() {
let json = r#"{
"info": { "name": "demo", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [
{ "name": "folder", "item": [
{ "name": "login", "request": {
"method": "POST",
"url": { "raw": "{{url}}/login?next=1", "host": ["{{url}}"], "path": ["login"] },
"header": [
{ "key": "Content-Type", "value": "application/json", "type": "text" },
{ "key": "X-Off", "value": "no", "disabled": true }
],
"body": { "mode": "raw", "raw": "{\"u\":\"a\"}" }
}}
]},
{ "name": "form", "request": {
"method": "POST",
"url": "{{url}}/upload",
"body": { "mode": "urlencoded", "urlencoded": [
{ "key": "a", "value": "1" },
{ "key": "f", "type": "file", "src": "x" }
]}
}}
]
}"#;
assert!(looks_like_postman(json));
let e = import_postman(json);
assert_eq!(
e.len(),
2,
"folders are flattened into requests, but their path is kept in the title"
);
assert_eq!(
e[0].title, "folder/login",
"the request's folder path is preserved in its title"
);
assert_eq!(e[0].method, "POST");
assert_eq!(e[0].url, "{{url}}/login?next=1");
assert_eq!(
e[0].headers,
vec![
(
"Content-Type".to_string(),
"application/json".to_string(),
true
),
("X-Off".to_string(), "no".to_string(), false),
]
);
assert_eq!(e[0].body_src.as_deref(), Some("{\"u\":\"a\"}"));
assert_eq!(e[1].title, "form");
assert_eq!(
e[1].form_fields,
vec![
FormField {
key: "a".into(),
value: "1".into(),
kind: FormFieldKind::Text,
content_type: None,
base64_prefix: None,
enabled: true,
desc: String::new(),
},
FormField {
key: "f".into(),
value: "x".into(),
kind: FormFieldKind::File,
content_type: None,
base64_prefix: None,
enabled: true,
desc: String::new(),
},
],
"text and file form-data fields are both imported"
);
}
#[test]
fn bearer_auth_becomes_a_header() {
let json = r#"{"info":{},"item":[{"name":"x","request":{
"method":"GET","url":"{{url}}/me",
"auth":{"type":"bearer","bearer":[{"key":"token","value":"{{tok}}"}]}
}}]}"#;
let e = import_postman(json);
assert_eq!(e.len(), 1);
assert!(e[0].headers.contains(&KvRow::toggled(
"Authorization".to_string(),
"Bearer {{tok}}".to_string(),
true
)));
}
#[test]
fn deeply_nested_folders_build_a_full_slash_separated_path() {
let json = r#"{"info":{},"item":[
{ "name": "Auth", "item": [
{ "name": "Tokens", "item": [
{ "name": "Refresh", "request": { "method": "POST", "url": "{{url}}/refresh" } }
]},
{ "name": "Login", "request": { "method": "POST", "url": "{{url}}/login" } }
]},
{ "name": "Health", "request": { "method": "GET", "url": "{{url}}/health" } }
]}"#;
let e = import_postman(json);
assert_eq!(e.len(), 3);
assert_eq!(
e[0].title, "Auth/Tokens/Refresh",
"nesting three levels deep joins every folder name"
);
assert_eq!(e[1].title, "Auth/Login");
assert_eq!(
e[2].title, "Health",
"a top-level request keeps its bare name"
);
}
#[test]
fn non_postman_json_is_not_detected() {
assert!(!looks_like_postman("{\"foo\": 1}"));
assert!(!looks_like_postman("GET http://x/y\nHTTP 200\n"));
}
#[test]
fn enveloped_collection_export_is_detected_and_imported() {
let json = r#"{ "collection": {
"info": { "name": "demo", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [
{ "name": "login", "request": { "method": "POST", "url": "{{url}}/login" } }
]
}}"#;
assert!(looks_like_postman(json));
let e = import_postman(json);
assert_eq!(e.len(), 1);
assert_eq!(e[0].title, "login");
assert_eq!(e[0].method, "POST");
assert_eq!(e[0].url, "{{url}}/login");
}
#[test]
fn collection_key_that_is_not_an_envelope_is_left_alone() {
let json = r#"{
"collection": "some-id",
"info": { "name": "demo" },
"item": [ { "name": "ping", "request": { "method": "GET", "url": "http://x/y" } } ]
}"#;
assert!(looks_like_postman(json));
assert_eq!(import_postman(json).len(), 1);
}
#[test]
fn form_field_with_explicit_null_value_still_imports() {
let json = r#"{
"info": {"name": "n"},
"item": [
{
"name": "upload",
"request": {
"method": "POST",
"url": "http://x/upload",
"body": {
"mode": "formdata",
"formdata": [
{"key": "doc", "value": "hi", "type": "text"},
{"key": "file", "type": "file", "value": null, "src": null},
{"key": "back", "type": "file", "src": "/tmp/a.png"}
]
}
}
}
]
}"#;
let entries = import_postman(json);
assert_eq!(entries.len(), 1);
let keys: Vec<&str> = entries[0]
.form_fields
.iter()
.map(|f| f.key.as_str())
.collect();
assert_eq!(keys, ["doc", "file", "back"]);
assert_eq!(entries[0].form_fields[2].value, "/tmp/a.png");
}
#[test]
fn accessor_chains_become_jsonpaths() {
let roots = vec!["jsonData".to_string()];
let p = |e: &str| accessor_to_jsonpath(e, &roots);
assert_eq!(p("jsonData['token']").as_deref(), Some("$.token"));
assert_eq!(p("jsonData[\"token\"]").as_deref(), Some("$.token"));
assert_eq!(p("jsonData.a.b").as_deref(), Some("$.a.b"));
assert_eq!(p("jsonData['a']['b']").as_deref(), Some("$.a.b"));
assert_eq!(p("jsonData.items[0].id").as_deref(), Some("$.items[0].id"));
assert_eq!(p("jsonData['a-b']").as_deref(), Some("$['a-b']"));
assert_eq!(p("jsonData").as_deref(), Some("$"));
assert_eq!(p("jsonData.foo()"), None);
assert_eq!(p("other['x']"), None);
}
#[test]
fn test_script_set_calls_become_captures_with_wildcard_status() {
let json = r#"{
"info": {},
"item": [
{ "name": "login", "request": { "method": "POST", "url": "{{url}}/login" },
"event": [
{ "listen": "test", "script": { "exec": [
"var jsonData = pm.response.json();\r",
"pm.environment.set(\"token\", jsonData['token']);",
"pm.collectionVariables.set(\"sid\", jsonData.session.id);"
]}}
]
}
]
}"#;
let e = import_postman(json);
assert_eq!(e.len(), 1);
assert_eq!(
e[0].captures,
vec![
("token".to_string(), "jsonpath \"$.token\"".to_string()),
("sid".to_string(), "jsonpath \"$.session.id\"".to_string()),
]
);
let text = e[0].to_hurl();
assert!(text.contains("HTTP *"), "wildcard status expected:\n{text}");
assert!(text.contains("token: jsonpath \"$.token\""));
}
#[test]
fn imported_request_without_captures_stays_bare() {
let json =
r#"{"info":{},"item":[{"name":"x","request":{"method":"GET","url":"{{u}}/a"}}]}"#;
let e = import_postman(json);
assert_eq!(e.len(), 1);
assert!(e[0].captures.is_empty());
assert!(
!e[0].to_hurl().contains("HTTP"),
"a capture-less import has no response line"
);
}
#[test]
fn postman_parameter_documentation_becomes_a_row_description() {
let json = r#"{
"info": { "name": "demo", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [
{ "name": "search", "request": {
"method": "POST",
"url": {
"raw": "{{url}}/search?q=cats",
"host": ["{{url}}"],
"path": ["search"],
"query": [ { "key": "q", "value": "cats" } ]
},
"header": [
{ "key": "X-Trace", "value": "on", "description": "staging only" }
],
"body": {
"mode": "urlencoded",
"urlencoded": [
{ "key": "region", "value": "eu", "description": "which cluster" }
]
}
}}
]
}"#;
let entries = import_postman(json);
let e = &entries[0];
assert_eq!(
e.headers[0].desc, "staging only",
"the header's Postman documentation should survive the import"
);
assert_eq!(
e.form_fields[0].desc, "which cluster",
"and so should a form field's"
);
}
}
#[cfg(test)]
mod description_tests {
use super::*;
fn one(request: &str) -> ConvertedCollection {
convert_postman(&format!(
r#"{{ "info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [ {{ "name": "r", "request": {request} }} ] }}"#
))
}
fn comments(e: &HurlEntry) -> Vec<&str> {
e.comments.iter().map(|c| c.text.as_str()).collect()
}
#[test]
fn a_request_description_is_kept_as_comments() {
let c = one(r#"{ "method": "GET", "url": "https://h/x",
"description": "Returns the current user.\n\nRequires the `read` scope." }"#);
assert_eq!(
comments(&c.entries[0]),
vec![
"# Returns the current user.",
"#",
"# Requires the `read` scope."
]
);
}
#[test]
fn the_description_never_becomes_part_of_the_name() {
let c = one(r#"{ "method": "GET", "url": "https://h/x", "description": "long prose" }"#);
assert_eq!(c.entries[0].title, "r");
}
#[test]
fn an_object_description_is_read_too() {
let c = one(r##"{ "method": "GET", "url": "https://h/x",
"description": { "content": "Heading", "type": "text/markdown" } }"##);
assert_eq!(comments(&c.entries[0]), vec!["# Heading"]);
}
#[test]
fn no_description_adds_nothing() {
let c = one(r#"{ "method": "GET", "url": "https://h/x" }"#);
assert!(c.entries[0].comments.is_empty());
}
#[test]
fn a_null_description_is_survivable() {
let c = one(r#"{ "method": "GET", "url": "https://h/x", "description": null }"#);
assert_eq!(c.entries.len(), 1);
assert!(c.entries[0].comments.is_empty());
}
}
#[cfg(test)]
mod body_mode_tests {
use super::*;
fn post(body: &str) -> ConvertedCollection {
convert_postman(&format!(
r#"{{ "info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [ {{ "name": "r", "request": {{ "method": "POST",
"url": "https://h/x", "body": {body} }} }} ] }}"#
))
}
#[test]
fn a_graphql_body_becomes_the_json_post_it_actually_is() {
let c = post(
r#"{ "mode": "graphql", "graphql": {
"query": "query Q($id: ID){ thing(id: $id) }",
"variables": "{ \"id\": \"7\" }" } }"#,
);
let e = &c.entries[0];
let sent: serde_json::Value = serde_json::from_str(e.body_src.as_deref().unwrap()).unwrap();
assert_eq!(sent["query"], "query Q($id: ID){ thing(id: $id) }");
assert_eq!(
sent["variables"]["id"], "7",
"the variables nest as an object, not as the string Postman stores"
);
assert!(
e.headers
.iter()
.any(|h| h.key.eq_ignore_ascii_case("content-type")
&& h.value.contains("application/json"))
);
assert!(
!c.notes.iter().any(|n| n.detail.contains("graphql")),
"and nothing was lost to report: {:?}",
c.notes
);
}
#[test]
fn unparseable_graphql_variables_are_left_out() {
let c = post(
r#"{ "mode": "graphql", "graphql": { "query": "{ ping }",
"variables": "{ not json" } }"#,
);
let sent: serde_json::Value =
serde_json::from_str(c.entries[0].body_src.as_deref().unwrap()).unwrap();
assert_eq!(sent["query"], "{ ping }");
assert!(sent.get("variables").is_none());
}
#[test]
fn a_file_body_is_reported_rather_than_imported_and_lost() {
let c = post(r#"{ "mode": "file", "file": { "src": "./payload.bin" } }"#);
assert_eq!(c.entries[0].body_src, None);
assert!(
c.notes.iter().any(|n| n.detail.contains("./payload.bin")),
"the path is named so it can be attached by hand: {:?}",
c.notes
);
}
#[test]
fn a_file_body_with_no_file_is_reported_not_invented() {
let c = post(r#"{ "mode": "file", "file": { "src": "" } }"#);
assert_eq!(c.entries[0].body_src, None);
assert!(
c.notes
.iter()
.any(|n| n.detail.contains("never had one chosen")),
"{:?}",
c.notes
);
}
}
#[cfg(test)]
mod profile_behavior_tests {
use super::*;
fn convert(item: &str) -> ConvertedCollection {
convert_postman(&format!(
r#"{{ "info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [ {item} ] }}"#
))
}
#[test]
fn a_get_body_postman_would_not_have_sent_is_left_out() {
let c = convert(
r#"{ "name": "r", "request": { "method": "GET", "url": "https://h/x",
"body": { "mode": "raw", "raw": "{\"stale\":true}" } } }"#,
);
assert_eq!(c.entries[0].body_src, None);
assert!(
c.notes.iter().any(|n| n.detail.contains("body pruning")),
"and it says why, since the text is visibly in the export: {:?}",
c.notes
);
}
#[test]
fn disable_body_pruning_keeps_the_body() {
let c = convert(
r#"{ "name": "r", "protocolProfileBehavior": { "disableBodyPruning": true },
"request": { "method": "GET", "url": "https://h/x",
"body": { "mode": "raw", "raw": "{}" } } }"#,
);
assert_eq!(c.entries[0].body_src.as_deref(), Some("{}"));
}
#[test]
fn a_post_body_is_untouched() {
let c = convert(
r#"{ "name": "r", "request": { "method": "POST", "url": "https://h/x",
"body": { "mode": "raw", "raw": "{}" } } }"#,
);
assert_eq!(c.entries[0].body_src.as_deref(), Some("{}"));
}
#[test]
fn a_folder_can_turn_pruning_off_for_everything_inside_it() {
let c = convert(
r#"{ "name": "F", "protocolProfileBehavior": { "disableBodyPruning": true },
"item": [ { "name": "r", "request": { "method": "GET", "url": "https://h/x",
"body": { "mode": "raw", "raw": "{}" } } } ] }"#,
);
assert_eq!(c.entries[0].body_src.as_deref(), Some("{}"));
}
#[test]
fn strict_ssl_off_becomes_the_insecure_option() {
let c = convert(
r#"{ "name": "r", "protocolProfileBehavior": { "strictSSL": false },
"request": { "method": "GET", "url": "https://h/x" } }"#,
);
assert!(
c.entries[0]
.options
.contains(&KvRow::toggled("insecure", "true", true))
);
}
#[test]
fn certificate_checking_stays_on_by_default() {
let c = convert(r#"{ "name": "r", "request": { "method": "GET", "url": "https://h/x" } }"#);
assert!(c.entries[0].options.is_empty());
}
#[test]
fn a_disabled_query_parameter_imports_switched_off() {
let c = convert(
r#"{ "name": "r", "request": { "method": "GET", "url": {
"raw": "https://h/x?page=2",
"query": [ { "key": "page", "value": "2" },
{ "key": "verbose", "value": "true", "disabled": true } ] } } }"#,
);
let q = &c.entries[0].queries;
assert!(
q.contains(&KvRow::toggled("verbose", "true", false)),
"the disabled parameter is kept, switched off: {q:?}"
);
assert_eq!(
q.iter().filter(|r| r.key == "page").count(),
0,
"and the enabled one is not duplicated — it is already in the URL text"
);
assert_eq!(c.entries[0].url, "https://h/x?page=2");
}
}
#[cfg(test)]
mod awsv4_tests {
use super::*;
fn one(auth: &str) -> ConvertedCollection {
convert_postman(&format!(
r#"{{
"info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [ {{ "name": "r", "request": {{ "method": "GET",
"url": "https://api.example.com/v1/x", "auth": {auth} }} }} ]
}}"#
))
}
fn option(e: &HurlEntry, name: &str) -> Option<String> {
e.options
.iter()
.find(|o| o.key == name)
.map(|o| o.value.clone())
}
#[test]
fn awsv4_auth_becomes_the_aws_sigv4_option() {
let c = one(r#"{ "type": "awsv4", "awsv4": [
{ "key": "accessKey", "value": "AKIA1" },
{ "key": "secretKey", "value": "s3cret" },
{ "key": "region", "value": "eu-west-1" },
{ "key": "service", "value": "execute-api" } ] }"#);
let e = &c.entries[0];
assert_eq!(
option(e, "aws-sigv4").as_deref(),
Some("aws:amz:eu-west-1:execute-api")
);
assert_eq!(option(e, "user").as_deref(), Some("AKIA1:s3cret"));
}
#[test]
fn an_unnamed_region_is_left_for_curl_to_infer() {
let c = one(r#"{ "type": "awsv4", "awsv4": [
{ "key": "accessKey", "value": "AKIA1" },
{ "key": "secretKey", "value": "s3cret" } ] }"#);
assert_eq!(
option(&c.entries[0], "aws-sigv4").as_deref(),
Some("aws:amz")
);
}
#[test]
fn a_bare_aws_auth_block_signs_with_named_variables_and_says_so() {
let c = one(r#"{ "type": "awsv4" }"#);
assert_eq!(
option(&c.entries[0], "user").as_deref(),
Some("{{aws_access_key_id}}:{{aws_secret_access_key}}")
);
assert!(
c.notes
.iter()
.any(|n| n.detail.contains("aws_access_key_id")),
"the user is told where to put the keys: {:?}",
c.notes
);
assert!(
!c.notes.iter().any(|n| n.detail.contains("was dropped")),
"and it is no longer reported as a lost auth type"
);
}
#[test]
fn a_session_token_rides_in_its_own_header() {
let c = one(r#"{ "type": "awsv4", "awsv4": [
{ "key": "accessKey", "value": "A" },
{ "key": "secretKey", "value": "B" },
{ "key": "sessionToken", "value": "tok" } ] }"#);
assert!(c.entries[0].headers.contains(&KvRow::toggled(
"x-amz-security-token",
"tok",
true
)));
}
}
#[cfg(test)]
mod oauth2_tests {
use super::*;
fn folder_oauth2(extra: &str) -> String {
format!(
r#"{{
"info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [
{{ "name": "Tenant API",
"auth": {{ "type": "oauth2", "oauth2": [
{{ "key": "accessTokenUrl", "value": "https://id.example.com/v1/token" }},
{{ "key": "grant_type", "value": "client_credentials" }},
{{ "key": "clientId", "value": "abc" }},
{{ "key": "clientSecret", "value": "shh" }},
{{ "key": "scope", "value": "read write" }},
{{ "key": "tokenType", "value": "Bearer" }}
{extra}
] }},
"item": [
{{ "name": "list", "request": {{ "method": "GET", "url": "https://h/a" }} }},
{{ "name": "get", "request": {{ "method": "GET", "url": "https://h/b" }} }}
] }}
]
}}"#
)
}
fn header(e: &HurlEntry, name: &str) -> Option<String> {
e.headers
.iter()
.find(|h| h.key.eq_ignore_ascii_case(name))
.map(|h| h.value.clone())
}
fn field(e: &HurlEntry, key: &str) -> Option<String> {
e.form_fields
.iter()
.find(|f| f.key == key)
.map(|f| f.value.clone())
}
#[test]
fn a_folders_client_credentials_auth_becomes_a_token_request() {
let c = convert_postman(&folder_oauth2(""));
let titles: Vec<&str> = c.entries.iter().map(|e| e.title.as_str()).collect();
assert_eq!(
titles,
vec![
"Tenant API/Get access token",
"Tenant API/list",
"Tenant API/get"
],
"the token request is generated once, in the folder that declared \
the auth, ahead of the requests that need it"
);
let token = &c.entries[0];
assert_eq!(token.method, "POST");
assert_eq!(token.url, "https://id.example.com/v1/token");
assert_eq!(
field(token, "grant_type").as_deref(),
Some("client_credentials")
);
assert_eq!(field(token, "scope").as_deref(), Some("read write"));
assert_eq!(
token.basic_auth,
Some(("abc".to_string(), "shh".to_string())),
"Postman's default client authentication is HTTP Basic"
);
assert_eq!(
token.captures,
vec![(
"access_token".to_string(),
"jsonpath \"$.access_token\"".to_string()
)]
);
assert_eq!(
token.expected_status,
Some(200),
"without this a failed token request captures nothing and every \
request after it fails for a reason that has scrolled away"
);
for e in &c.entries[1..] {
assert_eq!(
header(e, "Authorization").as_deref(),
Some("Bearer {{access_token}}"),
"{} must actually use the token",
e.title
);
}
}
#[test]
fn one_token_request_is_generated_per_distinct_configuration() {
let c = convert_postman(
r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [
{ "name": "A", "auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "client_credentials" },
{ "key": "clientId", "value": "same" } ] },
"item": [ { "name": "x", "request": { "method": "GET", "url": "https://h/x" } } ] },
{ "name": "B", "auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "client_credentials" },
{ "key": "clientId", "value": "same" } ] },
"item": [ { "name": "y", "request": { "method": "GET", "url": "https://h/y" } } ] },
{ "name": "C", "auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "client_credentials" },
{ "key": "clientId", "value": "other" } ] },
"item": [ { "name": "z", "request": { "method": "GET", "url": "https://h/z" } } ] }
]
}"#,
);
let tokens: Vec<&str> = c
.entries
.iter()
.filter(|e| e.title.ends_with("Get access token"))
.map(|e| e.title.as_str())
.collect();
assert_eq!(
tokens,
vec!["A/Get access token", "C/Get access token"],
"identical configurations share a token; a different client gets its own"
);
let used = |title: &str| {
c.entries
.iter()
.find(|e| e.title == title)
.and_then(|e| header(e, "Authorization"))
};
assert_eq!(used("A/x"), used("B/y"), "B reuses A's token");
assert_eq!(used("C/z").as_deref(), Some("Bearer {{access_token_2}}"));
}
#[test]
fn body_client_authentication_sends_the_credentials_as_form_fields() {
let c = convert_postman(&folder_oauth2(
r#", { "key": "client_authentication", "value": "body" }"#,
));
let token = &c.entries[0];
assert_eq!(token.basic_auth, None);
assert_eq!(field(token, "client_id").as_deref(), Some("abc"));
assert_eq!(field(token, "client_secret").as_deref(), Some("shh"));
}
#[test]
fn add_token_to_query_params_uses_a_query_parameter() {
let c = convert_postman(&folder_oauth2(
r#", { "key": "addTokenTo", "value": "queryParams" }"#,
));
let list = c
.entries
.iter()
.find(|e| e.title == "Tenant API/list")
.unwrap();
assert_eq!(header(list, "Authorization"), None);
assert!(
list.queries
.contains(&KvRow::toggled("access_token", "{{access_token}}", true))
);
}
#[test]
fn the_authorization_code_grant_is_reported_not_invented() {
let c =
convert_postman(&folder_oauth2("").replace("client_credentials", "authorization_code"));
assert!(
c.entries
.iter()
.all(|e| !e.title.ends_with("Get access token")),
"nothing is generated for a flow that needs a human"
);
assert!(
c.notes
.iter()
.any(|n| n.detail.contains("authorization_code")),
"but the user is told why: {:?}",
c.notes
);
}
#[test]
fn missing_credentials_become_variables_and_a_note() {
let c = convert_postman(
r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [ { "name": "x", "request": { "method": "GET", "url": "https://h/x",
"auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "client_credentials" },
{ "key": "clientId", "value": "" },
{ "key": "clientSecret", "value": "" } ] } } } ]
}"#,
);
assert_eq!(
c.entries[0].basic_auth,
Some((
"{{oauth_client_id}}".to_string(),
"{{oauth_client_secret}}".to_string()
))
);
assert!(
c.notes.iter().any(|n| n.detail.contains("oauth_client_id")),
"and it says so rather than leaving a silently unusable request"
);
}
#[test]
fn an_override_with_no_token_url_reuses_the_inherited_token() {
let c = convert_postman(
r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "client_credentials" },
{ "key": "clientId", "value": "abc" } ] },
"item": [
{ "name": "plain", "request": { "method": "GET", "url": "https://h/a" } },
{ "name": "F", "auth": { "type": "oauth2", "oauth2": [
{ "key": "headerPrefix", "value": "Token " } ] },
"item": [ { "name": "y", "request": { "method": "GET", "url": "https://h/y" } } ] }
]
}"#,
);
assert_eq!(
c.entries
.iter()
.filter(|e| e.title.ends_with("Get access token"))
.count(),
1,
"the override has no token URL of its own to fetch from"
);
let y = c.entries.iter().find(|e| e.title == "F/y").unwrap();
assert_eq!(
header(y, "Authorization").as_deref(),
Some("Token {{access_token}}"),
"but its prefix override is honoured"
);
}
#[test]
fn a_collection_wide_token_is_not_buried_in_a_folder() {
let c = convert_postman(
r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "client_credentials" },
{ "key": "clientId", "value": "abc" } ] },
"item": [ { "name": "Deep", "item": [ { "name": "Deeper", "item": [
{ "name": "x", "request": { "method": "GET", "url": "https://h/x" } } ] } ] } ]
}"#,
);
assert_eq!(c.entries[0].title, "Get access token");
}
#[test]
fn the_password_grant_is_generated_like_client_credentials() {
let c = convert_postman(
r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [ { "name": "x", "request": { "method": "GET", "url": "https://h/x",
"auth": { "type": "oauth2", "oauth2": [
{ "key": "accessTokenUrl", "value": "https://id/t" },
{ "key": "grant_type", "value": "password" },
{ "key": "clientId", "value": "abc" },
{ "key": "username", "value": "u" },
{ "key": "password", "value": "p" } ] } } } ]
}"#,
);
let token = &c.entries[0];
assert_eq!(field(token, "grant_type").as_deref(), Some("password"));
assert_eq!(field(token, "username").as_deref(), Some("u"));
assert_eq!(field(token, "password").as_deref(), Some("p"));
}
}
#[cfg(test)]
mod path_variable_tests {
use super::*;
fn one(url: &str) -> ConvertedCollection {
convert_postman(&format!(
r#"{{
"info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [ {{ "name": "r", "request": {{ "method": "GET", "url": {url} }} }} ]
}}"#
))
}
#[test]
fn a_declared_path_variable_becomes_a_hurl_variable() {
let c = one(r#"{ "raw": "{{base}}/v1/batches/:batch_id/add",
"variable": [{ "key": "batch_id", "value": "se-28529731" }] }"#);
assert_eq!(c.entries[0].url, "{{base}}/v1/batches/{{batch_id}}/add");
assert!(
c.variables
.contains(&("batch_id".into(), "se-28529731".into())),
"and the value Postman would have substituted comes with it"
);
}
#[test]
fn an_undeclared_colon_segment_is_left_alone() {
let c = one(r#"{ "raw": "http://localhost:8080/v1/:not_declared" }"#);
assert_eq!(c.entries[0].url, "http://localhost:8080/v1/:not_declared");
assert!(c.variables.is_empty());
}
#[test]
fn a_port_is_never_mistaken_for_a_path_variable() {
let c = one(r#"{ "raw": "http://host:8080/x/:id",
"variable": [{ "key": "id", "value": "7" }] }"#);
assert_eq!(c.entries[0].url, "http://host:8080/x/{{id}}");
}
#[test]
fn the_query_string_is_not_rewritten() {
let c = one(r#"{ "raw": "https://h/x/:id?at=12:30&who=:id",
"variable": [{ "key": "id", "value": "7" }] }"#);
assert_eq!(
c.entries[0].url, "https://h/x/{{id}}?at=12:30&who=:id",
"the path placeholder is rewritten; the colons after the `?` are not"
);
}
#[test]
fn two_requests_declaring_the_same_name_differently_are_reported() {
let c = convert_postman(
r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [
{ "name": "a", "request": { "method": "GET", "url": {
"raw": "https://h/:id", "variable": [{ "key": "id", "value": "1" }] } } },
{ "name": "b", "request": { "method": "GET", "url": {
"raw": "https://h/:id", "variable": [{ "key": "id", "value": "2" }] } } }
]
}"#,
);
assert_eq!(c.variables, vec![("id".to_string(), "1".to_string())]);
assert!(
c.notes
.iter()
.any(|n| n.item == "b" && n.detail.contains("id")),
"the discarded second value is named, not swallowed: {:?}",
c.notes
);
}
#[test]
fn a_declared_variable_with_no_value_still_parameterises_the_url() {
let c = one(r#"{ "raw": "{{baseUrl}}/v1/batches/:batch_id",
"variable": [{ "key": "batch_id", "value": "", "description": "Batch ID" }] }"#);
assert_eq!(c.entries[0].url, "{{baseUrl}}/v1/batches/{{batch_id}}");
assert_eq!(c.variables, vec![("batch_id".to_string(), String::new())]);
}
}
#[cfg(test)]
mod inheritance_tests {
use super::*;
fn nested() -> &'static str {
r#"{
"info": { "name": "demo", "schema": "https://schema.getpostman.com/..v2.1.0" },
"auth": { "type": "bearer", "bearer": [{ "key": "token", "value": "{{TOKEN}}" }] },
"variable": [
{ "key": "base", "value": "https://api.example.com" },
{ "key": "off", "value": "x", "disabled": true },
{ "key": "", "value": "nameless" }
],
"item": [
{ "name": "inherits", "request": { "method": "GET", "url": "{{base}}/a" } },
{ "name": "opts out", "request": {
"method": "GET", "url": "{{base}}/b", "auth": { "type": "noauth" } } },
{ "name": "folder",
"auth": { "type": "basic", "basic": [
{ "key": "username", "value": "u" }, { "key": "password", "value": "p" } ] },
"item": [
{ "name": "deep", "request": { "method": "GET", "url": "{{base}}/c" } },
{ "name": "own", "request": { "method": "GET", "url": "{{base}}/d",
"auth": { "type": "apikey", "apikey": [
{ "key": "key", "value": "X-Key" },
{ "key": "value", "value": "{{KEY}}" } ] } } }
] }
]
}"#
}
fn header(e: &HurlEntry, name: &str) -> Option<String> {
e.headers
.iter()
.find(|h| h.key.eq_ignore_ascii_case(name))
.map(|h| h.value.clone())
}
#[test]
fn a_request_without_auth_inherits_the_collections() {
let c = convert_postman(nested());
let e = &c.entries[0];
assert_eq!(e.title, "inherits");
assert_eq!(
header(e, "Authorization").as_deref(),
Some("Bearer {{TOKEN}}")
);
}
#[test]
fn a_request_can_opt_out_of_the_inherited_auth() {
let c = convert_postman(nested());
let e = &c.entries[1];
assert_eq!(e.title, "opts out");
assert_eq!(header(e, "Authorization"), None);
assert_eq!(e.basic_auth, None);
}
#[test]
fn a_folder_overrides_the_collection_for_everything_inside_it() {
let c = convert_postman(nested());
let e = c.entries.iter().find(|e| e.title == "folder/deep").unwrap();
assert_eq!(e.basic_auth, Some(("u".to_string(), "p".to_string())));
assert_eq!(
header(e, "Authorization"),
None,
"the collection's bearer token doesn't leak past the folder"
);
}
#[test]
fn a_requests_own_auth_beats_the_folder_it_is_in() {
let c = convert_postman(nested());
let e = c.entries.iter().find(|e| e.title == "folder/own").unwrap();
assert_eq!(header(e, "X-Key").as_deref(), Some("{{KEY}}"));
assert_eq!(e.basic_auth, None, "the folder's basic auth was replaced");
}
#[test]
fn an_api_key_in_the_query_string_becomes_a_query_parameter() {
let json = r#"{
"info": { "name": "d", "schema": "x" },
"item": [ { "name": "q", "request": { "method": "GET", "url": "https://x/y",
"auth": { "type": "apikey", "apikey": [
{ "key": "key", "value": "api_key" },
{ "key": "value", "value": "abc" },
{ "key": "in", "value": "query" } ] } } } ]
}"#;
let c = convert_postman(json);
let e = &c.entries[0];
assert!(
e.queries
.iter()
.any(|q| q.key == "api_key" && q.value == "abc"),
"the key rides in the query string: {:?}",
e.queries
);
assert_eq!(header(e, "api_key"), None, "and not in a header as well");
}
#[test]
fn collection_variables_are_extracted_for_a_vars_file() {
let vars = convert_postman(nested()).variables;
assert_eq!(
vars,
vec![("base".to_string(), "https://api.example.com".to_string())]
);
}
#[test]
fn what_could_not_be_converted_is_reported() {
let json = r#"{
"info": { "name": "d", "schema": "x" },
"item": [
{ "name": "oauth1", "request": { "method": "GET", "url": "https://x",
"auth": { "type": "oauth1" } } },
{ "name": "gql", "request": { "method": "POST", "url": "https://x",
"body": { "mode": "graphql" } } },
{ "name": "scripted", "request": { "method": "GET", "url": "https://x" },
"event": [ { "listen": "prerequest",
"script": { "exec": ["pm.environment.set('t', Date.now())"] } } ] }
]
}"#;
let notes = convert_postman(json).notes;
let for_item = |name: &str| {
notes
.iter()
.filter(|n| n.item == name)
.map(|n| n.detail.clone())
.collect::<Vec<_>>()
};
assert!(
for_item("oauth1")[0].contains("oauth1"),
"the auth type that was lost is named: {notes:?}"
);
assert!(
for_item("gql")[0].contains("GraphQL"),
"an empty GraphQL body has nothing to send, and says so"
);
assert!(for_item("scripted")[0].contains("pre-request"));
}
#[test]
fn a_generated_variable_is_renamed_so_the_file_still_parses() {
let json = r#"{
"info": { "name": "d", "schema": "x" },
"item": [ { "name": "start", "request": { "method": "POST",
"url": "https://x/{{$guid}}",
"header": [ { "key": "X-Run", "value": "{{$timestamp}}" } ],
"body": { "mode": "raw", "raw": "{\"id\": \"{{$processEnv.HOME}}\"}" } } } ]
}"#;
let converted = convert_postman(json);
let hurl = crate::hurl::collection_to_hurl(&converted.entries);
assert!(!hurl.contains("{{$"), "a `$` is not a legal name: {hurl}");
assert!(hurl.contains("{{guid}}"), "{hurl}");
assert!(hurl.contains("{{timestamp}}"), "{hurl}");
assert!(hurl.contains("{{processEnv_HOME}}"), "{hurl}");
assert_eq!(
crate::hurl::parse_hurl(&hurl).len(),
1,
"the converted file must read back: {:?}",
crate::hurl::parse_hurl_error(&hurl)
);
assert_eq!(converted.notes.len(), 3);
assert!(
converted
.notes
.iter()
.any(|n| n.detail.contains("{{guid}}"))
);
}
#[test]
fn a_file_part_with_no_file_is_switched_off_rather_than_written_broken() {
let json = r#"{
"info": { "name": "d", "schema": "x" },
"item": [ { "name": "upload", "request": { "method": "POST", "url": "https://x",
"body": { "mode": "formdata", "formdata": [
{ "key": "document_id", "value": "1", "type": "text" },
{ "key": "front_side_file", "type": "file", "src": "" }
] } } } ]
}"#;
let converted = convert_postman(json);
let hurl = crate::hurl::collection_to_hurl(&converted.entries);
assert!(
!hurl
.lines()
.any(|l| !l.trim_start().starts_with('#') && l.contains("file,;")),
"{hurl}"
);
assert_eq!(
crate::hurl::parse_hurl(&hurl).len(),
1,
"the converted file must read back: {:?}",
crate::hurl::parse_hurl_error(&hurl)
);
let back = &crate::hurl::parse_hurl(&hurl)[0];
let part = back
.form_fields
.iter()
.find(|f| f.key == "front_side_file")
.expect("the part survives as a disabled row");
assert!(!part.enabled);
assert!(
converted
.notes
.iter()
.any(|n| n.detail.contains("front_side_file")),
"the switched-off part is reported: {:?}",
converted.notes
);
}
#[test]
fn a_clean_collection_reports_nothing() {
let json = r#"{
"info": { "name": "d", "schema": "x" },
"item": [ { "name": "ok", "request": { "method": "GET", "url": "https://x",
"header": [ { "key": "Accept", "value": "application/json" } ] } } ]
}"#;
assert_eq!(convert_postman(json).notes, vec![]);
}
}
#[cfg(test)]
mod field_tolerance_tests {
use super::*;
fn collection_with(param: &str) -> String {
format!(
r#"{{
"info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"auth": {{ "type": "oauth2", "oauth2": [
{{ "key": "accessTokenUrl", "value": "https://id.example.com/token" }},
{{ "key": "grant_type", "value": "client_credentials" }},
{{ "key": "clientId", "value": "abc" }},
{{ "key": "clientSecret", "value": "shh" }},
{param}
] }},
"item": [
{{ "name": "Ping", "request": {{ "method": "GET", "url": "https://x/ping" }} }}
]
}}"#
)
}
#[test]
fn array_valued_auth_param_does_not_empty_the_collection() {
for value in [r#"[]"#, r#"[{"key": "a", "value": "b"}]"#, r#"{"a": 1}"#] {
let json = collection_with(&format!(
r#"{{ "key": "tokenRequestParams", "value": {value}, "type": "any" }}"#
));
let out = convert_postman(&json);
assert!(
out.entries.iter().any(|e| e.title == "Ping"),
"value {value} emptied the collection"
);
assert!(
out.notes
.iter()
.all(|n| !n.detail.contains("could not be read")),
"value {value} failed to parse"
);
}
}
#[test]
fn scalar_valued_fields_stringify() {
let json = r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [ { "name": "Ping", "request": {
"method": "GET", "url": "https://x/ping",
"header": [ { "key": "X-Retry", "value": 3 },
{ "key": "X-Debug", "value": true } ] } } ]
}"#;
let entries = import_postman(json);
let headers = &entries[0].headers;
assert_eq!(
headers.iter().find(|h| h.key == "X-Retry").unwrap().value,
"3"
);
assert_eq!(
headers.iter().find(|h| h.key == "X-Debug").unwrap().value,
"true"
);
}
#[test]
fn null_method_falls_back_to_get() {
let json = r#"{
"info": { "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": [ { "name": "Ping", "request": { "method": null, "url": "https://x/ping" } } ]
}"#;
assert_eq!(import_postman(json)[0].method, "GET");
}
#[test]
fn unreadable_collection_is_reported_rather_than_silently_empty() {
let json = r#"{ "info": { "schema": "https://schema.getpostman.com/..v2.1.0" },
"item": "not a list" }"#;
let out = convert_postman(json);
assert!(out.entries.is_empty());
assert_eq!(out.notes.len(), 1);
assert!(out.notes[0].item.is_empty());
assert!(out.notes[0].detail.contains("could not be read"));
}
fn with_auth(auth: &str) -> ConvertedCollection {
convert_postman(&format!(
r#"{{
"info": {{ "name": "d", "schema": "https://schema.getpostman.com/..v2.1.0" }},
"item": [ {{ "name": "r", "request": {{ "method": "GET",
"url": "https://api.example.com/v1/x", "auth": {auth} }} }} ]
}}"#
))
}
#[test]
fn two_users_on_one_client_each_get_their_own_token() {
let json = r#"{"info":{"name":"d","schema":"x"},"item":[
{"name":"Alice","auth":{"type":"oauth2","oauth2":[
{"key":"accessTokenUrl","value":"https://id/t"},
{"key":"grant_type","value":"password"},
{"key":"clientId","value":"cli"},
{"key":"username","value":"alice"},
{"key":"password","value":"alice-pw"}]},
"item":[{"name":"me","request":{"method":"GET","url":"https://h/me"}}]},
{"name":"Bob","auth":{"type":"oauth2","oauth2":[
{"key":"accessTokenUrl","value":"https://id/t"},
{"key":"grant_type","value":"password"},
{"key":"clientId","value":"cli"},
{"key":"username","value":"bob"},
{"key":"password","value":"bob-pw"}]},
"item":[{"name":"me","request":{"method":"GET","url":"https://h/me"}}]}]}"#;
let c = convert_postman(json);
let tokens: Vec<_> = c
.entries
.iter()
.filter(|e| e.title.ends_with("Get access token"))
.collect();
assert_eq!(tokens.len(), 2, "one token request per user");
let users: Vec<&str> = tokens
.iter()
.filter_map(|t| t.form_fields.iter().find(|f| f.key == "username"))
.map(|f| f.value.as_str())
.collect();
assert_eq!(users, vec!["alice", "bob"]);
let bob = c.entries.iter().find(|e| e.title == "Bob/me").unwrap();
let alice = c.entries.iter().find(|e| e.title == "Alice/me").unwrap();
let token_of = |e: &HurlEntry| {
e.headers
.iter()
.find(|h| h.key == "Authorization")
.map(|h| h.value.clone())
.unwrap_or_default()
};
assert_ne!(
token_of(bob),
token_of(alice),
"each user's requests use their own captured token"
);
}
#[test]
fn a_generated_token_never_takes_a_variable_name_already_in_use() {
let json = r#"{"info":{"name":"d","schema":"x"},
"variable":[{"key":"access_token","value":"a-preset-value"}],
"item":[{"name":"F","auth":{"type":"oauth2","oauth2":[
{"key":"accessTokenUrl","value":"https://id/t"},
{"key":"grant_type","value":"client_credentials"},
{"key":"clientId","value":"cli"}]},
"item":[{"name":"x","request":{"method":"GET","url":"https://h/x"}}]}]}"#;
let c = convert_postman(json);
let tok = c
.entries
.iter()
.find(|e| e.title.ends_with("Get access token"))
.unwrap();
let captured = &tok.captures[0].0;
assert_ne!(
captured, "access_token",
"the user's variable is left alone"
);
assert!(
c.variables
.iter()
.any(|(k, v)| k == "access_token" && v == "a-preset-value"),
"and still holds its value"
);
let req = c.entries.iter().find(|e| e.title == "F/x").unwrap();
assert!(
req.headers
.iter()
.any(|h| h.key == "Authorization" && h.value.contains(captured)),
"the request uses the generated name"
);
}
#[test]
fn a_commented_out_capture_is_not_a_capture() {
let script = r#"[
"// pm.environment.set(\"token\", jsonData.secret)",
"/* pm.environment.set(\"blocked\", jsonData.b) */",
"console.log(\"pm.environment.set('quoted', jsonData.c)\")",
"pm.environment.set(\"real\", jsonData.ok)"
]"#;
let json = format!(
r#"{{"info":{{"name":"d","schema":"x"}},"item":[
{{"name":"t","request":{{"method":"GET","url":"https://h/x"}},
"event":[{{"listen":"test","script":{{"exec":{script}}}}}]}}]}}"#
);
let e = import_postman(&json);
let names: Vec<&str> = e[0].captures.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, vec!["real"], "only the live call is captured");
}
#[test]
fn graphql_variables_given_as_an_object_are_kept() {
let json = r#"{"info":{"name":"d","schema":"x"},"item":[
{"name":"gql","request":{"method":"POST","url":"https://h/graphql",
"body":{"mode":"graphql","graphql":{
"query":"query($id:ID!){user(id:$id){name}}",
"variables":{"id":"42"}}}}}]}"#;
let e = import_postman(json);
let body = e[0].body_src.clone().unwrap();
let sent: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(sent["variables"]["id"], "42");
}
#[test]
fn a_url_kept_only_as_pieces_is_rebuilt() {
let json = r#"{"info":{"name":"d","schema":"x"},"item":[
{"name":"s","request":{"method":"GET","url":{
"protocol":"https","host":["api","example","com"],"port":"8443",
"path":["v1","users"],"query":[{"key":"page","value":"2"}]}}}]}"#;
let e = import_postman(json);
assert_eq!(e[0].url, "https://api.example.com:8443/v1/users?page=2");
}
#[test]
fn an_enabled_query_missing_from_the_url_text_is_added_once() {
let json = r#"{"info":{"name":"d","schema":"x"},"item":[
{"name":"d","request":{"method":"GET","url":{
"raw":"https://h/y?page=1",
"query":[{"key":"page","value":"1"},{"key":"token","value":"abc"}]}}}]}"#;
let e = import_postman(json);
assert_eq!(
e[0].url, "https://h/y?page=1&token=abc",
"the missing one is added, the shared one is not duplicated"
);
}
#[test]
fn a_url_fragment_is_dropped_and_reported() {
let json = r#"{"info":{"name":"d","schema":"x"},"item":[
{"name":"h","request":{"method":"GET",
"url":"https://h/search?q=hurl#results"}}]}"#;
let c = convert_postman(json);
assert_eq!(c.entries[0].url, "https://h/search?q=hurl");
assert!(
c.notes.iter().any(|n| n.detail.contains("#results")),
"the loss is reported, not silent: {:?}",
c.notes
);
let back = crate::hurl::parse_hurl(&c.entries[0].to_hurl());
assert_eq!(back.len(), 1, "and the file reads back as one request");
assert_eq!(back[0].url, "https://h/search?q=hurl");
}
#[test]
fn an_aws_service_without_a_region_is_left_to_curl() {
let c = with_auth(
r#"{ "type": "awsv4", "awsv4": [
{ "key": "accessKey", "value": "AKIA1" },
{ "key": "service", "value": "s3" } ] }"#,
);
let sigv4 = c.entries[0]
.options
.iter()
.find(|o| o.key == "aws-sigv4")
.map(|o| o.value.clone());
assert_eq!(sigv4.as_deref(), Some("aws:amz"));
}
#[test]
fn an_api_key_sent_as_a_header_is_not_announced_as_a_query_parameter() {
let c = with_auth(
r#"{ "type": "apikey", "apikey": [
{ "key": "key", "value": "X-Api-Key" },
{ "key": "value", "value": "secret" },
{ "key": "in", "value": "cookie" } ] }"#,
);
assert!(
!c.notes.iter().any(|n| n.detail.contains("query")),
"no query-string claim for a key that went to a header: {:?}",
c.notes
);
}
}