Skip to content

Commit

Permalink
tests: [torrust#109] E2E tests for settings routes
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Apr 26, 2023
1 parent cac49cf commit 9b2266d
Show file tree
Hide file tree
Showing 7 changed files with 322 additions and 25 deletions.
4 changes: 4 additions & 0 deletions docker/bin/e2e-env-restart.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/bash

./docker/bin/e2e-env-down.sh
./docker/bin/e2e-env-up.sh
2 changes: 1 addition & 1 deletion src/routes/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub async fn get_settings(req: HttpRequest, app_data: WebAppData) -> ServiceResu
return Err(ServiceError::Unauthorized);
}

let settings = app_data.cfg.settings.read().await;
let settings: tokio::sync::RwLockReadGuard<TorrustConfig> = app_data.cfg.settings.read().await;

Ok(HttpResponse::Ok().json(OkResponse { data: &*settings }))
}
Expand Down
60 changes: 39 additions & 21 deletions tests/e2e/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use reqwest::Response as ReqwestResponse;
use serde::Serialize;

use super::contexts::category::{AddCategoryForm, DeleteCategoryForm};
use super::contexts::settings::UpdateSettingsForm;
use super::contexts::user::{LoginForm, RegistrationForm, TokenRenewalForm, TokenVerificationForm, Username};
use crate::e2e::connection_info::ConnectionInfo;
use crate::e2e::http::{Query, ReqwestQuery};
Expand Down Expand Up @@ -49,6 +49,24 @@ impl Client {
self.http_client.get("", Query::empty()).await
}

// Context: settings

pub async fn get_public_settings(&self) -> Response {
self.http_client.get("settings/public", Query::empty()).await
}

pub async fn get_site_name(&self) -> Response {
self.http_client.get("settings/name", Query::empty()).await
}

pub async fn get_settings(&self) -> Response {
self.http_client.get("settings", Query::empty()).await
}

pub async fn update_settings(&self, update_settings_form: UpdateSettingsForm) -> Response {
self.http_client.post("settings", &update_settings_form).await
}

// Context: user

pub async fn register_user(&self, registration_form: RegistrationForm) -> Response {
Expand Down Expand Up @@ -87,7 +105,26 @@ impl Http {
}

pub async fn get(&self, path: &str, params: Query) -> Response {
self.get_request_with_query(path, params).await
let response = match &self.connection_info.token {
Some(token) => reqwest::Client::builder()
.build()
.unwrap()
.get(self.base_url(path).clone())
.query(&ReqwestQuery::from(params))
.bearer_auth(token)
.send()
.await
.unwrap(),
None => reqwest::Client::builder()
.build()
.unwrap()
.get(self.base_url(path).clone())
.query(&ReqwestQuery::from(params))
.send()
.await
.unwrap(),
};
Response::from(response).await
}

pub async fn post<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
Expand Down Expand Up @@ -145,26 +182,7 @@ impl Http {
Response::from(response).await
}

pub async fn get_request_with_query(&self, path: &str, params: Query) -> Response {
get(&self.base_url(path), Some(params)).await
}

fn base_url(&self, path: &str) -> String {
format!("http://{}{}{path}", &self.connection_info.bind_address, &self.base_path)
}
}

async fn get(path: &str, query: Option<Query>) -> Response {
let response: ReqwestResponse = match query {
Some(params) => reqwest::Client::builder()
.build()
.unwrap()
.get(path)
.query(&ReqwestQuery::from(params))
.send()
.await
.unwrap(),
None => reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap(),
};
Response::from(response).await
}
1 change: 1 addition & 0 deletions tests/e2e/contexts/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod about;
pub mod category;
pub mod root;
pub mod settings;
pub mod user;
275 changes: 275 additions & 0 deletions tests/e2e/contexts/settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
use serde::{Deserialize, Serialize};

use crate::e2e::contexts::user::fixtures::logged_in_admin;
use crate::e2e::environment::TestEnv;

// Request data

pub type UpdateSettingsForm = Settings;

// Response data

