End-to-End Testing
local graph
Chapter 15 — End-to-End Testing
Section titled “Chapter 15 — End-to-End Testing”15 End-to-End Testing
Section titled “15 End-to-End Testing”Unit testing gives us quick feedback on how our units of code work under a range of different inputs. However, how does the system work as a whole? Do all our units of code work when running together and communicating with each other? In this chapter, we are going to build end-to-end tests that automatically set up our system as a microservice cluster and perform a series of tests that make requests to the entire system running, and then inspect the responses. This chapter will cover the following:
- The importance of end-to-end testing
- Building our to-do HTTP kernel
- Building our atomic end-to-end tests
- Testing workflows with end-to-end tests
By the end of this chapter, you will be able to build automated pipelines that construct a microservice cluster and run a series of tests where the outcome of those tests is written to individual log files for you to inspect. You will also know about the difference between atomic end-to-end testing and testing workflows. We can get started by understanding the importance of end-to-end testing.
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 end-to-end testing
Section titled “The importance of end-to-end testing”End-to-end testing is different from unit testing. Unit testing is where we break down the code into small units. These small units are then tested with a range of inputs. The feedback for unit testing is quick, enabling us to develop and iterate code at a quick rate. However, it is not guaranteed, when the units are combined as a system, that they will work together. To ensure that all our code units work together as we expected, we implement end-to-end tests. End-to-end tests are slower than unit tests. Like data access layer testing, we must spin up databases and alter the state of those databases between tests. End-to-end testing enables us to validate the user experience to simulate various possible user journeys. In this chapter, we will perform an atomic end-to-end test and build a workflow so we can see whether the user journey makes sense. For instance, we could have an extra field for our items where the item needs to be approved before it is displayed and we can perform actions on it. We could unit test the creation of the item. We could unit test the alteration and deletion of the item, asserting that errors are thrown if we pass in an item that has not been approved by our mocks when trying to edit or delete the item. However, if we do not have an endpoint that approves the item to be edited or deleted, then the workflow is broken. Our unit tests would then pick this up. This is, however, quicker than manual steps. We can see in Figure 15.1 that tethering to the database for the end-to-end test highlights the break in the workflow, failing the test:
Figure 15.1 – An end-to-end test failing due to an inconsistent workflow while all unit tests pass
Not only does end-to-end testing help with the testing of entire workflows, but it also tests how all our services communicate with each other. For instance, we could have a circular dependency where service A requires something from service B. However, for service B to complete the request, it could require something from service A. If this circular dependency were written in just one program, the program would refuse to compile. However, if the services are communicating over a network call, our compiler will not detect this circular dependency, as these services are different programs, as we can see depicted in Figure 15.2:
[figure outside: Figure 15.1] [figure outside: Figure 15.2]
Figure 15.2 – a circular dependency (first cycle of request = hard arrow, second cycle of request = dashed arrow, other cycles after are omitted, as the cycles are infinite)
In the preceding figure, we can see that all the unit tests pass because we are mocking the inputs. However, the circular dependency will result in an infinite loop and the request for the result will timeout. Considering the circular dependency, we can see that an end-to-end test would highlight potential problems that do not get caught by unit tests.
With this, we can see where unit testing and end-to-end testing are utilized. Unit tests are effective at speeding up development, enabling us to inspect how the code works on a granular level. We then move over to end-to-end tests to test the system as a whole and how our system will run in production. We need to run end-to-end tests before we deploy anything.
A halfway measure between end-to-end tests and unit tests is atomic end-to-end testing. This is where the database is wiped between each HTTP request. This can lead to quick code iteration and testing how the system will run in production. For instance, the circular dependency between two different servers will be detected in an atomic end-to-end test. However, errors and gaps in workflows will not be detected. In this chapter, we will be building out an atomic end-to-end test for our delete endpoint, and then a full end-to-end workflow test for our delete endpoint.
Now that we understand the importance of end-to-end testing and where end-to-end testing is used, we can move on to building our end-to-end testing system. We can start by creating HTTP kernels for our to-do nanoservice for our atomic end-to-end test.
Building our to-do HTTP kernel
Section titled “Building our to-do HTTP kernel”For now, we are going to create the to-do HTTP kernels so we can do the atomic end-to-end test for deleting a to-do item. Once the atomic end-to-end test works, we can then move on to building our auth HTTP kernel so we can test an entire workflow. For our atomic end-to-end test, we focus on the to-do HTTP kernel so we can perform database operations before and after the test, calling the HTTP API for the atomic end-to-end test.
[figure outside: Figure 15.2]
Before we build our HTTP functions, now is the time to sit back and look at the bigger picture. We are going to be calling multiple endpoints, and as our system grows, the number of HTTP calls will increase. All these calls will require knowing the URL of services. We get the URL via the environment variables. To keep the getting of URLs simple and easy to maintain, we can group them in our glue module. For our to-do URL, we have the following:
use super::errors::{NanoServiceError, NanoServiceErrorStatus};
pub fn get_to_do_url() -> Result<String, NanoServiceError> { std::env::var("TO_DO_API_URL").map_err(|e| { NanoServiceError::new(e.to_string(), NanoServiceErrorStatus::BadRequest) })}We must also ensure that we have made this public in our glue workspace with the following code:
...pub mod urls;...There is one last thing. We will be making HTTP requests, and these HTTP requests will return numbers as the response codes. We must add a function in our error status to construct the error status from the raw code returned with the following code:
impl NanoServiceErrorStatus { pub fn from_code(code: u16) -> NanoServiceErrorStatus { match code { 404 => NanoServiceErrorStatus::NotFound, 403 => NanoServiceErrorStatus::Forbidden, 400 => NanoServiceErrorStatus::BadRequest, 409 => NanoServiceErrorStatus::Conflict, 401 => NanoServiceErrorStatus::Unauthorized, _ => NanoServiceErrorStatus::Unknown, } }}We can now access the to-do service URL from any workspace in our system. We can also sleep well at night knowing that there are not going to be multiple different environment variable names for the to-do URL. We can now move on to building the HTTP endpoints for our to-do kernel. Like what we did for the auth kernel, we want to add an HTTP feature to ensure that we can support different mechanisms in the future, including directly calling the core functions. For this chapter, we are only going to focus on the HTTP feature to avoid bloat. At this stage in the book, you have seen how to support other methods, so supporting other methods should be clear to you. For our to-do kernel, we have the following layout:
├── nanoservices │ ├── … │ ├── to_do │ ├── core │ │ ├── … │ │ └── dal │ │ ├── … │ │ └── kernel │ │ ├── Cargo.toml │ │ └── src │ │ ├── api │ │ │ ├── basic_actions │ │ │ │ ├── create.rs │ │ │ │ ├── delete.rs │ │ │ │ ├── mod.rs │ │ │ │ └── mod.rs │ │ │ └── lib.rs │ │ │ └── …
We are only going to use the delete endpoint in our atomic end-to-end test. However, we must use the create endpoint before we can delete the item. Seeing as we are looking at the to-do kernel, we might as well build both endpoints now.
We have the following layout for our Cargo.toml for our to-do kernel:
[package]name = "to-do-kernel"version = "0.1.0"edition = "2021"[dependencies]core = { path = "../core", optional = true }dal = { path = "../dal" }reqwest = { version = "0.12.5", optional = true, features = ["json"]}glue = { path = "../../../glue" }cache-client = { path = "../../user-session-cache/cache-client"}[features]http = ["dep:reqwest"]Here, we can see that our http feature relies on the reqwest dependency, and we have access to our data access layer, glue, cache client, and core. There is nothing that we cannot access in terms of our to-do server in this kernel.
At this stage, it is a good idea for you to make sure that both create and delete files are available outside of the library with public declarations in the mod.rs files. We can now focus on our create endpoints.
Building our create item HTTP kernel
Section titled “Building our create item HTTP kernel”To enable us to build our create endpoint, we can define the imports of our create HTTP request with the following code:
#[cfg(feature = "http")]mod common_imports { pub use glue::errors::NanoServiceError; pub use dal::to_do_items::schema::NewToDoItem; pub use dal::to_do_items::enums::TaskStatus; pub use dal::to_do_items::schema::AllToDOItems; pub use glue::errors::NanoServiceErrorStatus; pub use glue::token::HeaderToken;}#[cfg(feature = "http")]mod reqwest_imports { pub use reqwest::Client; pub use glue::urls::get_to_do_url;}Here, we see that we have split up the imports into two types: common and request. This means that if we add other methods in the future, we can keep the imports for that new feature separate.
For our create interface, we have the following function:
#[cfg(any(feature = "http"))]pub async fn create_item( token: common_imports::HeaderToken, title: String, status: common_imports::TaskStatus)) -> Result<common_imports::AllToDoItems,common_imports::NanoServiceError> {#[cfg(feature = "http")]let user: common_imports::AllToDoItems = create_item_api_call( token, title, status).await?.into();return Ok(user)}Here, even though it is a bit more code, we can see that we prefix our import references with common_imports::. By just looking at this, we can see that all the imports used in this function are from the common imports. Therefore, we will be able to add other feature support to this function later. For our API call, we have the following function signature:
#[cfg(feature = "http")]async fn create_item_api_call( token: common_imports::HeaderToken, title: String, status: common_imports::TaskStatus) -> Result< common_imports::AllToDoItems, common_imports::NanoServiceError> { ...}Inside the common function, we get our URL and define the body of our request with the following code:
let full_url = format!( "{}/api/v1/create", reqwest_imports::get_to_do_url()?);let body = common_imports::NewToDoItem { title, status};Now that we have our URL, we can move on to building our client and sending a request with the following code:
let client = reqwest_imports::Client::new();let response = client.post(&full_url).header("token", token.encode()?).json(&body).send().await.map_err(|e| { common_imports::NanoServiceError::new( e.to_string(), common_imports::NanoServiceErrorStatus::BadRequest )})?;Finally, we map the response code, returning all the items or an error if a created response was not returned with the following code:
let status_code = response.status().as_u16();
if status_code == 201 { let items = response .json::<common_imports::AllToDoItems>() .await .map_err(|e: reqwest::Error| { common_imports::NanoServiceError::new( e.to_string(), common_imports::NanoServiceErrorStatus::from_code( status_code ) )?; return Ok(items)} else { let error_message = response.text().await.unwrap_or_else(|_| "No error message".to_string()) ); return Err(common_imports::NanoServiceError::new( error_message, common_imports::NanoServiceErrorStatus::from_code( status_code ) ))}status_code
)))}Now that we have a create HTTP request for our to-do server ready, we can now move on to building our delete HTTP kernel endpoint.
Building our delete item HTTP kernel Building our delete endpoint will follow the same approach as the create endpoint. This is a good opportunity for you to try to build it yourself. We start off with the following imports:
#[cfg(feature = "http")]mod common_imports { pub use glue::errors::NanoServiceError; pub use dal::to_do_items::schema::AllToDOItems; pub use glue::errors::NanoServiceErrorStatus;}#[cfg(feature = "http")]mod reqwest_imports { pub use reqwest::Client; pub use glue::token::HeaderToken; pub use glue::urls::get_to_do_url;}Our delete interface is defined by the following code:
#[cfg(any(feature = "http"))]pub async fn delete_item( token: reqwest_imports::HeaderToken, name: String) -> Result< common_imports::AllToDOItems, common_imports::NanoServiceError{
#[cfg(feature = "http")] let user: common_imports::AllToDOItems = delete_item_api_call( token, name ).await?.into(); return Ok(user)}Then our API signature function has the following form:
#[cfg(feature = "http")]async fn delete_item_api_call( token: reqwest_imports::HeaderToken, name: String) -> Result< common_imports::AllToDoItems, common_imports::NanoServiceError> { ...}Inside our API call function, we get our URL with the following code:
let full_url = format!( "{}/api/v1/delete/{}", reqwest_imports::get_to_do_url()?, name);We can then make the HTTP request with the following code:
let client = reqwest_imports::Client::new();let response = client.delete(&full_url).header("token", token.encode()?).send().await.map_err(|e| { common_imports::NanoServiceError::new( e.to_string(), common_imports::NanoServiceErrorStatus::BadRequest )})?;Finally, we handle the response with the following code:
let status_code = response.status().as_u16();
if status_code == 200 {let trimmed_user = response .json::<common_imports::AllToDoItems>() .await .map_err(|e| common_imports::NanoServiceError::new( e.to_string(), common_imports::NanoServiceErrorStatus::from_code( status_code ) ))?; return Ok(trimmed_user)} else { return Err(common_imports::NanoServiceError::new( "Failed to delete item".to_string(), common_imports::NanoServiceErrorStatus::from_code( status_code ) ))}Here, our HTTP API endpoints are done for the create and delete items. We can now move on to building our atomic end-to-end tests.
Building our atomic end-to-end tests
Section titled “Building our atomic end-to-end tests”We can house our atomic end-to-end tests in our networking directory with the following layout:
nanoservices to_do networking actix_server atomic-http-tests Cargo.toml src api basic_actions delete.rs mod.rs mod.rs main.rs We can see that we have called our testing suite as HTTP atomic tests. We have not specified the framework. This is because our HTTP interface should be the same no matter what framework we use. So, if we slot an Axum server into the networking directory, we can run the same atomic end-to-end testing suite against the Axum implementation of our to-do server.
For our atomic end-to-end test module, we need the following dependencies:
[package]name = "to-do-atomic-http-tests"version = "0.1.0"edition = "2021"
[dependencies]glue = { path = "../../../../glue" }to-do-kernel = { path = "../../kernel", features = ["http"] }tokio = { version = "1.39.2", features = ["full"] }cache-client = { path = "../../../user-session-cache/cache-client"}dal = { path = "../../dal", features = ["sqlx-postgres"]}sqlx = { version = "0.7.4", features = ["postgres", "json", "runtime-tokio"]}By looking at the dependencies, we can see that we directly access the database using the data access layer and sqlx. We can also see that our code will be interacting with the user cache. This is because we must create a user auth session in the cache. Remember, our server checks the user auth session cache before we can perform the deletion of the to-do item.
Seeing as we are accessing the user cache, we must also add the URL to the glue module so we can pass the URL into our tests with the following code:
pub fn get_cache_url() -> Result<String, NanoServiceError> { std::env::var("CACHE_API_URL").map_err(|e| { NanoServiceError::new(e.to_string(), NanoServiceErrorStatus::BadRequest) })}We are now at the stage where we can write the atomic end-to-end test.
Writing the end-to-end test
Section titled “Writing the end-to-end test”The outline of our atomic end-to-end test takes the following form:
// src/api/basic_actions/delete.rs
#[cfg(test)]mod tests { use to_do_kernel::api::basic_actions::delete::delete_item; use dal::connections::sqlx_postgres::SQLX_POSTGRES_POOL; use dal::to_do_items::schema::ToDoItem; use dal::migrations::run_migrations; use glue::sql_commands::WIPE_DB; use glue::token::HeaderToken; use glue::urls::get_cache_url; use cache_client::login;
async fn setup() { sqlx::query(WIPE_DB).execute( &*SQLX_POSTGRES_POOL ).await.unwrap(); run_migrations().await; } #[tokio::test] async fn test_delete_item() { setup().await; ... }}Here, we can see that the setup wipes the database and then runs the migrations. We then run the setup function at the start of the test_delete_item test.
Inside our test_delete_item function, we define some user credentials and log in to the user session cache with the following code:
// src/api/basic_actions/delete.rs
let user_id = "123".to_string();let perm_user_id = 1;
login(&get_cache_url().unwrap(),
&user_id, 60, perm_user_id ).await.unwrap();You can see that we are not doing any error handling in the test code. This is because we are testing the code, and if it errors, we need to know, but we do not need to handle errors to prevent the system from crashing or having unexpected behavior. In our test, it takes less code and is more direct to just unwrap the result so we can see exactly where the code breaks. We can also note that we do not have to create a user. If our user session is in the cache, then we can conclude that the user is logged in and exists. This is safe because no outside user will be able to directly access the cache when we deploy our application onto a server.
We then insert the item to be deleted into the database with the following code:
// src/api/basic_actions/delete.rslet title = "test_sqlx_postgres_delete_one".to_string();let item = ToDoItem { id: 1, title: title.clone(), status: "PENDING".to_string()};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();
assert_eq!(item.title, title);assert_eq!(item.status, "PENDING");assert_eq!(item.id, 1);Our assertions check that the insertion worked. We then insert the connection with the following code:
// src/api/basic_actions/delete.rslet _ = sqlx::query(" INSERT INTO user_connections (user_id, to_do_id) VALUES ($1, $2)").bind(perm_user_id)bind(item.id).execute(&*SQLX_POSTGRES_POOL).await.unwrap();We now have everything set up for our API call. We perform the API call with the following code:
// src/api/basic_actions/delete.rslet token = HeaderToken { unique_id: user_id.clone()};let outcome = delete_item(token, title).await.unwrap();assert_eq!(outcome.done.len(), 0);assert_eq!(outcome.pending.len(), 0);Our assertions assert that there are no items returned. This is reassuring; however, we return items that are connected to the user. If we deleted the connection but not the item, we would return zero items from the API call, even if we did not technically delete the item. To properly ensure that the deletion fully worked, we do direct database calls to the connections and items table to ensure that there are no records with the following code:
// src/api/basic_actions/delete.rslet items: Vec<ToDoItem> = sqlx::query_as::<_, ToDoItem>( "SELECT * FROM to_do_items;").fetch_all(&*SQLX_POSTGRES_POOL).await.unwrap();assert_eq!(items.len(), 0);
let connections: Vec<(i32, i32)> = sqlx::query_as::<_, (i32, i32)>( "SELECT * FROM user_connections;").fetch_all(&*SQLX_POSTGRES_POOL).await.unwrap();assert_eq!(connections.len(), 0);With these direct database queries, we can ensure that our deletion worked the way we wanted it to. At this point, you can explore other tests, such as what happens if the user is not authenticated or if the item does not exist. Now that you know about the methods of testing, these tests should be trivial, and covering them here would needlessly bloat the chapter. Remember, this end-to-end atomic test is running everything. Our system is going to be running the database, cache, server, and logging database. Just trying to run this manually would be time-consuming and error-prone, and there is a chance that you would later forget how to run these tests unless they are documented. If we are documenting the steps, we might as well put these steps into our test script. End-to-End Testing
Running our atomic end-to-end test
When it comes to running our atomic end-to-end test, we must ensure that all our databases are running, our environment variables are loaded, and that our to-do server is running. At this stage, we should have a look at our overall system. Our workspaces in the root Cargo.toml file should look like the following:
[workspace]resolver = "2"members = [ "glue", "ingress", "ingress/frontend/rust-interface", "nanoservices/auth/core", "nanoservices/auth/dal", "nanoservices/auth/kernel", "nanoservices/auth/networking/actix_server", "nanoservices/to_do/core", "nanoservices/to_do/dal", "nanoservices/to_do/kernel", "nanoservices/to_do/networking/actix_server", "nanoservices/to_do/networking/atomic-http-tests", "nanoservices/user-session-cache/cache-client", "nanoservices/user-session-cache/cache-module"]Here, we can see that our system is growing, but we are managing the complexity. For instance, we could break our to-do server off into its own repo to manage all the layers and tests for the server. We will cover how to manage multiple servers in different repos in Chapter 19.
For running our system, our .env file in the root of our system should house the following variables:
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 TO_DO_API_URL=http://127.0.0.1:8080 JWT_SECRET=secret CACHE_API_URL=redis://127.0.0.1:6379 ELASTICSEARCH_URL=http://localhost:9200/logs/_doc
Finally, we can run our atomic end-to-end test by building the to-do server, running the to-do server in the background, and then running the tests by adding the following to the end of our tests script:
// scripts/run_tests.sh
…
export TO_DO_MAX_CONNECTIONS=1
cargo test -p dal —features sqlx-postgres
— —test-threads=1 > ./logs/dal.log
cargo build -p actix_servercargo run -p actix_server &to_do_server_pid=$!sleep 1
cargo test -p to-do-atomic-http-tests -- \--test-threads=1 --nocapture \> ./logs/to-do-atomic-http-tests.logDocker compose down kill $to_do_server_pid
We can see that we add a sleep after we run the server, and we build the server before we run the server. We build the server in a different step because the running of the server has an & at the end of the command. This means that the server runs in the background. If we also run the build in the background, the build could take so long that we try to run the atomic end-to-end tests before the build is complete. We could try to guess how long the build will take, but this could change as the code base changes. It’s best to just block the testing script for the exact amount of time it takes to build the server and then run it in the background. We get the process ID of the running of the server task by using $!. We can see that we then run our atomic end-to-end test, writing the outcome of the test to a log file, and then tear down the Docker containers and kill the process that is running the to-do server.
If we run our testing script, our logs/to-do-atomic-http-tests.log file should have the following contents:
running 1 test test api::basic_actions::delete::tests::test_delete_item … Migrating to-do database… to-do database migrations completed: () ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.09s
Here, we can see that our atomic end-to-end test worked with our entire system working together. I personally find unit tests to be the tool I use when I am building code, as unit tests offer the quickest feedback and the easiest way to test the code under different inputs and outputs. I then move on to atomic end-to-end tests, as these are also quick – for instance, if you have an IDE that enables you to click and run a single test from your IDE, as seen in Figure 15.3:
Figure 15.3 – Running an isolated test from the VS Code editor
When I’m developing against atomic end-to-end tests, I make sure I have one terminal running the Docker containers, another terminal running the server, and I configure my IDE to have the environment variables. This results in a super smooth development environment where I change the code, refresh the server, and then click the individual test correlated to the endpoint that I am updating. But, I stress, this does not beat the speed of feedback from a raw unit test.
Now that we have our atomic end-to-end test done, the final test we are going to build is testing workflows with end-to-end testing.
Testing workflows with end-to-end tests
Section titled “Testing workflows with end-to-end tests”For testing our workflows, we are going to focus on our delete endpoint. Seeing as this is the last section of the book that applies Rust code directly to the to-do application code base, a lot of the Rust code syntax should not be new. Also, a lot of the general approaches have been covered. This means that we will run through a lot of the code blocks with minimal explanations. This section has been kept in the chapter to show how all the general code concepts we have covered are orchestrated to run an end-to-end workflow that tests how the auth and to-do server work together. To get our workflow testing infrastructure done, we must carry out the following steps:
- Configure existing code to accommodate the workflow tests.
- Build a kernel API call for creating the user.
- Build a kernel API call for logging in.
[figure outside: Figure 15.3]
- Create a workflows test workspace.
- Create a delete workflow test.
- Update our test runner bash script.
With these steps laid out, we can start configuring the existing code.
Configuring existing code to accommodate the workflow tests
Section titled “Configuring existing code to accommodate the workflow tests”The first task we can check off our list is adding the auth server URL to our glue module with the following code:
pub fn get_auth_url() -> Result<String, NanoServiceError> { std::env::var("AUTH_API_URL").map_err(|e| { NanoServiceError::new(e.to_string(), NanoServiceErrorStatus::BadRequest) })}We then add the base64 dependency for the basic auth for our auth kernel, and put the base64 into the http feature, resulting in the following Cargo file:
## nanoservices/auth/kernel/Cargo.toml[package]name = "auth-kernel"version = "0.1.0"edition = "2021"
[dependencies]auth-core = { path = "../core", optional = true }auth-dal = { path = "../dal" }reqwest = { version = "0.12.5", optional = true, features = ["json"] }glue = { path = "../../../glue" }cache-client = { path = "../../user-session-cache/cache-client" }base64 = { version = "0.22.1", optional = true }
[features]http = ["reqwest", "auth-core", "base64"]core-postgres = ["auth-core"]We then need to focus on the core of our auth server. Our CreateUser struct currently only has the Deserialize trait implemented. We are going to be making an HTTP call from a client, meaning we must serialize it. We implement the Serialize trait with the following code:
...use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]pub struct CreateUser { pub email: String, pub password: String}...Our existing code is now ready to support our API endpoints. We can start with the create HTTP request for the kernel.
Building a kernel API call for creating a user
Section titled “Building a kernel API call for creating a user”For our create HTTP endpoint for the kernel, we start off with the following imports:
#[cfg(any(feature = "core-postgres", feature = "http"))]mod common_imports { pub use glue::errors::NanoServiceError; pub use auth_core::api::users::create::CreateUser;}#[cfg(feature = "core-postgres")]mod core_imports { pub use auth_dal::users::descriptors::SqlxPostGresDescriptor; pub use auth_core::api::users::create::create as create_user_core;}#[cfg(feature = "http")]mod reqwest_imports { pub use reqwest::Client; pub use glue::errors::NanoServiceErrorStatus; pub use glue::urls::get_auth_url;}We create the interface for the create user API endpoint with the following code:
#[cfg(any(feature = "core-postgres", feature = "http"))]pub async fn create_user(user: common_imports::CreateUser) {-> Result<(), common_imports::NanoServiceError> { #[cfg(feature = “core-postgres”)] core_imports::create_user_core::<
core_imports::SqlxPostGresDescriptor >(user).await?;#[cfg(feature = "http")]create_user_api_call(user).await?; return Ok(()) }
Finally, we create the API call function with the following code:
#[cfg(feature = "http")]async fn create_user_api_call(user: common_imports::CreateUser) -> Result<(), common_imports::NanoServiceError> { let url = reqwest_imports::get_auth_url()?; let full_url = format!("{}/api/v1/users/create", url); let client = reqwest_imports::Client::new(); let response = client .post(&full_url) .json(&user) .send() .await .map_err(|e| { common_imports::NanoServiceError::new( e.to_string(), reqwest_imports::NanoServiceErrorStatus::BadRequest ) })?; let status_code = response.status().as_u16(); if status_code != 201 { return Err(common_imports::NanoServiceError::new( response.text().await.unwrap_or_else(|_| "Unknown error".to_string() ), reqwest_imports::NanoServiceErrorStatus::from_code( status_code ) )) } return Ok(())}Here, it must be noted that if the creation of the user is a success, then we do not return anything. This does not break our workflow because we know the email and password to log in. Now we must build our login API endpoint.
Building a kernel API call for logging in
Section titled “Building a kernel API call for logging in”For our login API call, we need the following imports:
#[cfg(any(feature = "core-postgres", feature = "http"))]mod common_imports { pub use glue::errors::NanoServiceError;}#[cfg(feature = "core-postgres")]mod core_imports { pub use auth_dal::users::descriptors::SqlxPostGresDescriptor; pub use auth_core::api::auth::login::login as login_core;}#[cfg(feature = "http")]mod reqwest_imports { pub use reqwest::Client; pub use glue::errors::NanoServiceErrorStatus; pub use glue::urls::get_auth_url; pub use base64::engine::general_purpose::STANDARD;}#[cfg(feature = "http")]use base64::Engine;Here, we can see that the Engine trait is imported outside of the modules. This is because the Engine trait needs to be in the same namespace to be utilized.
The interface for the login function takes the following form:
#[cfg(any(feature = "core-postgres", feature = "http"))]pub async fn login_user(email: String, password: String) -> Result<String, common_imports::NanoServiceError> { #[cfg(feature = "core-postgres")] let token = core_imports::login_core::<{ core_imports::SqlxPostGresDescriptor }>(email, password).await?; #[cfg(feature = "http")] let token = login_user_api_call(email, password).await?.into(); return Ok(token)}473
Our API call function has the following signature:
#[cfg(feature = "http")]async fn login_user_api_call(email: String, password: String) -> Result<String, common_imports::NanoServiceError> { ... }Inside our login function, we gather the information needed for the request with the following code:
let url = reqwest_imports::get_auth_url()?;let full_url = format!("{}/api/v1/auth/login", url);let auth = format!("{}:{}", email, password);let encoded_auth = reqwest_imports::STANDARD.encode(auth);let auth_header_value = format!("Basic {}", encoded_auth);We then make the login HTTP request with the basic auth method using the following code:
let client = reqwest_imports::Client::new();let response = client .get(&full_url) .header("Authorization", auth_header_value) .send() .await .map_err(|e| { common_imports::NanoServiceError::new( e.to_string(), reqwest_imports::NanoServiceErrorStatus::BadRequest ) })?;Finally, we process the response and return the token with the following code:
let status_code = response.status().as_u16();if status_code == 200 { let token: String = response.json().await.map_err(|e| { common_imports::NanoServiceError::new( e.to_string(), reqwest_imports::NanoServiceErrorStatus::BadRequest ) })?;return Ok(token) } else {
let response_message = match response.json().await {Ok(json) => json,Err(_) => "Unknown error".to_string()};return Err(common_imports::NanoServiceError::new( response_message, reqwest_imports::NanoServiceErrorStatus::from_code( status_code
)))}With this, our auth kernel interfaces are ready for our workflow test. Now there is nothing stopping us from creating the workflow test workspace.
Creating a workflow test workspace
Section titled “Creating a workflow test workspace”It might seem logical to build workflow tests in the same workspace as the atomic tests. However, workflow tests require the entire system to be running, whereas the atomic end-to-end tests only require the to-do server to be working. It is always good to keep these separate to avoid clashes and your integrated tests breaking because you did not have the right infrastructure running at the time.
For our layout, the workflow testing suite takes the following form:
nanoservices to_do networking http-workflow-tests Cargo.toml src items delete.rs mod.rs main.rs
With this, our Cargo.toml for the workflow testing workspace is defined by the following code:
nanoservices/to_do/networking/http-workflow-tests/Cargo.toml
Section titled “nanoservices/to_do/networking/http-workflow-tests/Cargo.toml”[package]name = "to-do-http-workflow-tests"version = "0.1.0"edition = "2021"[dependencies]to-do-kernel = { path = "../../kernel", features = ["http"] }auth-kernel = { path = "../../../auth/kernel", features = ["http"] }auth-core = { path = "../../../auth/core" }tokio = { version = "1.16.1", features = ["full"] }dal = { path = "../../dal", features = ["sqlx-postgres"] }auth-dal = { path = "../../../auth/dal" }glue = { path = "../../../../glue" }sqlx = { version = "0.7.4", features = ["postgres", "json", "runtime-tokio"]}We can see that the only external dependency we are relying on here is tokio for the async runtime. All other dependencies are crates that we have built. This makes sense as we are testing the entire workflow. We need to ensure that all our crates work together in our system.
With our workspace defined and ready, we can now build our delete workflow test.
Creating a delete workflow test
Section titled “Creating a delete workflow test”For our delete workflow, we have the following outline:
// src/items/delete.rs#[cfg(test)]mod tests { ... async fn setup() { ... } #[tokio::test] async fn test_delete_item_ok() { ... }}We will start with the imports. We essentially require a little bit of everything in our system to get this delete workflow running using the following:
// src/items/delete.rsuse to_do_kernel::api::basic_actions::{create::create_item, delete::delete_item};use auth_kernel::api::{users::create::create_user, auth::login::login_user};use dal::{ migrations::run_migrations as run_todo_migrations, connections::sqlx_postgres::SQLX_POSTGRES_POOL as todo_pool,};use auth_dal::{ migrations::run_migrations as run_auth_migrations, connections::sqlx_postgres::SQLX_POSTGRES_POOL as auth_pool,};use glue::{token::HeaderToken, sql_commands::WIPE_DB};use dal::to_do_items::enums::TaskStatus;use auth_core::api::users::create::CreateUser;This is a lot of imports, so we will focus on what these imports are used for as and when we use them. The first function we build is the setup function, with the following code:
// src/items/delete.rsasync fn setup() { sqlx::query(WIPE_DB).execute(&*todo_pool).await.unwrap(); sqlx::query(WIPE_DB).execute(&*auth_pool).await.unwrap(); run_todo_migrations().await; run_auth_migrations().await;}Here, we can see that we wipe both the auth and to-do databases and then run the migrations for both. For our local system, we are only using one database. However, if we want the freedom to test against systems where the auth and to-do server have their own database, then this setup allows for this. All we need to do is have another database in docker-compose and change the environment variable for one of the servers to point to that database and we have a separate database for each server.
Inside our test_delete_function function, we run the setup function, and create the user with the following code:
// src/items/delete.rssetup().await;let user = CreateUser { password: "test".to_string(),};create_user(user).await.unwrap();We then log the user in, and construct HeaderToken structs from the result of the login with the following code:
// src/items/delete.rslet token = login_user( "test".to_string()).await.unwrap();
let header_token = HeaderToken::decode(&token).unwrap();let header_token_ref = HeaderToken::decode(&token).unwrap();We now have enough tokens to perform a create and delete request. We create an item, asserting that the item has been created via the HTTP response with the following code:
// src/items/delete.rslet items = match create_item( header_token_ref, "code".to_string(), TaskStatus::PENDING).await { Ok(items) => items, Err(e) => { println!("error: {:?}", e); panic!("error creating item"); }};assert_eq!(items.done.len(), 0);assert_eq!(items.pending.len(), 1);We finally delete that item, asserting that there are no items left associated with the user, with the following code:
// src/items/delete.rslet items = delete_item( header_token, "code".to_string()).await.unwrap();assert_eq!(items.done.len(), 0);assert_eq!(items.pending.len(), 0);And here we have it, our workflow test is complete. If you really wanted to test how the workflow held up, you could log another user in at the same time and perform operations on the items of both users to ensure that the items associated with one user were not affected by operations performed on items belonging to another user.
Another benefit that we can see of our workflow testing is that it is high-level. If our functions are sensibly named, someone who is not a Rust developer could look over the workflow to see the steps and understand what is being tested. This helps a lot with bugging. If someone complains that they cannot perform a certain action on your system, and there is a workflow that is heavily tested, then it is unlikely to be an error with that workflow, and you can start looking in other places.
Our test workflow is now ready to be run. We can now move on to updating our testing script so we can run the workflow test.
Updating our test runner bash script
Section titled “Updating our test runner bash script”Our system has grown into a fully functioning microservices system with a frontend, custom Redis cache, remote logging system, unit tests, atomic end-to-end tests, and now end-to-end tests that inspect entire workflows. Before we try to run all our tests, we should just do a couple of simple sanity tests.
The root Cargo.toml of our system should have the following workspaces:
[workspace]resolver = "2"members = [ "glue", "ingress", "ingress/frontend/rust-interface", "nanoservices/auth/core", "nanoservices/auth/dal", "nanoservices/auth/kernel", "nanoservices/auth/networking/actix_server", "nanoservices/to_do/core", "nanoservices/to_do/dal", "nanoservices/to_do/kernel", "nanoservices/to_do/networking/actix_server", "nanoservices/to_do/networking/atomic-http-tests", "nanoservices/to_do/networking/http-workflow-tests", "nanoservices/user-session-cache/cache-client", "nanoservices/user-session-cache/cache-module"]Considering all these workspaces, we must also ensure that we have all the environment variables we need when running the entire system. The .env file in the root of our system should have the following:
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 TO_DO_API_URL=http://127.0.0.1:8080 JWT_SECRET=secret CACHE_API_URL=redis://127.0.0.1:6379 ELASTICSEARCH_URL=http://localhost:9200/logs/_doc
For our testing bash script, we are now going to have multiple servers running at the same time. If we are not tracking the logs of these servers, it can be a nightmare working out which server failed. To handle the running of the servers properly, we need to rewrite our testing script after the data access layer unit tests. First, we run the two servers pointing to their own logs with the following code:
cargo build -p actix_servercargo run -p actix_server > ./logs/todo_server.log &to_do_server_pid=$!cargo build -p auth_actix_servercargo run -p auth_actix_server > ./logs/auth_server.log &auth_server_pid=$!sleep 1We then run our atomic end-to-end tests, and then our end-to-end workflow tests, with the following code:
cargo test -p to-do-atomic-http-tests -- \--test-threads=1 --nocapture \> ./logs/to-do-atomic-http-tests.logcargo test -p to-do-http-workflow-tests -- \--test-threads=1 --nocapture \> ./logs/to-do-http-workflow-tests.logFinally, we tear down our databases and kill the servers with the following code:
scripts/run_tests.sh
Section titled “scripts/run_tests.sh”docker-compose down kill auth_server_pid
If we run our test script now, we will be able to see that all our tests have passed and that the logs to the servers are what we expect. With this, our testing suite is fully operational!
Summary
Section titled “Summary”In this chapter, we built tests that interact with our entire system. We can now build and run tests throughout the entire stack, from individual unit tests on individual servers in a microservice structure. This end-to-end testing can be employed in GitHub Actions or other continuous integration systems to prevent breaking code from being pushed into the main branch. It is also a good idea to run these end-to-end tests before performing a release to a live server.
We have now gotten a feel for how our system works when both servers are running with the cache, logging database, and main database. In the next chapter, we will cover how to package and deploy our system onto servers on AWS.
Questions
Section titled “Questions”- What bug can end-to-end testing catch that unit testing cannot (hint: compilers can also catch the error if there is just one server)?
- What bug can an end-to-end workflow test catch that an atomic end-to-end test cannot?
- How do we run and then clean up a server when performing an end-to-end test?
- How do we ensure that our system can be end-to-end tested as either a monolith or a micro-services cluster?
- In this chapter, we ran our end-to-end tests on one database. How could we break it out so each server had its own database?
Answers
Section titled “Answers”- Circular dependencies. End-to-end tests can detect a circular dependency between multiple servers. However, a unit test would miss this as the unit test mocks the inputs to the unit of code.
- Breaks in the workflow. Atomic end-to-end tests set up the state of the app for the individual endpoint. However, there may be a missing API endpoint, making it impossible for the user to complete the workflow. An end-to-end workflow test will catch this.
- We build the server first to avoid having to guess the build time. Once the build is finished, we run the server in the background by using the & symbol. We then keep note of the process ID of the running server and kill that process at the end of the testing script.
- We perform a wipe on all databases in the setup function and then perform all the migrations of the services in the system. If the system is monolithic, then all database actions will run on the same database, including the wipes. If the system is a microservice cluster, then each server will commit a wipe action and migration on its own database.
- We create an extra database in docker-compose with a different port. We then allocate the URL of that database with that port to an environment variable of the database for one of the servers. When we run the end-to-end tests, our servers will have their own databases.
Get this book’s PDF copy, code bundle, and more
Section titled “Get this book’s PDF copy, code bundle, and more”Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.
UNLOCK NOW
Note: Have your invoice handy. Purchases made directly from the Packt website don’t require an invoice.
[blank page]