use bincode::{Decode, Encode}; use packet_service::packet::{Packet, PacketPayload}; use packet_service::packet_type::PacketType; // Define a test payload struct #[derive(Debug, Encode, Decode, PartialEq)] struct TestPayload { id: u32, name: String, value: f32, } impl PacketPayload for TestPayload {} #[test] fn test_packet_creation() { let payload = TestPayload { id: 123, name: "test".to_string(), value: 3.14, }; let packet = Packet::new(PacketType::PakcsAlive, &payload).unwrap(); // Check packet fields assert_eq!(packet.packet_type, PacketType::PakcsAlive); assert_eq!(packet.packet_crc, 0); // CRC is currently not implemented assert!(!packet.payload.is_empty()); } #[test] fn test_packet_serialization_deserialization() { let original_payload = TestPayload { id: 456, name: "serialization_test".to_string(), value: 2.71, }; // Create a packet let packet = Packet::new(PacketType::PakcsAlive, &original_payload).unwrap(); // Serialize to raw bytes let raw_data = packet.to_raw(); // Deserialize from raw bytes let deserialized_packet = Packet::from_raw(&raw_data).unwrap(); // Check packet fields match assert_eq!(deserialized_packet.packet_type, packet.packet_type); assert_eq!(deserialized_packet.packet_size, packet.packet_size); assert_eq!(deserialized_packet.packet_crc, packet.packet_crc); // Parse the payload let deserialized_payload: TestPayload = deserialized_packet.parse().unwrap(); // Check payload fields match assert_eq!(deserialized_payload, original_payload); } #[test] fn test_packet_from_raw_invalid_size() { // Create a packet with invalid size (too small) let raw_data = vec![0, 0, 0, 0]; // Only 4 bytes, less than minimum 6 bytes let result = Packet::from_raw(&raw_data); assert!(result.is_err()); } #[test] fn test_packet_from_raw_size_mismatch() { // Create a packet with size mismatch let mut raw_data = vec![0; 10]; // 10 bytes // Set packet size to 20 (more than actual data) raw_data[0] = 20; raw_data[1] = 0; let result = Packet::from_raw(&raw_data); assert!(result.is_err()); } #[test] fn test_packet_payload_encoding_decoding() { let original_payload = TestPayload { id: 789, name: "encoding_test".to_string(), value: 1.618, }; // Encode payload let encoded = bincode::encode_to_vec(&original_payload, bincode::config::standard()).unwrap(); // Decode payload let decoded: TestPayload = bincode::decode_from_slice(&encoded, bincode::config::standard()).unwrap().0; // Check payload fields match assert_eq!(decoded, original_payload); }