mod support;
use std::collections::BTreeSet;
use std::time::Duration;
use internetdata::{Database, DatabaseFormat, LicenseType, Outcome, Standing};
use serde_json::{Value, json};
use support::corpus;
use support::{Route, Stub};
const METADATA: &str = "/api/v2/database/metadata";
const LIST: &str = "/api/v2/database/list";
#[tokio::test]
async fn every_refusal_is_classified_the_way_the_corpus_says() {
let cases = corpus::load().errors;
assert!(!cases.is_empty(), "the corpus has no error cases, so this test asserts nothing");
for case in cases {
let mut route = Route::json(case.status, case.body.to_string());
for (name, value) in &case.headers {
route = route.header(name, value);
}
let stub = Stub::start([(METADATA.to_owned(), route)]).await;
let client = stub.client().retries(0).build().expect("build");
let err = client.database().metadata("any_database_v1").await.expect_err(&case.name);
assert_eq!(err.kind().as_str(), case.expect.kind, "{}: kind", case.name);
assert_eq!(err.retryable(), case.expect.retryable, "{}: retryable", case.name);
assert_eq!(err.status(), Some(case.status), "{}: status", case.name);
if let Some(message) = &case.expect.message {
assert_eq!(&err.message(), message, "{}: message", case.name);
}
assert_eq!(
err.retry_after(),
case.expect.retry_after_seconds.map(Duration::from_secs),
"{}: retry_after",
case.name
);
}
}
#[tokio::test]
async fn a_non_retryable_refusal_is_issued_exactly_once() {
for case in corpus::load().errors.into_iter().filter(|case| !case.expect.retryable) {
let mut route = Route::json(case.status, case.body.to_string());
for (name, value) in &case.headers {
route = route.header(name, value);
}
let stub = Stub::start([(METADATA.to_owned(), route)]).await;
let client = stub.client().retries(3).build().expect("build");
client.database().metadata("any_database_v1").await.expect_err(&case.name);
assert_eq!(stub.count(), 1, "{}: a non-retryable refusal was retried", case.name);
}
}
#[test]
fn the_standing_vocabulary_is_exactly_what_the_corpus_declares() {
let wire = [Standing::Licensed, Standing::Expired, Standing::Unlicensed];
assert_eq!(spellings(&wire), set(&corpus::load().standings));
assert_readers_match_the_wire(&wire);
}
#[test]
fn the_license_type_vocabulary_is_exactly_what_the_corpus_declares() {
let wire = [LicenseType::Evaluation, LicenseType::Standard, LicenseType::Redistribute];
assert_eq!(spellings(&wire), set(&corpus::load().license_type));
assert_readers_match_the_wire(&wire);
}
#[test]
fn the_outcome_readers_agree_with_the_wire() {
assert_readers_match_the_wire(&[
Outcome::Ok,
Outcome::Unauthorized,
Outcome::Denied,
Outcome::Expired,
Outcome::Unknown,
Outcome::Unavailable,
]);
}
#[test]
fn the_format_vocabulary_is_exactly_what_the_corpus_declares() {
let expected = set(&corpus::load().formats);
assert_eq!(spellings(&[DatabaseFormat::Csvgz, DatabaseFormat::Mmdb]), expected);
assert_readers_match_the_wire(&[DatabaseFormat::Csvgz, DatabaseFormat::Mmdb]);
}
#[test]
fn every_visibility_rule_the_corpus_names_is_asserted_here() {
let asserted = set(&[
"listing-is-returned-as-served",
"no-catalog-is-compiled-into-the-client",
"a-listing-is-never-reused-across-clients",
]);
let declared = set(&corpus::load().visibility.client_rules);
assert!(!declared.is_empty(), "the corpus declares no visibility rules");
assert_eq!(
declared, asserted,
"a visibility rule is declared with no test, or tested with no declaration"
);
}
#[tokio::test]
async fn a_listing_is_returned_as_served() {
let served = ["bogon_asn", "bogon_ip", "cdn_ip"];
let stub = Stub::start([(LIST.to_owned(), Route::ok(listing(&served)))]).await;
let client = stub.client().build().expect("build");
let databases = client.database().list().await.expect("list");
let got: Vec<&str> = databases.iter().map(|database| database.base.as_str()).collect();
assert_eq!(got, served, "{}", corpus::load().visibility.why);
}
#[tokio::test]
async fn no_catalog_is_compiled_into_the_client() {
let unheard_of = ["a_database_this_crate_has_never_heard_of"];
let stub = Stub::start([(LIST.to_owned(), Route::ok(listing(&unheard_of)))]).await;
let client = stub.client().build().expect("build");
let databases = client.database().list().await.expect("list");
assert_eq!(bases(&databases), set(&unheard_of), "an unknown family did not survive the decode");
let empty = Stub::start([(LIST.to_owned(), Route::ok(r#"{"databases":[]}"#))]).await;
let client = empty.client().build().expect("build");
assert!(
client.database().list().await.expect("list").is_empty(),
"an organization that licenses nothing was shown a catalog from somewhere else"
);
}
#[tokio::test]
async fn a_listing_is_never_reused_across_clients() {
let stub = Stub::start([(LIST.to_owned(), Route::ok(listing(&["bogon_asn"])))]).await;
let first = stub.client().api_key("key-of-one-org").build().expect("build");
first.database().list().await.expect("list");
stub.route(LIST, Route::ok(listing(&["cdn_ip", "hosting_ip"])));
let second = stub.client().api_key("key-of-another-org").build().expect("build");
let databases = second.database().list().await.expect("list");
assert_eq!(bases(&databases), set(&["cdn_ip", "hosting_ip"]));
assert_eq!(stub.count(), 2, "the second client did not ask for its own listing");
}
fn listing(bases: &[&str]) -> String {
let databases: Vec<Value> = bases
.iter()
.map(|base| {
json!({
"base": base,
"name": base,
"summary": "one line",
"standing": "licensed",
"license_type": "standard",
"starts": "2026-01-01T00:00:00.000Z",
"expires": null, "renews_at": null, "notice_due_at": null,
"versions": [{
"id": format!("{base}_v1"),
"version": 1,
"summary": "one line",
"formats": ["csvgz"],
}],
})
})
.collect();
json!({ "databases": databases }).to_string()
}
fn bases(databases: &[Database]) -> BTreeSet<String> {
databases.iter().map(|database| database.base.clone()).collect()
}
fn spellings<T: serde::Serialize>(variants: &[T]) -> BTreeSet<String> {
variants
.iter()
.map(|variant| {
serde_json::to_value(variant)
.expect("serializing a variant")
.as_str()
.expect("an enum variant serializes to a string")
.to_owned()
})
.collect()
}
fn assert_readers_match_the_wire<T>(variants: &[T])
where
T: serde::Serialize + std::fmt::Display + Copy,
{
for variant in variants {
let sent = serde_json::to_value(variant)
.expect("serializing a variant")
.as_str()
.expect("an enum variant serializes to a string")
.to_owned();
assert_eq!(variant.to_string(), sent, "Display disagrees with the wire spelling");
}
}
fn set(values: &[impl AsRef<str>]) -> BTreeSet<String> {
values.iter().map(|value| value.as_ref().to_owned()).collect()
}