use fauna_api::authentification::{Credentials, Profile};
use fauna_api::groups::Group;
use fauna_api::integrations::Platform;
use fauna_api::shared::schema::{PrimitiveType, Schema};
use serde_json::json;
#[test]
fn credentials_read_the_authorize_response() {
let credentials: Credentials = serde_json::from_value(json!({
"id": "42",
"email": "premium@faunakit.com",
"phone": "+15555550100",
"emailVerified": true,
"phoneVerified": false,
"permissions": ["fauna/groups:10", "fauna/groups:create"],
"integrations": ["GOOGLE", "WHATSAPP"],
"displayName": "Premium",
"apiKeys": [{ "id": "key", "balance": 1.5, "services": ["parrot"] }],
"balance": 12.25
}))
.unwrap();
assert_eq!(credentials.email, "premium@faunakit.com");
assert_eq!(credentials.phone, "+15555550100");
assert!(credentials.email_verified);
assert!(!credentials.phone_verified);
assert_eq!(
credentials.integrations,
vec![Platform::Google, Platform::WhatsApp]
);
assert_eq!(credentials.display_name.as_deref(), Some("Premium"));
assert_eq!(credentials.api_keys[0].services, vec!["parrot"]);
assert_eq!(credentials.token, "");
}
#[test]
fn groups_read_the_group_response() {
let body = json!({
"id": "7",
"name": "League",
"balance": 0,
"createdAt": "2026-10-14T05:00:00.000Z",
"admins": ["organizer@example.com"],
"people": ["organizer@example.com"],
"groups": [{ "id": "8", "name": "Tigers" }],
"members": [
{ "email": "organizer@example.com", "through": "7" },
{ "email": "coach@example.com", "displayName": "Coach", "through": "8" }
],
"through": "8"
});
let group = Group::from_json(&body);
let parsed: Group = serde_json::from_value(body).unwrap();
assert_eq!(group.name, "League");
assert_eq!(group.groups[0].name, "Tigers");
assert_eq!(group.members[1].display_name.as_deref(), Some("Coach"));
assert_eq!(group.members[1].through, "8");
assert_eq!(group.through, "8");
assert_eq!(group.created_at.to_rfc3339(), "2026-10-14T05:00:00+00:00");
assert_eq!(parsed.members, group.members);
}
#[test]
fn groups_read_nests_and_offers() {
use fauna_api::groups::{GroupNest, NestOffer, NestSide};
let nest = GroupNest::from_json(&json!({
"token": "abc",
"parent": { "id": "7", "name": "League" },
"child": { "id": "8", "name": "Tigers", "icon": "https://example.com/t.png" },
"from": "child",
"by": "coach@example.com",
"expires": "2026-10-21T05:00:00.000Z"
}));
assert_eq!(nest.from, NestSide::Child);
assert_eq!(
nest.child.icon.as_deref(),
Some("https://example.com/t.png")
);
assert_eq!(nest.by.as_deref(), Some("coach@example.com"));
assert_eq!(
NestOffer::from_json(&json!({ "nested": true })),
NestOffer::Nested
);
assert_eq!(
NestOffer::from_json(&json!({ "nested": false, "token": "abc" })),
NestOffer::Waiting {
token: "abc".to_string()
}
);
}
#[test]
fn groups_read_email_invites() {
use fauna_api::groups::EmailInvite;
let invite = EmailInvite::from_json(&json!({
"token": "abc",
"email": "sam@example.com",
"by": "coach@example.com",
"expires": "2026-10-21T05:00:00.000Z"
}));
assert_eq!(invite.email, "sam@example.com");
assert_eq!(invite.by.as_deref(), Some("coach@example.com"));
assert_eq!(invite.expires.to_rfc3339(), "2026-10-21T05:00:00+00:00");
assert!(
EmailInvite::from_json(
&json!({ "token": "t", "email": "a@b.c", "expires": "2026-10-21T05:00:00.000Z" })
)
.by
.is_none()
);
}
#[test]
fn webhooks_read_group_changes() {
use fauna_api::webhooks::{
Delivery, EventType, GroupChange, GroupChangeMember, GroupChangeReason,
};
let joined: Delivery = serde_json::from_value(json!({
"id": "evt_1",
"type": "group.joined",
"created": 1_760_000_000_000_i64,
"data": {
"group": { "id": "7", "name": "League" },
"member": { "group": { "id": "8", "name": "Tigers" } },
"reason": "joined"
}
}))
.unwrap();
assert_eq!(joined.r#type, EventType::GroupJoined);
let change: GroupChange = serde_json::from_value(joined.data).unwrap();
assert_eq!(change.group.name, "League");
assert_eq!(change.reason, GroupChangeReason::Joined);
let GroupChangeMember::Group { group } = change.member else {
panic!("expected a nested group");
};
assert_eq!(group.id, "8");
let left: Delivery = serde_json::from_value(json!({
"id": "evt_2",
"type": "group.left",
"created": 1_760_000_000_000_i64,
"data": {
"group": { "id": "8", "name": "Tigers" },
"member": { "email": "sam@example.com" },
"reason": "removed"
}
}))
.unwrap();
assert_eq!(left.r#type, EventType::GroupLeft);
let change: GroupChange = serde_json::from_value(left.data).unwrap();
assert_eq!(change.reason, GroupChangeReason::Removed);
assert_eq!(
change.member,
GroupChangeMember::Person {
email: "sam@example.com".to_string()
}
);
}
#[test]
fn rooms_read_owner_groups_and_people() {
use fauna_api::rooms::{LiveRoom, Member, Person, Role};
let room = LiveRoom::from_json(&json!({
"id": "r1",
"name": "Final",
"group": "7",
"members": [{ "group": "8", "role": "read" }, { "email": "ref@example.com", "role": "write" }],
"state": { "score": [0, 0] },
"version": 1,
"created": "2026-10-14T05:00:00.000Z",
"updated": "2026-10-14T05:00:00.000Z"
}));
assert_eq!(room.group.as_deref(), Some("7"));
assert_eq!(
room.members[1],
Member::Email {
email: "ref@example.com".to_string(),
role: Role::Write
}
);
let person = Person::from_json(&json!({
"profile": { "email": "coach@example.com" },
"groups": [{ "id": "7", "through": "8" }]
}));
assert_eq!(person.profile.email, "coach@example.com");
assert_eq!(person.groups[0].through, "8");
}
#[test]
fn parrot_chats_read_the_chat_list() {
use fauna_api::parrot::chat::ChatSummary;
use fauna_api::parrot::generative::{Author, Content, Part, Role};
let chats: Vec<ChatSummary> = serde_json::from_value(json!([
{
"id": "3", "name": "Tigers", "principalId": "group:7", "human": true,
"created": 1_760_000_000_000_i64, "updated": 1_760_000_100_000_i64, "unread": 2,
"last": { "parts": [{ "type": "TEXT", "text": "Practice at 6" }], "role": "USER", "createdAt": "2026-10-14T05:00:00.000Z", "author": { "email": "coach@example.com" } }
},
{ "id": "4", "name": "Notes", "principalId": "credentials:1", "human": false, "created": 1, "updated": 2, "last": null }
]))
.unwrap();
assert!(chats[0].human);
assert_eq!(chats[0].unread, 2);
assert!(
matches!(&chats[0].last.as_ref().unwrap().author, Some(Author::Profile(p)) if p.email == "coach@example.com")
);
assert!(chats[1].last.is_none());
let last = Content::from_json(
&json!({
"parts": [{ "type": "TEXT", "text": "Practice at 6" }],
"role": "USER",
"createdAt": "2026-10-14T05:00:00.000Z",
"author": { "email": "coach@example.com" }
}),
None,
);
assert_eq!(last.role, Role::User);
assert!(matches!(&last.parts[0], Part::Text(text) if text.text == "Practice at 6"));
assert!(matches!(&last.author, Some(Author::Profile(p)) if p.email == "coach@example.com"));
let by_key = Content::from_json(
&json!({ "role": "USER", "author": { "name": "Claude" } }),
None,
);
assert!(
matches!(&by_key.author, Some(Author::ApiKey(key)) if key.name.as_deref() == Some("Claude"))
);
assert_eq!(
Content::from_json(&json!({ "author": "MODEL" }), None).author,
Some(Author::Model)
);
assert_eq!(
Content::from_json(&json!({ "author": "+15550001111" }), None).author,
Some(Author::Address("+15550001111".to_string()))
);
}
#[test]
fn profiles_serialize_in_camel_case() {
let profile = Profile {
email: "a@b.c".to_string(),
display_name: Some("A".to_string()),
icon: None,
};
assert_eq!(
serde_json::to_value(profile).unwrap(),
json!({ "email": "a@b.c", "displayName": "A" })
);
}
#[test]
fn schemas_round_trip_by_type() {
let value = json!({
"type": "OBJECT",
"properties": {
"name": { "type": "STRING", "pattern": "^[a-z]+$" },
"tags": { "type": "ARRAY", "items": { "type": "STRING", "enum": ["a", "b"] } }
},
"required": ["name"]
});
let schema: Schema = serde_json::from_value(value.clone()).unwrap();
let Schema::Object(object) = &schema else {
panic!("expected an object schema");
};
let properties = object.properties.as_ref().unwrap();
assert!(
matches!(&properties["name"], Schema::Primitive(primitive) if primitive.r#type == PrimitiveType::String)
);
assert!(matches!(&properties["tags"], Schema::Array(_)));
assert_eq!(serde_json::to_value(&schema).unwrap(), value);
}
#[test]
fn billing_formats_like_intl_number_format() {
assert_eq!(fauna_api::billing::format(0.0), "$0.00");
assert_eq!(fauna_api::billing::format(1234.5), "$1,234.50");
assert_eq!(fauna_api::billing::format(1_000_000.0), "$1,000,000.00");
assert_eq!(fauna_api::billing::format(-12.345), "-$12.35");
}
#[test]
fn ticket_chat_turns_on_only_for_the_reporter_alone() {
use fauna_api::tickets::ticket_chat_auto_enabled;
assert!(ticket_chat_auto_enabled(
[" Reporter@Example.com "],
"reporter@example.com"
));
assert!(!ticket_chat_auto_enabled(
["reporter@example.com", "staff@example.com"],
"reporter@example.com"
));
assert!(!ticket_chat_auto_enabled(
["staff@example.com"],
"reporter@example.com"
));
assert!(!ticket_chat_auto_enabled(["reporter@example.com"], " "));
}
#[tokio::test]
async fn webhooks_verify_the_fauna_signature() {
use fauna_api::webhooks::{ChatMessage, Delivery, EventType, verify};
use hmac::{Hmac, Mac};
use sha2::Sha256;
let body = json!({
"id": "evt_1",
"type": "chat.message",
"created": 1_760_000_000_000_i64,
"data": {
"chatId": "3",
"chatName": "Tigers",
"group": "7",
"position": 12,
"author": { "email": "coach@example.com", "displayName": "Coach" },
"text": "@Sam bring the cones",
"mentions": [{ "email": "sam@example.com" }],
"created": 1_760_000_000_000_i64
}
})
.to_string();
let t = chrono::Utc::now().timestamp();
let mut mac = Hmac::<Sha256>::new_from_slice(b"whsec_test_secret_123").unwrap();
mac.update(format!("{t}.{body}").as_bytes());
let digest: String = mac
.finalize()
.into_bytes()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
let signature = format!("t={t},v1={digest}");
assert!(
verify("whsec_test_secret_123", &body, &signature, None)
.await
.unwrap()
);
assert!(
!verify("another_secret_value", &body, &signature, None)
.await
.unwrap()
);
assert!(
!verify(
"whsec_test_secret_123",
&format!("{body} "),
&signature,
None
)
.await
.unwrap()
);
let stale = format!("t={},v1={digest}", t - 600);
assert!(
!verify("whsec_test_secret_123", &body, &stale, None)
.await
.unwrap()
);
let delivery: Delivery = serde_json::from_str(&body).unwrap();
assert_eq!(delivery.r#type, EventType::ChatMessage);
let message: ChatMessage = serde_json::from_value(delivery.data).unwrap();
assert_eq!(message.mentions[0].email, "sam@example.com");
assert!(message.reaction.is_none());
}
#[test]
fn maps_read_routes_forecasts_and_passes() {
use fauna_api::maps::{Condition, Forecast, Route, TilePass, TravelMode, Units};
let routes: Vec<Route> = serde_json::from_value(json!([{
"mode": "transit",
"duration": 5419,
"distance": 29845,
"path": [{ "latitude": 30.2, "longitude": -97.6 }],
"steps": [{
"mode": "transit",
"instruction": "Bus towards University of Texas NB",
"distance": 14198,
"duration": 1875,
"line": "20",
"vehicle": "bus",
"stops": 31,
"departure": "2026-10-16T14:05:00Z"
}],
"fare": { "amount": 2.5, "currency": "USD" },
"departure": "2026-10-16T14:05:00Z"
}]))
.unwrap();
assert_eq!(routes[0].mode, TravelMode::Transit);
assert_eq!(routes[0].steps[0].stops, Some(31));
assert_eq!(routes[0].fare.as_ref().unwrap().amount, 2.5);
let forecast: Forecast = serde_json::from_value(json!({
"units": "imperial",
"timeZone": "America/Chicago",
"days": [{ "date": "2026-10-14", "high": 89.9, "low": 72.1, "condition": "partly_cloudy", "summary": "Partly cloudy", "precipitation": 10, "wind": 11 }],
"hours": [{ "time": "2026-10-14T20:00:00Z", "temperature": 84, "feelsLike": 88, "condition": "thunderstorm", "summary": "Storms", "precipitation": 40, "wind": 9 }]
}))
.unwrap();
assert_eq!(forecast.units, Units::Imperial);
assert_eq!(forecast.days[0].condition, Condition::PartlyCloudy);
assert_eq!(forecast.hours[0].feels_like, 88.0);
let pass: TilePass = serde_json::from_value(json!({
"id": "abc.def",
"tiles": 150,
"expires": "2026-10-15T08:00:00.000Z",
"size": 256,
"maxZoom": 22,
"attribution": { "text": "Map data", "logo": "https://example.com/logo.png" }
}))
.unwrap();
assert_eq!(pass.max_zoom, 22);
assert!(
fauna_api::maps::get_tile_url(&pass).ends_with("/maps/tile?pass=abc.def&z={z}&x={x}&y={y}")
);
}
#[test]
fn travel_reads_flights_and_hotels() {
use fauna_api::travel::{Flight, Hotel};
let flights: Vec<Flight> = serde_json::from_value(json!([{
"id": "fl_x",
"price": { "amount": 50, "currency": "USD" },
"duration": 8820,
"stops": 0,
"from": "AUS",
"to": "DEN",
"departure": "2026-11-24T20:04",
"arrival": "2026-11-24T21:31",
"airlines": ["Frontier"],
"legs": [{
"airline": "Frontier",
"number": "F9 2047",
"from": { "code": "AUS", "name": "Austin" },
"to": { "code": "DEN", "name": "Denver" },
"departure": "2026-11-24T20:04",
"arrival": "2026-11-24T21:31",
"duration": 8820
}]
}]))
.unwrap();
assert_eq!(flights[0].legs[0].to.code, "DEN");
let hotels: Vec<Hotel> = serde_json::from_value(json!([{
"id": "ht_x",
"name": "Hyatt Place Austin Downtown",
"rating": 4.7,
"nightly": { "amount": 108, "currency": "USD" },
"amenities": ["Free Wi-Fi"],
"offers": [{ "seller": "Hyatt", "url": "https://www.hyatt.com" }]
}]))
.unwrap();
assert_eq!(hotels[0].offers[0].seller, "Hyatt");
assert!(hotels[0].coordinates.is_none());
}