Skip to content

Commit

Permalink
Restructure test macro to be rustfmt-friendly
Browse files Browse the repository at this point in the history
The Mojo Rust library uses a macro to declare its tests to add
initialization code at the beginning. However, the macro did not work
with rustfmt: the code inside was not formatted.

This replaces it with a macro that rustfmt can process.

Bug: 1274864
Change-Id: Ia83cabc755d05ff35bb69566e749267b81310b26
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4295199
Reviewed-by: danakj <danakj@chromium.org>
Commit-Queue: Collin Baker <collinbaker@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1110598}
  • Loading branch information
chbaker0 authored and Chromium LUCI CQ committed Feb 27, 2023
1 parent 8426500 commit be96fb4
Show file tree
Hide file tree
Showing 7 changed files with 716 additions and 662 deletions.
72 changes: 35 additions & 37 deletions mojo/public/rust/tests/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,43 +39,41 @@ use crate::util::mojom_validation::*;
/// output, and decoding that once again.
macro_rules! encoding_tests {
($($name:ident { MessageHeader => $header_cls:expr, $req_type:ident => $cls:expr } )*) => {
tests! {
$(
fn $name() {
let data = include_str!(concat!("../../interfaces/bindings/tests/data/validation/",
stringify!($name),
".data"));
match util::parse_validation_test(data) {
Ok((mut data, num_handles)) => {
let mut mock_handles = Vec::with_capacity(num_handles);
for _ in 0..num_handles {
mock_handles.push(unsafe { system::acquire(0) });
}
println!("{}: Decoding header", stringify!($name));
let header = MessageHeader::deserialize(&mut data[..], Vec::new()).expect("Should not error");
let ctxt: Context = Default::default();
let header_size = header.serialized_size(&ctxt);
let header_cls = $header_cls;
println!("{}: Verifying decoded header", stringify!($name));
header_cls(header);
let payload_buffer = &mut data[header_size..];
let cls = $cls;
println!("{}: Decoding payload", stringify!($name));
let decoded_payload = $req_type::deserialize(payload_buffer, mock_handles).expect("Should not error");
println!("{}: Verifying decoded payload", stringify!($name));
cls(&decoded_payload);
println!("{}: Re-encoding payload", stringify!($name));
let (mut encoded_payload, handles) = decoded_payload.auto_serialize();
println!("{}: Decoding payload again", stringify!($name));
let redecoded_payload = $req_type::deserialize(&mut encoded_payload[..], handles).expect("Should not error");
println!("{}: Verifying decoded payload again", stringify!($name));
cls(&redecoded_payload);
},
Err(msg) => panic!("Error: {}", msg),
}
}
)*
}
$(
mojo_test!($name, {
let data = include_str!(concat!("../../interfaces/bindings/tests/data/validation/",
stringify!($name),
".data"));
match util::parse_validation_test(data) {
Ok((mut data, num_handles)) => {
let mut mock_handles = Vec::with_capacity(num_handles);
for _ in 0..num_handles {
mock_handles.push(unsafe { system::acquire(0) });
}
println!("{}: Decoding header", stringify!($name));
let header = MessageHeader::deserialize(&mut data[..], Vec::new()).expect("Should not error");
let ctxt: Context = Default::default();
let header_size = header.serialized_size(&ctxt);
let header_cls = $header_cls;
println!("{}: Verifying decoded header", stringify!($name));
header_cls(header);
let payload_buffer = &mut data[header_size..];
let cls = $cls;
println!("{}: Decoding payload", stringify!($name));
let decoded_payload = $req_type::deserialize(payload_buffer, mock_handles).expect("Should not error");
println!("{}: Verifying decoded payload", stringify!($name));
cls(&decoded_payload);
println!("{}: Re-encoding payload", stringify!($name));
let (mut encoded_payload, handles) = decoded_payload.auto_serialize();
println!("{}: Decoding payload again", stringify!($name));
let redecoded_payload = $req_type::deserialize(&mut encoded_payload[..], handles).expect("Should not error");
println!("{}: Verifying decoded payload again", stringify!($name));
cls(&redecoded_payload);
},
Err(msg) => panic!("Error: {}", msg),
}
});
)*
}
}

Expand Down
77 changes: 38 additions & 39 deletions mojo/public/rust/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,47 +16,46 @@ use std::thread;

use crate::util::mojom_validation::*;

