use crate::error::Error;
pub fn id_from_url(id_or_url: &str) -> Result<String, Error> {
if id_or_url.is_empty() {
return Err(Error::validation("id_or_url", "must be a non-empty string"));
}
let stripped = id_or_url.trim_end_matches('/');
let segment = stripped.rsplit('/').next().unwrap_or(stripped);
if segment.is_empty() {
return Err(Error::validation(
"id_or_url",
"resolves to an empty path segment",
));
}
Ok(segment.to_string())
}
#[cfg(test)]
mod tests {
use super::id_from_url;
use crate::error::Error;
#[test]
fn bare_numeric_id_returned_unchanged() {
assert_eq!(id_from_url("12345").unwrap(), "12345");
}
#[test]
fn bare_opaque_id_returned_unchanged() {
assert_eq!(id_from_url("p_abc123").unwrap(), "p_abc123");
}
#[test]
fn full_url_fragment_extracts_trailing_id() {
assert_eq!(id_from_url("/2.2/networks/12345").unwrap(), "12345");
}
#[test]
fn nested_url_fragment_extracts_trailing_id() {
assert_eq!(
id_from_url("/2.2/networks/12345/profiles/p_67890").unwrap(),
"p_67890"
);
}
#[test]
fn url_with_trailing_slash_handled() {
assert_eq!(id_from_url("/2.2/networks/12345/").unwrap(), "12345");
}
#[test]
fn absolute_url_extracts_trailing_id() {
assert_eq!(
id_from_url("https://api-user.e2ro.com/2.2/networks/12345").unwrap(),
"12345"
);
}
#[test]
fn empty_string_raises_validation_error() {
let err = id_from_url("").unwrap_err();
match err {
Error::Validation { field, message, .. } => {
assert_eq!(field, "id_or_url");
assert_eq!(message, "must be a non-empty string");
}
other => panic!("expected Error::Validation, got {other:?}"),
}
}
#[test]
fn single_slash_raises_validation_error_for_empty_segment() {
let err = id_from_url("/").unwrap_err();
match err {
Error::Validation { field, message, .. } => {
assert_eq!(field, "id_or_url");
assert_eq!(message, "resolves to an empty path segment");
}
other => panic!("expected Error::Validation, got {other:?}"),
}
}
#[test]
fn all_slashes_raises_validation_error_for_empty_segment() {
let err = id_from_url("///").unwrap_err();
match err {
Error::Validation { field, message, .. } => {
assert_eq!(field, "id_or_url");
assert_eq!(message, "resolves to an empty path segment");
}
other => panic!("expected Error::Validation, got {other:?}"),
}
}
}