replace `if let {unreachable!()}` with `assert!(matches!())` and add test setup description

This commit is contained in:
maotao 2022-06-24 09:59:11 +08:00
parent 530a0d7867
commit efe0a7dec0
1 changed files with 14 additions and 8 deletions

View File

@ -104,6 +104,7 @@ impl Parser {
// check for max allowed size // check for max allowed size
if length > max_size { if length > max_size {
// drop the payload
src.advance(length); src.advance(length);
return Err(ProtocolError::Overflow); return Err(ProtocolError::Overflow);
} }
@ -337,20 +338,25 @@ mod tests {
#[test] #[test]
fn test_parse_frame_max_size_recoverability() { fn test_parse_frame_max_size_recoverability() {
let mut buf = let mut buf = BytesMut::new();
BytesMut::from(&[0b0000_0001u8, 0b0000_0010u8, 0b0000_0000u8, 0b0000_0000u8][..]); // The first text frame with length == 2, payload doesn't matter.
buf.extend(&[0b0000_0010u8, 0b0000_0010u8, 0xffu8, 0xffu8]); buf.extend(&[0b0000_0001u8, 0b0000_0010u8, 0b0000_0000u8, 0b0000_0000u8]);
// Next binary frame with length == 2 and payload == `[0x1111_1111u8, 0x1111_1111u8]`.
buf.extend(&[0b0000_0010u8, 0b0000_0010u8, 0b1111_1111u8, 0b1111_1111u8]);
assert_eq!(buf.len(), 8); assert_eq!(buf.len(), 8);
if let Err(ProtocolError::Overflow) = Parser::parse(&mut buf, false, 1) { assert!(matches!(
} else { Parser::parse(&mut buf, false, 1),
unreachable!("error"); Err(ProtocolError::Overflow)
} ));
assert_eq!(buf.len(), 4); assert_eq!(buf.len(), 4);
let frame = extract(Parser::parse(&mut buf, false, 2)); let frame = extract(Parser::parse(&mut buf, false, 2));
assert!(!frame.finished); assert!(!frame.finished);
assert_eq!(frame.opcode, OpCode::Binary); assert_eq!(frame.opcode, OpCode::Binary);
assert_eq!(frame.payload, Bytes::from(vec![0xffu8, 0xffu8])); assert_eq!(
frame.payload,
Bytes::from(vec![0b1111_1111u8, 0b1111_1111u8])
);
assert_eq!(buf.len(), 0); assert_eq!(buf.len(), 0);
} }