#[derive(Deserialize)]
pub struct AllSettingsResponse {
pub data: Settings,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Settings {
pub website: Website,
pub tracker: Tracker,
pub net: Net,
pub auth: Auth,
pub database: Database,
pub mail: Mail,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Website {
pub name: String,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Tracker {
pub url: String,
pub mode: String,
pub api_url: String,
pub token: String,
pub token_valid_seconds: u64,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Net {
pub port: u64,
pub base_url: Option<String>,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Auth {
pub email_on_signup: String,
pub min_password_length: u64,
pub max_password_length: u64,
pub secret_key: String,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Database {
pub connect_url: String,
pub torrent_info_update_interval: u64,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Mail {
pub email_verification_enabled: bool,
pub from: String,
pub reply_to: String,
pub username: String,
pub password: String,
pub server: String,
pub port: u64,
}

#[derive(Deserialize)]
pub struct PublicSettingsResponse {
pub data: Public,
}

#[derive(Deserialize, PartialEq, Debug)]
pub struct Public {
pub website_name: String,
pub tracker_url: String,
pub tracker_mode: String,
pub email_on_signup: String,
}

#[derive(Deserialize)]
pub struct SiteNameResponse {
pub data: String,
}

#[tokio::test]
#[cfg_attr(not(feature = "e2e-tests"), ignore)]
async fn it_should_allow_guests_to_get_the_public_settings() {
let client = TestEnv::default().unauthenticated_client();

let response = client.get_public_settings().await;

let res: PublicSettingsResponse = serde_json::from_str(&response.body).unwrap();

assert_eq!(
res.data,
Public {
website_name: "Torrust".to_string(),
tracker_url: "udp://tracker:6969".to_string(),
tracker_mode: "Public".to_string(),
email_on_signup: "Optional".to_string(),
}
);
if let Some(content_type) = &response.content_type {
assert_eq!(content_type, "application/json");
}
assert_eq!(response.status, 200);
}

#[tokio::test]
#[cfg_attr(not(feature = "e2e-tests"), ignore)]
async fn it_should_allow_guests_to_get_the_site_name() {
let client = TestEnv::default().unauthenticated_client();

let response = client.get_site_name().await;

let res: SiteNameResponse = serde_json::from_str(&response.body).unwrap();

assert_eq!(res.data, "Torrust");
if let Some(content_type) = &response.content_type {
assert_eq!(content_type, "application/json");
}
assert_eq!(response.status, 200);
}

#[tokio::test]
#[cfg_attr(not(feature = "e2e-tests"), ignore)]
async fn it_should_allow_admins_to_get_all_the_settings() {
let logged_in_admin = logged_in_admin().await;
let client = TestEnv::default().authenticated_client(&logged_in_admin.token);

let response = client.get_settings().await;

let res: AllSettingsResponse = serde_json::from_str(&response.body).unwrap();

assert_eq!(
res.data,
Settings {
website: Website {
name: "Torrust".to_string(),
},
tracker: Tracker {
url: "udp://tracker:6969".to_string(),
mode: "Public".to_string(),
api_url: "http://tracker:1212".to_string(),
token: "MyAccessToken".to_string(),
token_valid_seconds: 7_257_600,
},
net: Net {
port: 3000,
base_url: None,
},
auth: Auth {
email_on_signup: "Optional".to_string(),
min_password_length: 6,
max_password_length: 64,
secret_key: "MaxVerstappenWC2021".to_string(),
},
database: Database {
connect_url: "sqlite://storage/database/torrust_index_backend_e2e_testing.db?mode=rwc".to_string(),
torrent_info_update_interval: 3600,
},
mail: Mail {
email_verification_enabled: false,
from: "[email protected]".to_string(),
reply_to: "[email protected]".to_string(),
username: String::new(),
password: String::new(),
server: "mailcatcher".to_string(),
port: 1025,
}
}
);
if let Some(content_type) = &response.content_type {
assert_eq!(content_type, "application/json");
}
assert_eq!(response.status, 200);
}

#[tokio::test]
#[cfg_attr(not(feature = "e2e-tests"), ignore)]
async fn it_should_allow_admins_to_update_all_the_settings() {
let logged_in_admin = logged_in_admin().await;
let client = TestEnv::default().authenticated_client(&logged_in_admin.token);

// todo: we can't actually change the settings because it would affect other E2E tests.
// Location for the `config.toml` file is hardcoded. We could use a ENV variable to change it.

let response = client
.update_settings(UpdateSettingsForm {
website: Website {
name: "Torrust".to_string(),
},
tracker: Tracker {
url: "udp://tracker:6969".to_string(),
mode: "Public".to_string(),
api_url: "http://tracker:1212".to_string(),
token: "MyAccessToken".to_string(),
token_valid_seconds: 7_257_600,
},
net: Net {
port: 3000,
base_url: None,
},
auth: Auth {
email_on_signup: "Optional".to_string(),
min_password_length: 6,
max_password_length: 64,
secret_key: "MaxVerstappenWC2021".to_string(),
},
database: Database {
connect_url: "sqlite://storage/database/torrust_index_backend_e2e_testing.db?mode=rwc".to_string(),
torrent_info_update_interval: 3600,
},
mail: Mail {
email_verification_enabled: false,
from: "[email protected]".to_string(),
reply_to: "[email protected]".to_string(),
username: String::new(),
password: String::new(),
server: "mailcatcher".to_string(),
port: 1025,
},
})
.await;

let res: AllSettingsResponse = serde_json::from_str(&response.body).unwrap();

assert_eq!(
res.data,
Settings {
website: Website {
name: "Torrust".to_string(),
},
tracker: Tracker {
url: "udp://tracker:6969".to_string(),
mode: "Public".to_string(),
api_url: "http://tracker:1212".to_string(),
token: "MyAccessToken".to_string(),
token_valid_seconds: 7_257_600,
},
net: Net {
port: 3000,
base_url: None,
},
auth: Auth {
email_on_signup: "Optional".to_string(),
min_password_length: 6,
max_password_length: 64,
secret_key: "MaxVerstappenWC2021".to_string(),
},
database: Database {
connect_url: "sqlite://storage/database/torrust_index_backend_e2e_testing.db?mode=rwc".to_string(),
torrent_info_update_interval: 3600,
},
mail: Mail {
email_verification_enabled: false,
from: "[email protected]".to_string(),
reply_to: "[email protected]".to_string(),
username: String::new(),
password: String::new(),
server: "mailcatcher".to_string(),
port: 1025,
}
}
);
if let Some(content_type) = &response.content_type {
assert_eq!(content_type, "application/json");
}
assert_eq!(response.status, 200);
}
2 changes: 0 additions & 2 deletions tests/e2e/contexts/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,6 @@ async fn it_should_not_allow_a_logged_in_user_to_renew_an_authentication_token_w
})
.await;

println!("Response body: {}", response.body);

let res: TokenRenewalResponse = serde_json::from_str(&response.body).unwrap();

assert_eq!(
Expand Down
Loading

0 comments on commit 9b2266d

Please sign in to comment.