Skip to content

Commit 44c8680

Browse files
committed
Improve binary payload test coverage
Signed-off-by: Didier Wenzek <[email protected]>
1 parent e513fcc commit 44c8680

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

crates/extensions/tedge_flows/src/js_script.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,61 @@ export async function onMessage(message, config) {
396396
);
397397
}
398398

399+
#[tokio::test]
400+
async fn using_standard_built_in_objects() {
401+
let js = r#"
402+
export async function onMessage(message, config) {
403+
const te = new globalThis.TextEncoder();
404+
const td = new globalThis.TextDecoder();
405+
406+
const encodedText = message.raw_payload;
407+
const decodedText = td.decode(encodedText);
408+
const finalPayload = te.encode(decodedText + decodedText);
409+
return [{topic:"decoded", payload: finalPayload}];
410+
}
411+
"#;
412+
let (runtime, script) = runtime_with(js).await;
413+
414+
let input = Message::new_binary("encoded", [240, 159, 146, 150]);
415+
let output = Message::new_binary("decoded", [240, 159, 146, 150, 240, 159, 146, 150]);
416+
assert_eq!(
417+
script
418+
.on_message(&runtime, &DateTime::now(), &input)
419+
.await
420+
.unwrap(),
421+
vec![output]
422+
);
423+
}
424+
425+
#[tokio::test]
426+
async fn reading_raw_integers() {
427+
let js = r#"
428+
export async function onMessage(message, config) {
429+
const measurements = new Uint32Array(message.raw_payload.buffer);
430+
431+
const tedge_json = {
432+
time: measurements[0],
433+
value: measurements[1]
434+
}
435+
436+
return [{topic:"decoded", payload: JSON.stringify(tedge_json)}];
437+
}
438+
"#;
439+
let (runtime, script) = runtime_with(js).await;
440+
441+
let time = 1758212648u32.to_le_bytes();
442+
let value = 12345u32.to_le_bytes();
443+
let input = Message::new_binary("encoded", [time, value].as_flattened());
444+
let output = Message::new("decoded", r#"{"time":1758212648,"value":12345}"#);
445+
assert_eq!(
446+
script
447+
.on_message(&runtime, &DateTime::now(), &input)
448+
.await
449+
.unwrap(),
450+
vec![output]
451+
);
452+
}
453+
399454
async fn runtime_with(js: &str) -> (JsRuntime, JsScript) {
400455
let mut runtime = JsRuntime::try_new().await.unwrap();
401456
let mut script = JsScript::new("toml".into(), 1, "js".into());

0 commit comments

Comments
 (0)