Skip to content

Commit

Permalink
Use a struct for the core function's response
Browse files Browse the repository at this point in the history
  • Loading branch information
maahl committed Nov 5, 2023
1 parent a2c68c9 commit f7150a8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ edition = "2021"

[dependencies]
lambda_runtime = "0.8.1"
serde = "1.0.164"
serde_json = "1.0.97"
tokio = "1.28.2"
29 changes: 23 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
use lambda_runtime::{service_fn, Error, LambdaEvent};
use serde_json::{json, Value};

#[derive(Debug, PartialEq, serde::Serialize)]
struct HelloResponse {
message: String,
}

// Send a greeting
fn say_hello(name: Option<&str>) -> String {
fn say_hello(name: Option<&str>) -> HelloResponse {
// if a name was not provided, address the greeting to "stranger"
let name = name.unwrap_or("stranger");

format!("Hello, {name}!")
HelloResponse {
message: format!("Hello, {name}!"),
}
}

// Wrapper for our core function
Expand Down Expand Up @@ -35,20 +42,30 @@ mod tests {
fn test_name_provided() {
let name = "world";
let result = say_hello(Some(name));
assert_eq!(format!("Hello, {name}!"), result);
assert_eq!(
HelloResponse {
message: format!("Hello, {name}!")
},
result
);
}

#[test]
fn test_no_name_provided() {
let result = say_hello(None);
assert_eq!("Hello, stranger!".to_owned(), result);
assert_eq!(
HelloResponse {
message: "Hello, stranger!".into()
},
result
);
}

#[tokio::test]
async fn test_wrapper_name_provided() {
let name = "world";
let event = LambdaEvent::new(json!({ "name": name }), Context::default());
let expected_result = json!(format!("Hello, {name}!"));
let expected_result = json!({ "message": format!("Hello, {name}!") });

let result = run_lambda(event).await;

Expand All @@ -63,7 +80,7 @@ mod tests {
json!({ "meaningless_key": "meaningless_value" }),
Context::default(),
);
let expected_result = json!(format!("Hello, stranger!"));
let expected_result = json!({ "message": format!("Hello, stranger!") });

let result = run_lambda(event).await;

Expand Down

0 comments on commit f7150a8

Please sign in to comment.