tests! {
// Tests basic client and server interaction over a thread
fn send_and_recv() {
let (endpt0, endpt1) = message_pipe::create().unwrap();
// Client and server handles
let client = IntegrationTestInterfaceClient::new(endpt0);
let server = IntegrationTestInterfaceServer::with_version(endpt1, 0);
// Tests basic client and server interaction over a thread
mojo_test!(send_and_recv, {
let (endpt0, endpt1) = message_pipe::create().unwrap();
// Client and server handles
let client = IntegrationTestInterfaceClient::new(endpt0);
let server = IntegrationTestInterfaceServer::with_version(endpt1, 0);

// Client thread
let handle = thread::spawn(move || {
// Send request
client.send_request(5, IntegrationTestInterfaceMethod0Request {
param0: BasicStruct {
a: -1,
},
}).unwrap();
// Wait for response
client.pipe().wait(HandleSignals::READABLE);
// Decode response
let (req_id, options) = client.recv_response().unwrap();
assert_eq!(req_id, 5);
match options {
IntegrationTestInterfaceResponseOption::IntegrationTestInterfaceMethod0(msg) => {
assert_eq!(msg.param0, vec![1, 2, 3]);
},
}
});
// Wait for request
server.pipe().wait(HandleSignals::READABLE);
// Decode request
let (req_id, options) = server.recv_response().unwrap();
// Client thread
let handle = thread::spawn(move || {
// Send request
client
.send_request(
5,
IntegrationTestInterfaceMethod0Request { param0: BasicStruct { a: -1 } },
)
.unwrap();
// Wait for response
client.pipe().wait(HandleSignals::READABLE);
// Decode response
let (req_id, options) = client.recv_response().unwrap();
assert_eq!(req_id, 5);
match options {
IntegrationTestInterfaceRequestOption::IntegrationTestInterfaceMethod0(msg) => {
assert_eq!(msg.param0.a, -1);
},
IntegrationTestInterfaceResponseOption::IntegrationTestInterfaceMethod0(msg) => {
assert_eq!(msg.param0, vec![1, 2, 3]);
}
}
});
// Wait for request
server.pipe().wait(HandleSignals::READABLE);
// Decode request
let (req_id, options) = server.recv_response().unwrap();
assert_eq!(req_id, 5);
match options {
IntegrationTestInterfaceRequestOption::IntegrationTestInterfaceMethod0(msg) => {
assert_eq!(msg.param0.a, -1);
}
// Send response
server.send_request(5, IntegrationTestInterfaceMethod0Response {
param0: vec![1, 2, 3],
}).unwrap();
let _ = handle.join();
}
}
// Send response
server
.send_request(5, IntegrationTestInterfaceMethod0Response { param0: vec![1, 2, 3] })
.unwrap();
let _ = handle.join();
});
53 changes: 25 additions & 28 deletions mojo/public/rust/tests/regression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,40 +57,37 @@ impl<T: MojomEncodable> MojomEncodable for StructA<T> {

impl<T: MojomEncodable> MojomStruct for StructA<T> {}

tests! {
// Fixed size arrays have complex and unsafe semantics to ensure
// there are no memory leaks. We test this behavior here to make
// sure memory isn't becoming corrupted.
fn regression_fixed_size_array_error_propagates_safely() {
let handle1 = unsafe { system::acquire(0) };
let handle2 = unsafe { system::acquire(0) };
let handle3 = unsafe { system::acquire(0) };
let val = StructA {
param0: [handle1, handle2, handle3],
};
let (mut buffer, mut handles) = val.auto_serialize();
handles.truncate(1);
let new_val = <StructA<UntypedHandle>>::deserialize(&mut buffer[..], handles);
match new_val {
Ok(_) => panic!("Value should not be okay!"),
Err(err) => assert_eq!(err, ValidationError::IllegalHandle),
}
// Fixed size arrays have complex and unsafe semantics to ensure
// there are no memory leaks. We test this behavior here to make
// sure memory isn't becoming corrupted.
mojo_test!(regression_fixed_size_array_error_propagates_safely, {
let handle1 = unsafe { system::acquire(0) };
let handle2 = unsafe { system::acquire(0) };
let handle3 = unsafe { system::acquire(0) };
let val = StructA { param0: [handle1, handle2, handle3] };
let (mut buffer, mut handles) = val.auto_serialize();
handles.truncate(1);
let new_val = <StructA<UntypedHandle>>::deserialize(&mut buffer[..], handles);
match new_val {
Ok(_) => panic!("Value should not be okay!"),
Err(err) => assert_eq!(err, ValidationError::IllegalHandle),
}
});

// Same as the above test, but verifies that drop() is called.
// For the only handle that should drop, we make the handle some
// random number which is potentially a valid handle. When on
// drop() we try to close it, we should panic.
#[should_panic]
// Same as the above test, but verifies that drop() is called.
// For the only handle that should drop, we make the handle some
// random number which is potentially a valid handle. When on
// drop() we try to close it, we should panic.
mojo_test!(
regression_fixed_size_array_verify_drop,
// Ignore this test, it panics while panicking
#[ignore]
fn regression_fixed_size_array_verify_drop() {
#[should_panic]
{
let handle1 = unsafe { system::acquire(42) };
let handle2 = unsafe { system::acquire(0) };
let handle3 = unsafe { system::acquire(0) };
let val = StructA {
param0: [handle1, handle2, handle3],
};
let val = StructA { param0: [handle1, handle2, handle3] };
let (mut buffer, mut handles) = val.auto_serialize();
handles.truncate(1);
let new_val = <StructA<UntypedHandle>>::deserialize(&mut buffer[..], handles);
Expand All @@ -99,4 +96,4 @@ tests! {
Err(err) => assert_eq!(err, ValidationError::IllegalHandle),
}
}
}
);
Loading

0 comments on commit be96fb4

Please sign in to comment.