[domistream] Tests: rustfmt

This commit is contained in:
2026-11-25 12:52:38 +01:00
parent 948f446a13
commit da1f3afd52
16 changed files with 1015 additions and 293 deletions
+184 -56
View File
@@ -13,9 +13,7 @@ use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, NO_PEER_ID,
encode_datagram, parse_datagram,
};
use domistream::enet::{
Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE,
};
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE};
use domistream::{Error, Instant};
use proptest::prelude::*;
@@ -29,7 +27,12 @@ fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandB
fn ping_vector() {
// peer 1, session 0, sent-time flag; ping with acknowledge flag on channel 0xFF, reliable sequence 1.
let bytes = [0x80, 0x01, 0x12, 0x34, 0x85, 0xFF, 0x00, 0x01];
let want = Datagram { peer_id: 1, session_id: 0, sent_time: Some(0x1234), commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)] };
let want = Datagram {
peer_id: 1,
session_id: 0,
sent_time: Some(0x1234),
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
};
assert_eq!(parse_datagram(&bytes).unwrap(), want);
assert_eq!(encode_datagram(&want).unwrap(), bytes);
}
@@ -73,7 +76,14 @@ fn params(connect_id: u32) -> ConnectParams {
}
fn frag(start: u16, count: u32, number: u32, total: u32, offset: u32, data: Vec<u8>) -> Fragment {
Fragment { start_sequence: start, fragment_count: count, fragment_number: number, total_length: total, fragment_offset: offset, data }
Fragment {
start_sequence: start,
fragment_count: count,
fragment_number: number,
total_length: total,
fragment_offset: offset,
data,
}
}
/// Every command kind, with the total size PROTOCOL.md 3.1 gives for it.
@@ -107,7 +117,12 @@ fn every_command_round_trips_with_its_wire_size() {
assert_eq!(parse_datagram(&bytes).unwrap(), d);
}
}
let all = Datagram { peer_id: 0x0FFF, session_id: 3, sent_time: Some(1), commands: every_command().into_iter().map(|(c, _)| c).collect() };
let all = Datagram {
peer_id: 0x0FFF,
session_id: 3,
sent_time: Some(1),
commands: every_command().into_iter().map(|(c, _)| c).collect(),
};
assert_eq!(parse_datagram(&encode_datagram(&all).unwrap()).unwrap(), all);
}
@@ -130,7 +145,12 @@ fn kind(b: &CommandBody) -> u8 {
#[test]
fn unsequenced_carries_its_flag() {
let d = Datagram { peer_id: 0, session_id: 0, sent_time: None, commands: vec![cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 1, data: vec![1] })] };
let d = Datagram {
peer_id: 0,
session_id: 0,
sent_time: None,
commands: vec![cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 1, data: vec![1] })],
};
let bytes = encode_datagram(&d).unwrap();
assert_eq!(bytes[2] & 0x40, 0x40, "unsequenced flag");
}
@@ -153,7 +173,13 @@ fn hostile_truncation() {
assert_err!(parse_datagram(bad), Error::Truncated { .. }, "{why}");
}
// A connect cut at every length.
let full = encode_datagram(&Datagram { peer_id: NO_PEER_ID, session_id: 0, sent_time: Some(0), commands: vec![every_command()[1].0.clone()] }).unwrap();
let full = encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(0),
commands: vec![every_command()[1].0.clone()],
})
.unwrap();
for cut in 5..full.len() {
assert_err!(parse_datagram(&full[..cut]), Error::Truncated { .. }, "connect cut at {cut}");
}
@@ -162,12 +188,23 @@ fn hostile_truncation() {
#[test]
fn hostile_values() {
assert_err!(parse_datagram(&[0x40, 0x01, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed");
assert_err!(parse_datagram(&[0xC0, 0x01, 0x00, 0x00, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed + time");
assert_err!(
parse_datagram(&[0xC0, 0x01, 0x00, 0x00, 0x85, 0xFF, 0x00, 0x01]),
Error::UnexpectedValue { .. },
"compressed + time"
);
for number in [0u8, 13, 14, 15] {
assert_err!(parse_datagram(&[0x00, 0x01, 0x80 | number, 0xFF, 0x00, 0x01, 0, 0, 0, 0]), Error::UnexpectedValue { .. }, "command {number}");
assert_err!(
parse_datagram(&[0x00, 0x01, 0x80 | number, 0xFF, 0x00, 0x01, 0, 0, 0, 0]),
Error::UnexpectedValue { .. },
"command {number}"
);
}
// A good command followed by an unknown one: the whole datagram is refused.
assert_err!(parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]), Error::UnexpectedValue { .. });
assert_err!(
parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]),
Error::UnexpectedValue { .. }
);
}
#[test]
@@ -202,42 +239,62 @@ fn hostile_sizes() {
#[test]
fn encode_refuses_oversized() {
let many = Datagram { peer_id: 0, session_id: 0, sent_time: None, commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping); MAX_COMMANDS_PER_DATAGRAM + 1] };
let many = Datagram {
peer_id: 0,
session_id: 0,
sent_time: None,
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping); MAX_COMMANDS_PER_DATAGRAM + 1],
};
assert!(matches!(encode_datagram(&many), Err(Error::TooLarge { .. })));
let big = Datagram { peer_id: 0, session_id: 0, sent_time: None, commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(vec![0; MAX_DATAGRAM_BYTES]))] };
let big = Datagram {
peer_id: 0,
session_id: 0,
sent_time: None,
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(vec![0; MAX_DATAGRAM_BYTES]))],
};
assert!(matches!(encode_datagram(&big), Err(Error::TooLarge { .. })));
}
fn body() -> impl Strategy<Value = CommandBody> {
let data = || proptest::collection::vec(any::<u8>(), 0..64);
let fragment = || (any::<u16>(), any::<u32>(), any::<u32>(), any::<u32>(), any::<u32>(), data())
.prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f));
let cparams = || proptest::array::uniform12(any::<u32>()).prop_map(|a| ConnectParams {
outgoing_peer_id: (a[0] & 0xFFFF) as u16,
incoming_session_id: a[1] as u8,
outgoing_session_id: (a[1] >> 8) as u8,
mtu: a[2],
window_size: a[3],
channel_count: a[4],
incoming_bandwidth: a[5],
outgoing_bandwidth: a[6],
packet_throttle_interval: a[7],
packet_throttle_acceleration: a[8],
packet_throttle_deceleration: a[9],
connect_id: a[10],
});
let fragment = || {
(any::<u16>(), any::<u32>(), any::<u32>(), any::<u32>(), any::<u32>(), data())
.prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f))
};
let cparams = || {
proptest::array::uniform12(any::<u32>()).prop_map(|a| ConnectParams {
outgoing_peer_id: (a[0] & 0xFFFF) as u16,
incoming_session_id: a[1] as u8,
outgoing_session_id: (a[1] >> 8) as u8,
mtu: a[2],
window_size: a[3],
channel_count: a[4],
incoming_bandwidth: a[5],
outgoing_bandwidth: a[6],
packet_throttle_interval: a[7],
packet_throttle_acceleration: a[8],
packet_throttle_deceleration: a[9],
connect_id: a[10],
})
};
prop_oneof![
(any::<u16>(), any::<u16>()).prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }),
(any::<u16>(), any::<u16>())
.prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }),
(cparams(), any::<u32>()).prop_map(|(params, data)| CommandBody::Connect { params, data }),
cparams().prop_map(CommandBody::VerifyConnect),
any::<u32>().prop_map(|data| CommandBody::Disconnect { data }),
Just(CommandBody::Ping),
data().prop_map(CommandBody::SendReliable),
(any::<u16>(), data()).prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }),
(any::<u16>(), data())
.prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }),
fragment().prop_map(CommandBody::SendFragment),
(any::<u16>(), data()).prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }),
(any::<u32>(), any::<u32>()).prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }),
(any::<u32>(), any::<u32>(), any::<u32>()).prop_map(|(interval, acceleration, deceleration)| CommandBody::ThrottleConfigure { interval, acceleration, deceleration }),
(any::<u16>(), data())
.prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }),
(any::<u32>(), any::<u32>())
.prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }),
(any::<u32>(), any::<u32>(), any::<u32>()).prop_map(|(interval, acceleration, deceleration)| {
CommandBody::ThrottleConfigure { interval, acceleration, deceleration }
}),
fragment().prop_map(CommandBody::SendUnreliableFragment),
]
}
@@ -299,7 +356,13 @@ struct Link {
impl Link {
fn host_datagram(&self, commands: Vec<Command>) -> Vec<u8> {
encode_datagram(&Datagram { peer_id: self.to_client, session_id: 0, sent_time: Some(self.now_ms as u16), commands }).unwrap()
encode_datagram(&Datagram {
peer_id: self.to_client,
session_id: 0,
sent_time: Some(self.now_ms as u16),
commands,
})
.unwrap()
}
fn feed(&mut self, commands: Vec<Command>) -> domistream::Result<()> {
@@ -350,7 +413,8 @@ fn start() -> (EnetClient, Datagram, ConnectParams, u32, u16) {
let mut client = EnetClient::connect(config(), at(0), &mut SeqRng::new(5)).expect("EnetClient::connect");
assert_eq!(client.state(), EnetState::Connecting);
let d = parse_datagram(&client.poll_transmit(at(0)).expect("connect datagram")).unwrap();
let c = d.commands.iter().find(|c| matches!(c.body, CommandBody::Connect { .. })).expect("a connect command").clone();
let c =
d.commands.iter().find(|c| matches!(c.body, CommandBody::Connect { .. })).expect("a connect command").clone();
let (params, data) = match c.body {
CommandBody::Connect { params, data } => (params, data),
_ => unreachable!(),
@@ -364,7 +428,15 @@ fn connected() -> Link {
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
link.feed(vec![
cmd(false, 0xFF, 0, CommandBody::Acknowledge { received_reliable_sequence: connect_seq, received_sent_time: d.sent_time.unwrap_or(0) }),
cmd(
false,
0xFF,
0,
CommandBody::Acknowledge {
received_reliable_sequence: connect_seq,
received_sent_time: d.sent_time.unwrap_or(0),
},
),
cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify)),
])
.expect("verify connect");
@@ -398,7 +470,11 @@ fn connect_refuses_configs_outside_enet_limits() {
] {
assert_err!(EnetClient::connect(bad, at(0), &mut SeqRng::new(1)), Error::Malformed { .. }, "{bad:?}");
}
for ok in [EnetConfig { mtu: 576, ..config() }, EnetConfig { mtu: 4096, ..config() }, EnetConfig { channel_count: 255, ..config() }] {
for ok in [
EnetConfig { mtu: 576, ..config() },
EnetConfig { mtu: 4096, ..config() },
EnetConfig { channel_count: 255, ..config() },
] {
assert!(EnetClient::connect(ok, at(0), &mut SeqRng::new(1)).is_ok(), "{ok:?}");
}
}
@@ -407,7 +483,13 @@ fn connect_refuses_configs_outside_enet_limits() {
fn verify_with_wrong_connect_id_does_not_connect() {
let (client, _, params, _, _) = start();
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
let verify = ConnectParams { connect_id: params.connect_id ^ 1, outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
let verify = ConnectParams {
connect_id: params.connect_id ^ 1,
outgoing_peer_id: 0,
incoming_session_id: 0,
outgoing_session_id: 0,
..params
};
let _ = link.feed(vec![cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]);
assert_eq!(link.client.state(), EnetState::Connecting);
assert!(link.events().is_empty());
@@ -420,7 +502,11 @@ fn garbage_never_changes_state() {
assert!(link.client.handle_datagram(at(5), bad).is_err(), "{bad:?}");
assert_eq!(link.client.state(), EnetState::Connected);
}
assert_too_large!(link.client.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1);
assert_too_large!(
link.client.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]),
MAX_DATAGRAM_BYTES,
MAX_DATAGRAM_BYTES + 1
);
assert!(link.events().is_empty());
}
@@ -428,7 +514,13 @@ fn garbage_never_changes_state() {
fn datagrams_for_another_peer_are_dropped() {
let mut link = connected();
let c = link.reliable(0, b"not for you");
let other = encode_datagram(&Datagram { peer_id: link.to_client ^ 0x0001, session_id: 0, sent_time: Some(1), commands: vec![c] }).unwrap();
let other = encode_datagram(&Datagram {
peer_id: link.to_client ^ 0x0001,
session_id: 0,
sent_time: Some(1),
commands: vec![c],
})
.unwrap();
assert_eq!(link.client.handle_datagram(at(9), &other), Ok(()));
assert!(link.events().is_empty());
}
@@ -448,7 +540,12 @@ fn reliable_in_order_reordered_and_duplicated() {
link.feed(vec![a, b.clone(), c]).unwrap();
link.feed(vec![b]).unwrap();
assert!(link.received().is_empty());
let acks: usize = link.transmitted().iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::Acknowledge { .. })).count();
let acks: usize = link
.transmitted()
.iter()
.flat_map(|d| &d.commands)
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
.count();
assert!(acks >= 4, "duplicates are still acknowledged ({acks})");
}
@@ -508,7 +605,12 @@ fn fragments(link: &mut Link, data: &[u8], piece: usize) -> Vec<Command> {
link.host_seq[0] = link.host_seq[0].wrapping_add(1);
let off = n as usize * piece;
let chunk = data[off..(off + piece).min(data.len())].to_vec();
cmd(true, 0, link.host_seq[0], CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk)))
cmd(
true,
0,
link.host_seq[0],
CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk)),
)
})
.collect()
}
@@ -531,24 +633,30 @@ fn fragments_with_lying_lengths() {
let mut link = connected();
link.host_seq[0] += 1;
let s = link.host_seq[0];
let r = link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(frag(s, 2, 0, MAX_PACKET_BYTES as u32 + 1, 0, vec![0; 100])))]);
let r = link.feed(vec![cmd(
true,
0,
s,
CommandBody::SendFragment(frag(s, 2, 0, MAX_PACKET_BYTES as u32 + 1, 0, vec![0; 100])),
)]);
assert_too_large!(r, MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1);
assert!(link.events().is_empty());
// Other lies: never delivered, never a panic, the connection survives.
for f in [
frag(0, 0, 0, 10, 0, vec![0; 10]), // zero fragments
frag(0, 2, 2, 20, 0, vec![0; 10]), // number >= count
frag(0, 2, 0, 20, 15, vec![0; 10]), // offset + length past total
frag(0, 2, 0, 5, 0, vec![0; 10]), // fragment longer than total
frag(0, u32::MAX, 0, 100, 0, vec![0; 10]), // absurd count for a small total
frag(0, 2, 0, u32::MAX, 0, vec![0; 10]), // absurd total
frag(0, 2, 1, 20, u32::MAX - 3, vec![0; 10]), // offset overflow
frag(0, 0, 0, 10, 0, vec![0; 10]), // zero fragments
frag(0, 2, 2, 20, 0, vec![0; 10]), // number >= count
frag(0, 2, 0, 20, 15, vec![0; 10]), // offset + length past total
frag(0, 2, 0, 5, 0, vec![0; 10]), // fragment longer than total
frag(0, u32::MAX, 0, 100, 0, vec![0; 10]), // absurd count for a small total
frag(0, 2, 0, u32::MAX, 0, vec![0; 10]), // absurd total
frag(0, 2, 1, 20, u32::MAX - 3, vec![0; 10]), // offset overflow
] {
let mut link = connected();
link.host_seq[0] += 1;
let s = link.host_seq[0];
let r = link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(Fragment { start_sequence: s, ..f.clone() }))]);
let r =
link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(Fragment { start_sequence: s, ..f.clone() }))]);
assert!(link.events().is_empty(), "{f:?} -> {r:?}");
assert_eq!(link.client.state(), EnetState::Connected, "{f:?}");
}
@@ -609,20 +717,40 @@ fn reliable_sends_are_retransmitted_until_acknowledged() {
let mut link = connected();
link.client.send(at(10), 0, Delivery::Reliable, b"hello").unwrap();
let first = link.transmitted();
let sent = first.iter().flat_map(|d| &d.commands).find(|c| c.body == CommandBody::SendReliable(b"hello".to_vec())).expect("sent").clone();
let sent = first
.iter()
.flat_map(|d| &d.commands)
.find(|c| c.body == CommandBody::SendReliable(b"hello".to_vec()))
.expect("sent")
.clone();
let when = link.client.poll_timeout().expect("a retransmission deadline");
link.now_ms = when.as_micros() / 1000 + 1;
link.client.handle_timeout(at(link.now_ms)).unwrap();
let again = link.transmitted();
assert!(again.iter().flat_map(|d| &d.commands).any(|c| c.reliable_sequence == sent.reliable_sequence && c.body == sent.body), "retransmitted");
assert!(
again
.iter()
.flat_map(|d| &d.commands)
.any(|c| c.reliable_sequence == sent.reliable_sequence && c.body == sent.body),
"retransmitted"
);
// Acknowledge it: no more retransmissions of that command.
link.feed(vec![cmd(false, 0, 0, CommandBody::Acknowledge { received_reliable_sequence: sent.reliable_sequence, received_sent_time: 10 })]).unwrap();
link.feed(vec![cmd(
false,
0,
0,
CommandBody::Acknowledge { received_reliable_sequence: sent.reliable_sequence, received_sent_time: 10 },
)])
.unwrap();
for _ in 0..5 {
if let Some(t) = link.client.poll_timeout() {
link.now_ms = link.now_ms.max(t.as_micros() / 1000 + 1);
link.client.handle_timeout(at(link.now_ms)).unwrap();
}
assert!(!link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body), "acknowledged command sent again");
assert!(
!link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body),
"acknowledged command sent again"
);
}
}