Files
binproto/tests/python_generator.rs
T
2025-11-05 15:00:05 +08:00

311 lines
8.7 KiB
Rust

use binproto::{TargetLanguage, compile_schema};
use std::fs;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
/// Helper function to get unique temp directory name
fn get_temp_dir() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros();
format!("/tmp/binproto_python_test_{}", now)
}
/// Test Python generator with simple struct containing primitives
#[test]
fn test_python_simple_struct() {
// Schema: Basic struct with various primitive types
let schema = r#"
struct Primitives {
u8 a
u7 b
u1 c
u32 d
i32 e
}
"#;
// Parse schema
let parsed_schema = compile_schema(schema).expect("Failed to compile schema");
// Generate Python code
let python_code = binproto::generator::generate(&parsed_schema, TargetLanguage::Python)
.expect("Failed to generate Python code");
// Create temp directory
let temp_dir = get_temp_dir();
fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");
// Write Python module
let module_path = format!("{}/primitives.py", temp_dir);
fs::write(&module_path, python_code).expect("Failed to write Python file");
// Write test script
let test_script = format!(
r#"
import sys
sys.path.insert(0, '{}')
from primitives import Primitives
# Test: Create instance with known values
p = Primitives(a=0x12, b=0x34, c=0x1, d=0xABCD, e=-42)
# Test bitsize calculation
# u8=8, u7=7, u1=1, u32=32, i32=32 → total=80 bits
assert p.bitsize() == 80, f"Expected bitsize 80, got {{p.bitsize()}}"
# Test serialization to bytes
data = p.to_bytes()
print(f"Serialized: {{data.hex()}}")
# Test deserialization from bytes
p2 = Primitives.from_bytes(data)
assert p2.a == 0x12, f"Expected a=0x12, got {{p2.a}}"
assert p2.b == 0x34, f"Expected b=0x34, got {{p2.b}}"
assert p2.c == 0x1, f"Expected c=0x1, got {{p2.c}}"
assert p2.d == 0xABCD, f"Expected d=0xABCD, got {{p2.d}}"
assert p2.e == -42, f"Expected e=-42, got {{p2.e}}"
# Test file I/O
p.to_file('{}/test.bin')
p3 = Primitives.from_file('{}/test.bin')
assert p3.a == 0x12
assert p3.b == 0x34
assert p3.c == 0x1
assert p3.d == 0xABCD
assert p3.e == -42
print("✓ All Python simple struct tests passed")
"#,
temp_dir, temp_dir, temp_dir
);
let test_script_path = format!("{}/test_script.py", temp_dir);
fs::write(&test_script_path, test_script).expect("Failed to write test script");
// Run Python script
let output = Command::new("python3")
.arg(&test_script_path)
.output()
.expect("Failed to run Python script");
// Cleanup
fs::remove_dir_all(&temp_dir).ok();
// Check results
if !output.status.success() {
panic!(
"Python test failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("✓ All Python simple struct tests passed"));
}
/// Test Python generator with nested structs and constant arrays
#[test]
fn test_python_nested_structs() {
// Schema: Nested structures with constant array
let schema = r#"
struct Header {
u8 version
u8 flags
}
struct Data {
u16[3] values
}
struct Packet {
Header header
Data data
}
"#;
// Parse schema
let parsed_schema = compile_schema(schema).expect("Failed to compile schema");
// Generate Python code
let python_code = binproto::generator::generate(&parsed_schema, TargetLanguage::Python)
.expect("Failed to generate Python code");
// Create temp directory
let temp_dir = get_temp_dir();
fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");
// Write Python module
let module_path = format!("{}/packet.py", temp_dir);
fs::write(&module_path, python_code).expect("Failed to write Python file");
// Write test script
let test_script = format!(
r#"
import sys
sys.path.insert(0, '{}')
from packet import Header, Data, Packet
# Test: Create nested instance
h = Header(version=1, flags=0x80)
d = Data(values=[10, 20, 30])
p = Packet(header=h, data=d)
# Test bitsize: u8+u8 + (u16*3) = 16 + 48 = 64 bits
assert p.bitsize() == 64, f"Expected bitsize 64, got {{p.bitsize()}}"
# Test serialization
data = p.to_bytes()
print(f"Serialized nested: {{data.hex()}}")
# Verify specific encoding:
# version=1 (0x01), flags=0x80, values=[10, 20, 30]
# Expected: 01 80 00 0A 00 14 00 1E (big-endian u16)
expected_hex = "0180000a00140014001e" # Note: Depends on endianness
print(f"Expected pattern present: {{expected_hex[:4] in data.hex()}}")
# Test deserialization
p2 = Packet.from_bytes(data)
assert p2.header.version == 1
assert p2.header.flags == 0x80
assert p2.data.values[0] == 10
assert p2.data.values[1] == 20
assert p2.data.values[2] == 30
# Test file I/O
p.to_file('{}/nested_test.bin')
p3 = Packet.from_file('{}/nested_test.bin')
assert p3.header.version == 1
assert p3.header.flags == 0x80
assert len(p3.data.values) == 3
assert p3.data.values[0] == 10
print("✓ All Python nested struct tests passed")
"#,
temp_dir, temp_dir, temp_dir
);
let test_script_path = format!("{}/test_nested_script.py", temp_dir);
fs::write(&test_script_path, test_script).expect("Failed to write test script");
// Run Python script
let output = Command::new("python3")
.arg(&test_script_path)
.output()
.expect("Failed to run Python script");
// Cleanup
fs::remove_dir_all(&temp_dir).ok();
// Check results
if !output.status.success() {
panic!(
"Python nested struct test failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("✓ All Python nested struct tests passed"));
}
/// Test Python generator with dynamic arrays
#[test]
fn test_python_dynamic_arrays() {
// Schema: Dynamic array with length field
let schema = r#"
struct Message {
u8 count
u32[count] items
}
"#;
// Parse schema
let parsed_schema = compile_schema(schema).expect("Failed to compile schema");
// Generate Python code
let python_code = binproto::generator::generate(&parsed_schema, TargetLanguage::Python)
.expect("Failed to generate Python code");
// Create temp directory
let temp_dir = get_temp_dir();
fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");
// Write Python module
let module_path = format!("{}/message.py", temp_dir);
fs::write(&module_path, python_code).expect("Failed to write Python file");
// Write test script
let test_script = format!(
r#"
import sys
sys.path.insert(0, '{}')
from message import Message
# Test 1: Empty array
m1 = Message(count=0, items=[])
assert m1.bitsize() == 8, f"Expected bitsize 8, got {{m1.bitsize()}}"
data1 = m1.to_bytes()
m1_back = Message.from_bytes(data1)
assert m1_back.count == 0
assert len(m1_back.items) == 0
# Test 2: Array with 3 elements
m2 = Message(count=3, items=[100, 200, 300])
# Bitsize: u8(8) + u32*3(96) = 104 bits = 13 bytes
assert m2.bitsize() == 104, f"Expected bitsize 104, got {{m2.bitsize()}}"
data2 = m2.to_bytes()
print(f"Dynamic array serialized: {{data2.hex()}}")
m2_back = Message.from_bytes(data2)
assert m2_back.count == 3, f"Expected count=3, got {{m2_back.count}}"
assert len(m2_back.items) == 3, f"Expected len=3, got {{len(m2_back.items)}}"
assert m2_back.items[0] == 100
assert m2_back.items[1] == 200
assert m2_back.items[2] == 300
# Test 3: File I/O with dynamic array
m2.to_file('{}/dynamic_test.bin')
m3 = Message.from_file('{}/dynamic_test.bin')
assert m3.count == 3
assert len(m3.items) == 3
assert m3.items[0] == 100
assert m3.items[1] == 200
assert m3.items[2] == 300
print("✓ All Python dynamic array tests passed")
"#,
temp_dir, temp_dir, temp_dir
);
let test_script_path = format!("{}/test_dynamic_script.py", temp_dir);
fs::write(&test_script_path, test_script).expect("Failed to write test script");
// Run Python script
let output = Command::new("python3")
.arg(&test_script_path)
.output()
.expect("Failed to run Python script");
// Cleanup
fs::remove_dir_all(&temp_dir).ok();
// Check results
if !output.status.success() {
panic!(
"Python dynamic array test failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("✓ All Python dynamic array tests passed"));
}