Unit Testing
local graph
Chapter 14 — Unit Testing
Section titled “Chapter 14 — Unit Testing”Unit Testing
Section titled “Unit Testing”We have built our to-do application, and it is working. However, we only know it is working because our operations were simple. We know that in the real world, the logic behind our applications will be more complex with more moving parts. This is where unit testing comes in. Unit testing is essential when your application evolves. In this chapter, we will cover the following:
- The importance of unit testing
- Writing our first unit test
- Testing our core
- Unit testing our networking layer
- Unit testing our data access layer
By the end of this chapter, you will understand the importance of unit testing. You will also be able to write unit tests and mock IO handles such as calls to a database, to test how our code handles different states. You will also be able to test HTTP requests for a service and build a testing harness that configures a database and runs tests in log files.
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle.
The importance of unit testing
Section titled “The importance of unit testing”It baffles me that there is pushback against testing at all. Sadly, the internet is full of tutorials rushing to get a poorly structured app with loads of tech debt deployed. The issue with these tutorials is that when you are copying the code and chugging along the predefined path, everything seems smooth and quick. However, this smooth, quick process is a facade. If you create software that aims to solve a problem in the real world, you will have a general idea of where to start, but there will always be unknowns and features that you did not initially think about. This is why experienced software engineers generally say, “Estimate how long the task is going to take and then double it”. As the system grows, if unit testing is not in place, development will become error-prone and will take longer and longer to add features. Refactoring an untested system can become near enough impossible if the system is too complex. You also get brittle software, meaning that if you change a piece of code in one place, it can break code elsewhere. To demonstrate this, we can look at Figure 14.1 to see the number of steps needed to test the core function of a delete:
Figure 14.1 - The steps needed to test a core delete item
Here, we can see that there are 11 pieces of code in the way of testing to see if our core function for deleting an item works. If there is an error in any of those 11 pieces of code, then you will not be able to test our delete item code. You will have to perform 3 steps before you can test the delete function. So, we attempt to write the delete function, perform the three steps, and then see if our delete func-tion acts as expected. Again, our example is very simple, but with more complex processes, it’s very unlikely that you will get it right on the first try. So, you tear down the database, spin up another one, and then perform the steps again. Then, you wonder what will happen if you try and delete an item that is not there. So, you do the first two steps, then the fourth step, and you get an unhelpful error when you really want a not found error. So, you update it, do the first, second, and fourth steps. Okay, it now works, but you also need to wipe the database again and do all four steps in sequence to make sure that your most recent change did not affect the deletion of an item if it does exist. Again, this may seem excessive for a simple delete function; however, I’m only using this as a simplified example. For more complex real-world examples, changing code to account for one edge case might break code for another edge case. If you don’t like doing all these manual steps and decide to write a script that performs all four steps in a process, then you are writing a testing script. You might as well lean into the entire ecosystem of testing tools and do it properly.
[figure outside: Figure 14.1]
For a unit test, we isolate the piece of code and pass a range of inputs and assert the outcomes, as seen in Figure 14.2:
Figure 14.2 - The steps needed for a unit test
With this unit test, we do two operations to test both of our edge cases, as opposed to seven steps and two database wipes. When you run these steps again and again when you are developing your code, of course, the proper unit-tested code will enable you to iterate your code at a much faster rate. At the time of writing this book, I am working in GPU streaming in Rust at Kings College London for a surgical robotics project. I was at the stage of reshaping the data coming out of the GPU, which was streamed into the GPU. My PhD student was struggling, so I spent an evening where we captured one frame from the stream and stored it as a binary file. We then passed that frame through the GPU so that a convolutional neural network could detect objects in the frame, and we saved the computation from the GPU. I then built a unit test for the function. The PhD student then did not have to worry about GPU drivers. He could code on any computer he wanted. All he had to do was run the test that accepted the input and spat out his output. Within a day, he solved the problem. When I next spoke to him, he admitted that he did not really take my talks on unit testing seriously until he experienced it first-hand. Now he is an avid unit tester.
There are some potential pitfalls to unit testing. For instance, another part of the code could change, but you did not change your mock. Therefore, your test could technically pass but break in a larger system. This is less likely to happen with Rust due to the strong typing. However, it is something to keep an eye out for. We will also completely negate this issue with end-to-end testing in the next chapter. Others state that unit testing is too rigid. You change one thing, then you must change a load of tests. This, however, is more of a reflection of their code. Well-structured code with clean interfaces is easy to test and move around. Unit testing is also a test of the code structure. If code is hard to test, will it be easy to refactor that code or change a data source? Probably not. Unit tests not only save time running the code with quick feedback loops, but they also give us a sense of whether we are going down a bad path with our code structure.
[figure outside: Figure 14.2]
Unit Testing
Now that we know that testing is one of the most important skills we can learn as a developer, let us write our first unit test.
Writing our first unit test
Section titled “Writing our first unit test”To get to grips with the basics of testing, we are going to test the following simple function in a blank Rust workspace:
fn add_two_numbers<T, U>(a: T, b: U)-> Result<T, <U as TryInto<T>>::Error>where T: std::ops::Add<Output = T>, U: TryInto<T>,{ let b_converted: T = b.try_into()?; Ok(a + b_converted)}Here, we make a generic function that adds two numbers together. We can also try and cast the second number into the same type as the first number, so we can pass in a different number type, and we will try and convert it.
To test our function, we must define the following module inside the same file:
#[cfg(test)]mod tests { use super::*; ...}Here, we are importing everything in the file into the tests module. The tests module will only be compiled if we are running tests and will not be included in the main app for deployment. Inside our tests module, we can define our first test with the following code:
#[test]fn test_add_two_numbers_i32() { let result = add_two_numbers(5i32, 3i32); assert_eq!(result, 0k(8));}Here, we are adding two i32 integers and checking to see whether the result is an eight. We can run our tests with the following command:
cargo testThis command will give us the following printout:
running 1 test test tests::test_add_two_numbers_i32 … ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
For our next three tests, we can add different integer types: a minus integer, a float, and an integer to see how our function works with the following code:
#[test]fn test_add_two_numbers_i32_u64() { let result = add_two_numbers(5i32, 3u64); assert_eq!(result, Ok(8));}#[test]fn test_add_two_numbers_minus() { let result = add_two_numbers(5i32, -3i32); assert_eq!(result, Ok(2));}#[test]fn test_add_two_numbers_float_and_int() { let result = add_two_numbers(5.0, 3); assert_eq!(result, Ok(8.0));}With the test command giving us the following printout:
running 4 tests test tests::test_add_two_numbers_float_and_int … ok test tests::test_add_two_numbers_i32 … ok test tests::test_add_two_numbers_minus … ok test tests::test_add_two_numbers_i32_u64 … ok test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Finally, we want to ensure that if our second number exceeds the maximum value of the first number type, we get an error with the following test:
#[test]fn test_add_two_numbers_outsize() {let result = add_two_numbers(5u8, 5000i32);assert_eq!(result.is_err(), true);}If we run the test command again, all five of our tests will pass. Here, we have mapped exactly how our function would work before we try and integrate our adding function into the rest of our system if we need to.
You may have heard about setups and teardowns in unit tests. This is where a setup function fires before the test is run, and the teardown function is fired after the test. Seeing as we are not interacting with the state of anything, we do not need to perform setup and teardown functions. We will cover the setup and teardown functions in the following chapter for end-to-end testing, as our end-to-end tests must interact with databases, and these databases need to be wiped and set up between tests to ensure that the tests are isolated and deterministic.
Now that we know how to build and run basic tests, we are going to move to the core module of our servers to mock our data access layer to see how our core module handles different data access responses.
Testing our core
Section titled “Testing our core”We are now at the stage where we want to create a unit test for the delete function in our core. However, before we write any testing code, we must acknowledge that our core code just has the bare minimum to perform our application logic. The functions in the core are async, but we do not have any async runtime dependencies in the core workspace. However, we do need a runtime to test our async functions. To remedy this, we add a tokio dependency in our dev-dependencies section so our development processes like running tests have tokio, but our core library will not have the tokio dependency when being deployed. This is achieved with the following code:
...[dependencies]To-do-dal = { path = "../dal" }serde = { version = "1.0.197", features = ["derive"] }glue = { path = "../../../glue"}auth-kernel = { path = "../../auth/kernel", features = ["core-postgres"]}
[dev-dependencies]tokio = { version = "1.39.1", features = ["full"] }With tokio, we can use the #[tokio::test] macro, which essentially enables us to run async test functions. With our tokio dependency sorted, we can now move on to building our tests for our core delete function.
Here, we must pass in the correct parameters to the data access layer. If the item is not in the database, then we will get an error. For our testing harness of the delete core function, we have the following code:
Chapter 14
Section titled “Chapter 14”[cfg(test)]
Section titled “[cfg(test)]”mod tests { use super::*; use to_do_dal::to_do_items::schema::ToDoItem; use to_do_dal::to_do_items::transactions::delete::DeleteOneResponse; use std::future::Future;
#[tokio::test] async fn test_delete_ok() { ... } #[tokio::test] async fn test_delete_err() { ... }}Because we structured our code well with traits handling the database operation, we can create a mock struct and implement the database handle trait to mock different responses from the database. Inside our test_delete_one_ok function, we can create a mock struct and implement the DeleteOne trait with the following code:
struct ReturnOneMock;
impl DeleteOne for ReturnOneMock { fn delete_one(id: String, user_id: i32) -> impl Future<Output = DeleteOneResponse> + Send { ... }}Inside the delete_one function in our trait implementation, we must assert that a correct title and user ID were passed to the data access layer. We can also see that our test is trying to create a successful delete; therefore, we must return an OK result because we are testing the success of our delete core function. Our checks and return inside the delete_one function in our trait implementation are defined ahead:
if id != "coding" { panic!("Invalid title");}if user_id != 1 {panic!("Invalid user_id");}async { Ok(ToDoItem { id: 1, title: "title".to_string(), status: "PENDING".to_string(), })}Finally, in our test_delete_one_ok function, we call the delete core function with our mock handle, and assert that the result is okay with the following code:
let result = delete::<ReturnOneMock>("coding", 1).await;assert!(result.is_ok());For our error test, we have an outline like the previous with the following code:
#[tokio::test]async fn test_delete_err() { struct ReturnErrorMock; impl DeleteOne for ReturnErrorMock { fn delete_one(id: String, user_id: i32) -> impl Future<Output = DeleteOneResponse> + Send { ... } } let result = delete::<ReturnErrorMock>("coding", 1).await; match result { Ok(_) => panic!("Expected error"), Err(e) => { assert_eq!( e.status, glue::errors::NanoServiceErrorStatus::NotFound ); assert_eq!(e.message, "Some Error"); } }}Inside the implementation of the DeleteOne trait for the delete_one function, we have the following code:
if id != "coding" { panic!("Invalid title");}if user_id != 1 { panic!("Invalid user_id");}async { Err(NanoServiceError::new( "Some Error".to_string(), glue::errors::NanoServiceErrorStatus::NotFound ))}And now our unit test is complete. If we navigate to the core of the to-do nanoservice and run our cargo test command, we should get the following printout:
orunning 2 teststest api::basic_actions::delete::tests::test_delete_err ... oktest api::basic_actions::delete::tests::test_delete_ok ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured;0 filtered out; finished in 0.00s
Doc-tests core
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;0 filtered out; finished in 0.00sHere, our tests are working. These tests are consistent, deterministic, and fully automated. We can continue to build out our tests and run them to get feedback on the code we are writing within seconds.
It must be noted that if we merely run a cargo test command in the root of our project, we will get an error due to the code for the Redis module. We must remember that we are going to be running a range of tests as we essentially have a microservices system with a Redis cache, database, logging database, and multiple servers talking to each other. When we run a cargo test command, it runs the tests over multiple threads. We are going to need to run our tests in a single threaded way one after the other. We can communicate to other developers our testing strategy and automate the running of all our tests with the following bash script in the scripts directory at the root of our system: #!/usr/bin/env bash
scripts/run_tests.sh
Section titled “scripts/run_tests.sh”# navigate to directorySCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"cd $SCRIPTPATHcd ..
cargo test -p to-do-coreNow that our basic unit testing for our core delete function is done, another developer can look at the tests and know how to call the function and what to expect when using the function. The threshold is also lowered for them adding extra functionality to the delete function; they can hit the ground running, developing directly against the tests as opposed to having to spin up multiple databases and servers.
But what about our networking layer? Yes, we can unit test HTTP requests and see how our server handles them.
Unit testing our networking layer
Section titled “Unit testing our networking layer”When it comes to unit testing, most good web frameworks will offer unit testing tools because the maintainers are skilled engineers, and they know the importance of unit testing. Actix is no exception. Unit testing our networking layer is a bit more complicated compared to our core because there are more moving parts. However, unit testing our network layer is a bit more representative of what unit testing is like outside of a toy example because we must handle multiple moving parts, and we must test how they work.
Before we write any testing code, however, we must reconfigure our dependencies with the following:
nanoservices/to_do/networking/actix_server/
Section titled “nanoservices/to_do/networking/actix_server/”Cargo.toml
Section titled “Cargo.toml”… [dependencies] … to-do-core = { path = ”../../core” } …
[dev-dependencies]serde_json = "1.0.120"actix-http = "3.8.0"...We can see that we add the serde-json and actix-http crates into dev-dependencies. We will use these crates to create HTTP requests for our test. We will also need to deserialize the JSON response body in the test. With this in place, we can build out our unit test by carrying out the following steps:
- Defining our test module
- Mocking our database handle
- Mocking our cache handle
- Defining our mock service
- Writing tests
With this comprehensive approach, we will be able to see how our delete endpoint acts in a whole range of ways. For Rocket, Axum, and hyper, we do not need any extra dependencies apart from serde-json because we can construct requests from their own crates. For instance, constructing a request for Axum can be done using the Axum crate. The same goes for Hyper and Rocket.
We can start our HTTP unit test by defining our test module.
Defining our test module
Section titled “Defining our test module”For our test module definition, we have the following outline:
// src/api/basic_actions/delete.rs
#[cfg(test)]mod tests { use super::*; use actix_web::{ dev::ServiceResponse, self, body::MessageBody, http::header::ContentType, test::{ call_service, init_service, TestRequest }, web, App }; use actix_http::Request; use glue::token::HeaderToken; use dal::to_do_items::transactions::delete::DeleteOneResponse; use dal::to_do_items::schema::{ToDoItem, AllToDoItems}; use std::future::Future; use auth_kernel::user_session::schema::UserSession;}With all these imports, we will be able to mock the database and cache. We will also be able to construct test HTTP requests and services. Before we write any tests, we must write some helper functions that are available to all test functions. First, we build a function that generates an item with the following code:
// src/api/basic_actions/delete.rsfn generate_to_do_item() -> ToDoItem { ToDoItem { id: 1, title: "test".to_string(), status: "PENDING".to_string(), }}We might as well produce the same item throughout the tests just to keep it simple and reduce the amount of code we must write to get our tests running. We can also build a function that generates the return items with the following:
// src/api/basic_actions/delete.rsfn generate_get_all_return() -> Vec<ToDoItem> { vec![ generate_to_do_item() ]}We can now move on to mocking our database handle.
Mocking our database handle
Section titled “Mocking our database handle”For our mock database handle, we implement the DeleteOne trait by returning an internal async function we can see in the following code:
// src/api/basic_actions/delete.rsstruct MockDbHandle;
impl DeleteOne for MockDbHandle { fn delete_one(title: String, _user_id: i32) -> impl Future<Output = DeleteOneResponse> + Send { async fn run(title: String) -> DeleteOneResponse { ... } run(title) }}Inside our internal run function, we want to see how our delete endpoint handles a successful and a failed delete operation. We do not want to write loads of different mocks for our tests. We can make it so that an error is returned if coding is not passed into the function with the following code:
// src/api/basic_actions/delete.rsif title == "coding" { return Ok(generate_to_do_item())}return Err(
NanoServiceError::new( "Item not found".to_string(), NanoServiceErrorStatus::NotFound ))We implement the GetAll trait for our mock database handle with the following code:
// src/api/basic_actions/delete.rsimpl GetAll for MockDbHandle { fn get_all(user_id: i32) -> impl Future<Output = Result< Vec<ToDoItem> >, NanoServiceError>> + Send { async fn run(user_id: i32) -> Result<Vec<ToDoItem>, NanoServiceError> { ... } run(user_id) }}Again, we can create an error if we pass in a certain user ID, so we can test multiple outcomes with the same mock for different tests. The code inside our internal run function takes the following form:
// src/api/basic_actions/delete.rsif user_id == 2 { return Err( NanoServiceError::new( "error getting items got get all".to_string(), NanoServiceErrorStatus::Unknown )}434Unit Testing )}Ok(generate_get_all_return())For other servers such as Rocket, Hyper, and Actix, we have the same implementations as the mocks that we have just done here, as the trait implementations are independent of the web framework used. For Rocket, we have been using the macro, which makes mocking harder. We can get around this by having an inner function that accepts traits. Our inner function for the Rocket delete function would take the following form:
pub async fn delete_by_name_generic<T, X>( token: HeaderToken, name: &str) -> Result<Json<AllToDOItems>, NanoServiceError>where T: DeleteOne + GetAll, X: GetUserSession{ let user = X::get_user_session(token.unique_id).await?; let _ = delete_core::<T>(name, user.user_id).await?; Ok(Json(get_all_core::<T>(user.user_id).await?))}Then our API wrapper is defined with the following code:
#[delete("/delete/<name>")]pub async fn delete_by_name( token: HeaderToken, name: &str) -> Result<Json<AllToDOItems>, NanoServiceError> { delete_by_name_generic::< SqlxPostGresDescriptor, RedisSessionDescriptor >(token, name).await}With these trait implementations, our database handle is ready for our tests, so we can now move on to mocking our user session cache.
Mocking our user cache handle
Section titled “Mocking our user cache handle”For our mock cache handle, we implement the GetUserSession trait with the following code:
// src/api/basic_actions/delete.rsstruct MockUserSessionHandle;impl GetUserSession for MockUserSessionHandle { fn get_user_session(unique_id: String) -> Result<UserSession, NanoServiceError> { impl Future<Output = Result<UserSession, NanoServiceError>> { async fn run(unique_id: String) -> Result<UserSession, NanoServiceError> { .. } run(unique_id) } }}Inside our run internal function, we can return two different user IDs and an error with the following code:
// src/api/basic_actions/delete.rsif unique_id == "break" { return Err( NanoServiceError::new( "User not found".to_string(), NanoServiceErrorStatus::NotFound ) )}if unique_id == "2" { return Ok(UserSession { user_id: 2 })}Ok(UserSession { user_id: 1})With this, all our mock handles have been defined and are ready to be used in all our tests. We can now move on to defining our mock service.
Defining our mock service
Section titled “Defining our mock service”For our service, we could spin up a server. However, we would have to find a local port that does not clash with another process and wait for the server to run in either a different thread or async task. Instead, we can build a testing service with the following code:
// src/api/basic_actions/delete.rsasync fn run_request(req: Request) -> ServiceResponse { let service = delete_by_name::<MockDbHandle, MockUserSessionHandle> >; let app = init_service(App::new().route( "/delete/{name}", web::delete().to(service) )).await; call_service(&app, req).await}Here, we can see that we get the delete_by_name function with our mock handles, associate the function with an endpoint and delete method using the init_service function, and then use the call_service function provided by actix to call the service with the request that we pass into the function. Our run_request function will be called in all our tests.
With this service defined, we can now move on to writing our tests.
Writing tests
Section titled “Writing tests”For our tests, we create a test request, pass this request to the run_request function, process the response, and assert checks on the values of that response. For our first test, where everything is okay, we have the following signature:
// src/api/basic_actions/delete.rs#[tokio::test]async fn test_delete_ok() { std::env::set_var("JWT_SECRET", "secret"); ...}Here, we set the environment variable so we can encode the header token. We do not know when each test will run or the order, so to be safe, we define the environment variable at the start of every test that requires the header token. Inside our test, we create a request and make a call to the service with the following code:
// src/api/basic_actions/delete.rslet req = TestRequest::delete() .insert_header(ContentType::json()) .insert_header( "token", HeaderToken{ unique_id: "test_id".to_string() }.encode().unwrap() ) .uri("/delete/coding") .to_request();let resp = run_request(req).await;We then process the HTTP response with the following code:
// src/api/basic_actions/delete.rslet status = resp.status().as_u16();let raw_body = resp.into_body().try_into_bytes().unwrap();let body_str = std::str::from_utf8(&raw_body).unwrap();let body: AllToDoItems = serde_json::from_str( body_str).unwrap();Finally, we assert that the response was okay and that the body contains the items that we are expecting from the mock with the following code:
// src/api/basic_actions/delete.rsassert_eq!(status, 200);assert_eq!( body, AllToDoItems::from_vec(generate_get_all_return())).unwrap();With this, our test will work just by running the test. To test an invalid token, we must pass in an invalid token that would not decode properly. At this point, it would be a good chance to try and code the test yourself. If you attempted the invalid token test, hopefully, it looks like the following code:
// src/api/basic_actions/delete.rs#[tokio::test]async fn test_delete_invalid_token() { // configure the service std::env::set_var("JWT_SECRET", "secret");
// make the request and get the response let req = TestRequest::delete() .insert_header(ContentType::json()) .insert_header(("token", "test")) .uri("/delete/coding") .to_request(); let resp = run_request(req).await;
// extract the status and body let status = resp.status().as_u16(); let raw_body = resp.into_body().try_into_bytes().unwrap(); let body_str = std::str::from_utf8(&raw_body).unwrap();
// assert the status and body assert_eq!(status, 401); assert_eq!(body_str, "\"token not a valid string\"");}We can then move on to creating a test for when the user is not found. Here, we must pass in a string that will get the user session cache to return a not found. If you attempted to write the test yourself, hopefully it looks like the following code:
// src/api/basic_actions/delete.rs#[tokio::test]async fn test_delete_user_not_found() { // configure the service std::env::set_var("JWT_SECRET", "secret");
// make the request and get the response let req = TestRequest::delete() .insert_header(ContentType::json()).insert_header( "token", HeaderToken{ unique_id: "break".to_string() }.encode().unwrap()).uri("/delete/coding").to_request();let resp = run_request(req).await;// extract the status and bodylet status = resp.status().as_u16();let raw_body = resp.into_body().try_into_bytes().unwrap();let body_str = std::str::from_utf8(&raw_body).unwrap();
// assert the status and bodyassert_eq!(status, 404);assert_eq!(body_str, "\"User not found\"");}For our item not found error, we must pass in the name to the delete handle mock to return an error. If you attempted to write this test yourself, hopefully it looks like the following code:
// src/api/basic_actions/delete.rs#[tokio::test]async fn test_delete_item_not_found() { // configure the service std::env::set_var("JWT_SECRET", "secret");
// make the request and get the response let req = TestRequest::delete() .insert_header(ContentType::json()) .insert_header( "token", HeaderToken{ unique_id: "test_id".to_string() }.encode().unwrap() ) .uri("/delete/break") .to_request(); let resp = run_request(req).await;For our item not found error, we must pass in the name to the delete handle mock to return an error. If you attempted to write this test yourself, hopefully it looks like the following code:
// extract the status and bodylet status = resp.status().as_u16();let raw_body = resp.into_body().try_into_bytes().unwrap();let body_str = std::str::from_utf8(&raw_body).unwrap();// assert the status and bodyassert_eq!(status, 404);assert_eq!(body_str, "\"Item not found\"");Finally, we need to test the last remaining failure case: when get_all fails while building the response. Here, we must have a user ID that triggers this error. If you attempted to write the test, hopefully it looks like the following code:
// src/api/basic_actions/delete.rs#[tokio::test]async fn test_delete_get_all_error() { // configure the service std::env::set_var("JWT_SECRET", "secret");
// make the request and get the response let req = TestRequest::delete() .insert_header(ContentType::json()) .insert_header( "token", HeaderToken{ unique_id: "2".to_string() }.encode().unwrap() ) .uri("/delete/coding") .to_request(); let resp = run_request(req).await;
// extract the status and body let status = resp.status().as_u16(); let raw_body = resp.into_body().try_into_bytes().unwrap(); let body_str = std::str::from_utf8(&raw_body).unwrap();
// assert the status and body assert_eq!(status, 500); assert_eq!(body_str, "\"error getting items got all\"");We are now done with our unit tests for an HTTP endpoint! Now we must update our testing script, giving us the following total contents for the script:
#!/usr/bin/env bash## scripts/run_tests.sh
## navigate to directorySCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"cd $SCRIPTPATH
cd ..
cargo test -p to-do-corecargo test -p to-do-actix-serverIf we run this script, we will see all our tests run and pass, and we will see that our tests pass with the following printout:
Running unittests src/lib.rs(target/debug/deps/actix_server-e72261cb22d7ffc0)
running 5 teststest api::basic_actions::delete::tests::test_delete_user_not_found ... oktest api::basic_actions::delete::tests::test_delete_invalid_token ... oktest api::basic_actions::delete::tests::test_delete_get_all_error ... oktest api::basic_actions::delete::tests::test_delete_ok ... oktest api::basic_actions::delete::tests::test_delete_item_not_found ... ok
test result: ok. 5 passed; 0 failed;0 ignored; 0 measured; 0 filtered out; finished in 0.01sWe are now finished with our network testing. We could move on to testing all the endpoints and functions, but we wouldn’t add any new concepts, just a lot of repetition.
So far, we have been mocking the outputs from calls to the database, but what if our SQL code is incorrect? In our last stretch of unit testing, we will test our data access layer.
Unit testing our data access layer
Section titled “Unit testing our data access layer”Unit tests are where the test checks a small unit of code. Testing the data access layer is no exception. However, it is going to be slightly different from our other unit tests. The data access layer is the interface we have with the database. This means that if we mock the database calls, our tests will be close to useless. Because of this, we must coordinate our data access unit tests with the running of the databases. Because there are more moving parts, we must carry out the following steps if we want to unit test our data access layer:
- Defining a teardown SQL command
- Creating a data access layer (DAL) unit test
- Refactoring our testing script
We will start with the teardown SQL command.
Defining a teardown SQL command
Section titled “Defining a teardown SQL command”Because our tests rely on the interaction of the database, the state of the database can affect the test and make the test flaky, meaning that sometimes they will pass and other times they will not. Sadly, I have seen the run it a few times and the test suite should pass attitude a bit too much in some projects. We want our test to work every time. Therefore, we must have a teardown command that completely wipes the database. Therefore, we can ensure that the database state is what we want at the start of every test. Other testing modules in other workspaces might also interact with a database. We know that, in the next chapter, we will be doing end-to-end testing, so we will certainly want to use a teardown command there too. As you have probably guessed, to enable all our workspaces to access such commands, we are going to put the teardown command in the glue module. Our teardown SQL statement takes the following form:
pub static WIPE_DB: &str = ""
DO $$
DECLARE
r RECORD;
BEGIN
-- Disable referential integrity checks SET session_replication_role = replica;
-- Loop through all table names and drop them FOR r IN ( SELECT tablename FROM pg_tables WHERE schemaname = 'public' ) LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
END LOOP;— Re-enable referential integrity checks SET session_replication_role = DEFAULT; END $$; ”;
It is a SQL statement that does not look familiar, but we can go through this. The
is commonly used:
-
DECLARE: This section is used to declare any variables that will be used within the block. In this case, the variable r, of type RECORD, is declared. A RECORD type is a flexible data type that can hold a single row of data with columns that might vary.
-
BEGIN … END: This block contains the executable part of the code where the actual operations are performed.
-
SET session_replication_role = replica;; This command temporarily disables the enforcement of foreign key constraints. By setting session_replication_role to replica, it tells PostgreSQL to behave as if it is applying changes replicated from another server, which often involves bypassing some constraint checks.
-
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = ‘public’): This loop iterates over all table names in the public schema. The pg_tables system catalog contains information about all tables in the database, and this query selects all table names where the schema is public. We do not want to mess with tables outside of public; we could mess with the postgres internals.
-
EXECUTE ‘DROP TABLE IF EXISTS’ || quote_ident(r.tablename) || ‘CASCADE’;: Inside the loop, this dynamic SQL command constructs and executes a DROP TABLE IF EXISTS statement for each table. The quote_ident function is used to safely quote the table name, preventing SQL injection and handling special characters or reserved keywords in table names. The CASCADE option ensures that any dependent objects (like foreign key constraints, views, etc.) are also dropped.
We now have a command that is going to wipe our database, no matter what tables we have. This will also wipe our migrations reference, as migrations are denoted by a migrations table in the public space, so migration tools can keep track of what migrations to apply. With all the tables dropped, running the migrations will set up all the tables we need with no rows.
Now that we have our teardown command done, we can move on to building our unit test for our data access layer.
Creating a DAL unit test
Section titled “Creating a DAL unit test”To test our delete functionality for our data access layer, we initially need the following outline:
#[cfg(feature = "sqlx-postgres")]#[cfg(test)]mod tests {use super::*;use crate::migrations::run_migrations;use glue::sql_commands::WIPE_DB;
async fn setup() { sqlx::query(WIPE_DB).execute(&*SQLX_POSTGRES_POOL) .await .unwrap(); run_migrations().await;}#[tokio::test]async fn test_sqlx_postgres_delete_one_ok() { setup().await; ...}Here, we can see that our | function, which we run at the start of every test that we want to run, wipes the database and then runs the migrations. We can also see that our test module is guarded by the sqlx feature. This is because we do not have trait implementations of the delete transaction for postgres unless we are using the sqlx feature. This also means that we must enable the sqlx feature. Inside our test_sqlx_postgres_delete_one_ok function, after the setup function is fired, we start off our test by defining the data that we are going to be inserting with the following code:
let title = "test_sqlx_postgres_delete_one".to_string();let user_id = 1;let item = ToDoItem { id: 1, title: title.clone(), status: "PENDING".to_string()};We can now use these definitions to insert and compare against. We then insert the item into the database with the following code:
let item = sqlx::query_as::<_, ToDoItem>(" INSERT INTO to_do_items (title, status) VALUES ($1, $2) RETURNING *").bind(item.title).bind(item.status.to_string()).fetch_one(&*SQLX_POSTGRES_POOL).await.unwrap();We also must remember that there is a user connection associated with the item, so we also insert the user connection with the following code:
let _ = sqlx::query(" INSERT INTO user_connections (user_id, to_do_id) VALUES ($1, $2)").bind(user_id).bind(item.id).execute(&*SQLX_POSTGRES_POOL).await.unwrap();We can now delete our item with the function that we are testing with the following code:
let result = sqlx_postgres_delete_one( title.clone(), user_id).await.unwrap();assert_eq!(result.title, title);With the assert, we ensure that we deleted the item that we intended to by checking the title.
We can now start performing direct SQL queries on the database to double-check that our database transaction went through and influenced the state. We assert that the item is no longer in the database with the following code:
let result = sqlx::query_as::<_, ToDoItem>(" SELECT * FROM to_do_items WHERE title = $1").bind(title).fetch_optional(&*SQLX_POSTGRES_POOL).await.unwrap();assert!(result.is_none());And we then assert that there are no longer any user connections with the following code:
let result = sqlx::query_as::<_, (i64,)>(" SELECT COUNT(*) FROM user_connections WHERE user_id = $1 AND to_do_id = $2").bind(user_id).bind(item.id).fetch_one(&*SQLX_POSTGRES_POOL).await.unwrap();assert_eq!(result.0, 0)With this, our test is ready to run. Our test for trying to delete an item that does not exist is more straightforward, as we do not have to put anything into the database. Instead, we just try and delete an item straight away with the following code:
#[tokio::test]async fn test_sqlx_postgres_delete_no_existing_item() { setup().await; let title = "placeholder".to_string(); let user_id = 1; let result = sqlx_postgres_delete_one( title.clone(), user_id ).await; assert!(result.is_err());}With these two tests, we can now move on to refactoring our test script to run our data access tests, because we need to run and then shut down our databases.
Refactoring our testing script
Section titled “Refactoring our testing script”So far, our testing script tests two different workspaces, and we are about to add the data access layer testing, making it three. As you add more tests, the terminal printout will become a mess, and you will spend most of your time scrolling through lengthy terminal printouts just trying to find the service that you want to inspect. We now must coordinate database access for tests. As always, a key part of succeeding in software engineering is constantly reassessing and managing your complexity. We are going to rewrite our testing bash script, so we run all our unit tests that do not need any state and stream the output into their own log files. We can then spin up our docker-compose and run our tests that need access to those databases, shutting down the database afterwards. Before we write any testing bash, we must ensure that we have the following .env file in the root directory of the entire system:
TO_DO_DB_URL=postgres://username:password@localhost/to_do AUTH_DB_URL=postgres://username:password@localhost/to_do AUTH_API_URL=http://127.0.0.1:8081 JWT_SECRET=secret CACHE_API_URL=redis://127.0.0.1:6379 ELASTICSEARCH_URL=http://localhost:9200/logs/_doc
We can now move over to the testing script. First, we have the boilerplate code moving the working directory to the directory where the bash script is and moving out to the root directory with the following code:
#!/usr/bin/env bash
scripts/run_tests.sh
Section titled “scripts/run_tests.sh”# navigate to directorySCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"cd $SCRIPTPATHcd ..We then remove the logs directory if the logs directory is present, and then create the logs directory with the following code:
if [ -d "./logs" ]; then echo "Removing existing log directory: ./logs" rm -rf "./logs"fimkdir logsWe can now create a function where we run the pg_isready function in the postgres docker container to verify that the database is ready to accept connections with the following code:
scripts/run_tests.sh
Section titled “scripts/run_tests.sh”function check_postgres_ready() { docker compose exec -T postgres pg_isready \ -U username -d to_do}We then export the environment variables from the | file, and then run our unit tests, piping the results of those tests into their own log files with the following code:
export $(cat .env | xargs)cargo test -p to-do-core > ./logs/to-do-core.logcargo test -p to-do-actix-server > ./logs/to-do-actix-server.logWith our unit tests that do not need any databases out of the way, we then move on to running our docker-compose in the background and then looping until we can access the database with the following code:
scripts/run_tests.sh
Section titled “scripts/run_tests.sh”Docker compose up -d
Wait for PostgreSQL to be ready
Section titled “Wait for PostgreSQL to be ready”echo “Waiting for PostgreSQL to be ready…” until check_postgres_ready; do echo -n ”.” sleep 1 done
echo "PostgreSQL is ready."Finally, we run our data access unit tests and pipe the output into the dal.log file, shutting down the database after the tests have finished with the following code:
export TO_DO_MAX_CONNECTIONS=1cargo test -p dal --features sqlx-postgres \-- --test-threads=1 > ./logs/dal.logDocker compose down
It must be noted that we set the max connections to one. At the time of writing this, there is a known issue on sqlx where if the mac connections are higher than one, there are issues with timeouts on testing suites. Hopefully this error will be fixed in the future, and this issue will not affect our server in production. We can now run our tests, resulting in the following content for our data access layer log file:
running 2 tests test to_do_items::transactions::delete::tests:: test_sqlx_postgres_delete_no_existing_item … ok test to_do_items::transactions::delete::tests:: test_sqlx_postgres_delete_one_ok … ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
We can see that both of our tests pass. With this done, we can conclude that we have managed to test every layer.
Summary
Section titled “Summary”In this chapter, we built unit tests and mocks. We then configured our mocks to pass in a range of different outcomes to see how our code behaves under a range of different edge cases. Think back to when you were developing the application throughout the book. You would have to spin up the server and configure a range of requests to get to the piece of code you wanted to test, then manually perform the test that you wanted. This is very time-consuming, especially if you want to test your endpoint for a range of different conditions. Our unit tests not only give us feedback within seconds from an automated process, but they are also baked in, meaning that we can run one command to run all our tests within seconds whenever we change any of the code. Speeding up the feedback on how our code runs will always result in faster development time. This is why good, experienced developers practice test-driven development. This is where we write the tests as we are writing the code, resulting in instant isolated feedback on how our code acts as we are writing it. While unit testing will greatly speed up your development time and get rid of bugs in your logic before those bugs have time to hide in a bigger system, there is a criticism that while individual modules work well, the sum of all these modules might not work together. This is where end-to-end testing comes in. In the next chapter, we perform end-to-end testing where we spin up the entire system and run atomic tests to see how the entire system runs in different deployment states.
Questions
Section titled “Questions”- At a high level, how does unit testing speed up our development time?
- How do we mock the return of a database transaction?
- What is a setup function, and when would we typically use it?
- What is a flaky test?
- What are two precautions you can employ to avoid flaky tests?
Answers
Section titled “Answers”- Because we are only testing the unit of code that we are interested in, we do not have to perform a range of manual steps before getting to the unit of code that we are interested in. Due to mocking, we can also test a range of edge cases instantly. The quick feedback enables us to iterate through our code at a quicker rate and catch bugs we write before they can hide deeper in the code.
- Because we are using traits for interfaces for the database transactions, we can create another struct and implement the database trait for that struct. Because the struct is just for the test, we can hardcode the response for the database transaction.
- A setup function fires before a test. We generally use setup functions when there is a stateful component to the test. For instance, if we were using a database for the state, our setup would wipe the database and run migrations, ensuring that all of the test is deterministic.
- A flaky test is when other random forces alter the outcome of the test, making the outcome of the test random, resulting in the test randomly failing and passing.
- Wipe stateful components before the test and run your tests in a single-threaded context to avoid concurrency issues when interacting with the state.
Learn more on Discord
Section titled “Learn more on Discord”To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow this QR code: https://packt.link/EaKXL