Revision control
Copy as Markdown
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
*/
use once_cell::sync::Lazy;
use url::Url;
use url_macro::url;
// Deliberately unsorted: deployed environments first, then the test one,
// then the custom escape hatch.
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
pub enum Environment {
#[default]
Prod,
Staging,
#[cfg(test)]
Test,
Custom(Url),
}
impl Environment {
pub fn into_url(self, path: &str) -> Url {
let mut url = self.base_url();
url.path_segments_mut()
// Cannot fail: every `base_url()` arm is an `https` URL, which `url`
// guarantees is hierarchical.
.expect("base URL must be hierarchical")
.pop_if_empty()
.extend(path.split('/').filter(|segment| !segment.is_empty()));
url
}
fn base_url(self) -> Url {
match self {
Environment::Prod => MARS_API_ENDPOINT_PROD.clone(),
Environment::Staging => MARS_API_ENDPOINT_STAGING.clone(),
#[cfg(test)]
Environment::Test => Url::parse(&mockito::server_url()).unwrap(),
Environment::Custom(url) => url,
}
}
}
#[cfg(test)]
mod tests {
use url::Host;
use super::*;
#[test]
fn prod_endpoint_parses_and_is_expected() {
let url = Environment::Prod.into_url("ads");
assert_eq!(url.scheme(), "https");
assert_eq!(url.host(), Some(Host::Domain("ads.mozilla.org")));
assert_eq!(url.path(), "/v1/ads");
}
#[test]
fn staging_endpoint_parses_and_is_expected() {
let url = Environment::Staging.into_url("ads");
assert_eq!(url.scheme(), "https");
assert_eq!(url.host(), Some(Host::Domain("ads.allizom.org")));
assert_eq!(url.path(), "/v1/ads");
}
#[test]
fn into_url_normalizes_slash() {
assert_eq!(
Environment::Prod.into_url("/ads"),
Environment::Prod.into_url("ads"),
);
assert_eq!(
Environment::Prod.into_url("//ads/with/extra//slashes//"),
Environment::Prod.into_url("ads/with/extra/slashes"),
);
}
}