Skip to content

Commit

Permalink
refactor: [torrust#142] simplify test api server
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Dec 23, 2022
1 parent 96f386c commit 68d521e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 98 deletions.
99 changes: 45 additions & 54 deletions tests/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
use core::panic;
use std::env;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes};
use reqwest::Response;
use tokio::task::JoinHandle;
use torrust_tracker::api::resource;
use torrust_tracker::api::resource::auth_key::AuthKey;
use torrust_tracker::api::resource::stats::Stats;
use torrust_tracker::api::resource::torrent::{self, Torrent};
use torrust_tracker::config::Configuration;
use torrust_tracker::jobs::tracker_api;
use torrust_tracker::protocol::clock::DurationSinceUnixEpoch;
use torrust_tracker::tracker::peer;
use torrust_tracker::protocol::info_hash::InfoHash;
use torrust_tracker::tracker::peer::{self, Peer};
use torrust_tracker::tracker::statistics::Keeper;
use torrust_tracker::{ephemeral_instance_keys, logging, static_time, tracker};

Expand Down Expand Up @@ -68,71 +67,63 @@ impl ConnectionInfo {
}
}

pub struct Server {
pub started: AtomicBool,
pub job: Option<JoinHandle<()>>,
pub tracker: Option<Arc<tracker::Tracker>>,
pub connection_info: Option<ConnectionInfo>,
pub async fn start_default_api_server() -> Server {
let configuration = tracker_configuration();
start_custom_api_server(configuration.clone()).await
}

impl Server {
pub fn new() -> Self {
Self {
started: AtomicBool::new(false),
job: None,
tracker: None,
connection_info: None,
}
}
pub async fn start_custom_api_server(configuration: Arc<Configuration>) -> Server {
start(configuration).await
}

pub async fn new_running_instance() -> Self {
let configuration = tracker_configuration();
Self::new_running_custom_instance(configuration.clone()).await
}
async fn start(configuration: Arc<Configuration>) -> Server {
let connection_info = ConnectionInfo::new(
&configuration.http_api.bind_address.clone(),
&configuration.http_api.access_tokens.get_key_value("admin").unwrap().1.clone(),
);

async fn new_running_custom_instance(configuration: Arc<Configuration>) -> Self {
let mut api_server = Self::new();
api_server.start(configuration).await;
api_server
}
// Set the time of Torrust app starting
lazy_static::initialize(&static_time::TIME_AT_APP_START);

pub async fn start(&mut self, configuration: Arc<Configuration>) {
if !self.started.load(Ordering::Relaxed) {
self.connection_info = Some(ConnectionInfo::new(
&configuration.http_api.bind_address.clone(),
&configuration.http_api.access_tokens.get_key_value("admin").unwrap().1.clone(),
));
// Initialize the Ephemeral Instance Random Seed
lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED);

// Set the time of Torrust app starting
lazy_static::initialize(&static_time::TIME_AT_APP_START);
// Initialize stats tracker
let (stats_event_sender, stats_repository) = Keeper::new_active_instance();

// Initialize the Ephemeral Instance Random Seed
lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED);
// Initialize Torrust tracker
let tracker = match tracker::Tracker::new(&configuration.clone(), Some(stats_event_sender), stats_repository) {
Ok(tracker) => Arc::new(tracker),
Err(error) => {
panic!("{}", error)
}
};

// Initialize stats tracker
let (stats_event_sender, stats_repository) = Keeper::new_active_instance();
// Initialize logging
logging::setup(&configuration);

// Initialize Torrust tracker
let tracker = match tracker::Tracker::new(&configuration.clone(), Some(stats_event_sender), stats_repository) {
Ok(tracker) => Arc::new(tracker),
Err(error) => {
panic!("{}", error)
}
};
self.tracker = Some(tracker.clone());
// Start the HTTP API job
tracker_api::start_job(&configuration.http_api, tracker.clone()).await;

// Initialize logging
logging::setup(&configuration);
Server {
tracker,
connection_info,
}
}

// Start the HTTP API job
self.job = Some(tracker_api::start_job(&configuration.http_api, tracker).await);
pub struct Server {
pub tracker: Arc<tracker::Tracker>,
pub connection_info: ConnectionInfo,
}

self.started.store(true, Ordering::Relaxed);
}
impl Server {
pub fn get_connection_info(&self) -> ConnectionInfo {
self.connection_info.clone()
}

pub fn get_connection_info(&self) -> Option<ConnectionInfo> {
self.connection_info.clone()
/// Add a torrent to the tracker
pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &Peer) {
self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await;
}
}

Expand Down
66 changes: 22 additions & 44 deletions tests/tracker_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,19 @@ mod tracker_api {
use torrust_tracker::api::resource::stats::Stats;
use torrust_tracker::protocol::info_hash::InfoHash;

use crate::api::{sample_torrent_peer, Client, Server};
use crate::api::{sample_torrent_peer, start_default_api_server, Client};

#[tokio::test]
async fn should_allow_getting_tracker_statistics() {
let api_server = Server::new_running_instance().await;
let api_server = start_default_api_server().await;

let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap();

let (peer, _peer_resource) = sample_torrent_peer();

let api_connection_info = api_server.get_connection_info().unwrap();
let api_connection_info = api_server.get_connection_info();

// Add a torrent to the tracker
api_server
.tracker
.unwrap()
.update_torrent_with_peer_and_get_stats(&info_hash, &peer)
.await;
api_server.add_torrent(&info_hash, &peer).await;

let stats_resource = Client::new(api_connection_info).get_tracker_statistics().await;

Expand Down Expand Up @@ -89,20 +84,15 @@ mod tracker_api {
mod for_torrent_resources {
#[tokio::test]
async fn should_allow_getting_torrents() {
let api_server = Server::new_running_instance().await;
let api_server = start_default_api_server().await;

let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap();

let (peer, _peer_resource) = sample_torrent_peer();

let api_connection_info = api_server.get_connection_info().unwrap();
let api_connection_info = api_server.get_connection_info();

// Add a torrent to the tracker
api_server
.tracker
.unwrap()
.update_torrent_with_peer_and_get_stats(&info_hash, &peer)
.await;
api_server.add_torrent(&info_hash, &peer).await;

let torrent_resources = Client::new(api_connection_info).get_torrents().await;

Expand All @@ -120,19 +110,14 @@ mod tracker_api {

#[tokio::test]
async fn should_allow_getting_a_torrent_info() {
let api_server = Server::new_running_instance().await;
let api_connection_info = api_server.get_connection_info().unwrap();
let api_server = start_default_api_server().await;
let api_connection_info = api_server.get_connection_info();

let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap();

let (peer, peer_resource) = sample_torrent_peer();

// Add a torrent to the tracker
api_server
.tracker
.unwrap()
.update_torrent_with_peer_and_get_stats(&info_hash, &peer)
.await;
api_server.add_torrent(&info_hash, &peer).await;

let torrent_resource = Client::new(api_connection_info).get_torrent(&info_hash.to_string()).await;

Expand All @@ -153,23 +138,22 @@ mod tracker_api {
use torrust_tracker::api::resource::torrent::{self, Torrent};
use torrust_tracker::protocol::info_hash::InfoHash;

use crate::api::{sample_torrent_peer, Client, Server};
use crate::api::{sample_torrent_peer, start_default_api_server, Client};

#[tokio::test]
async fn should_allow_whitelisting_a_torrent() {
let api_server = Server::new_running_instance().await;
let api_server = start_default_api_server().await;

let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned();

let res = Client::new(api_server.get_connection_info().unwrap())
let res = Client::new(api_server.get_connection_info())
.whitelist_a_torrent(&info_hash)
.await;

assert_eq!(res.status(), 200);
assert!(
api_server
.tracker
.unwrap()
.is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap())
.await
);
Expand All @@ -181,35 +165,34 @@ mod tracker_api {

use torrust_tracker::protocol::info_hash::InfoHash;

use crate::api::{Client, Server};
use crate::api::{start_default_api_server, Client};

#[tokio::test]
async fn should_allow_whitelisting_a_torrent() {
let api_server = Server::new_running_instance().await;
let api_server = start_default_api_server().await;

let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned();

let res = Client::new(api_server.get_connection_info().unwrap())
let res = Client::new(api_server.get_connection_info())
.whitelist_a_torrent(&info_hash)
.await;

assert_eq!(res.status(), 200);
assert!(
api_server
.tracker
.unwrap()
.is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap())
.await
);
}

#[tokio::test]
async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() {
let api_server = Server::new_running_instance().await;
let api_server = start_default_api_server().await;

let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned();

let api_client = Client::new(api_server.get_connection_info().unwrap());
let api_client = Client::new(api_server.get_connection_info());

let res = api_client.whitelist_a_torrent(&info_hash).await;
assert_eq!(res.status(), 200);
Expand All @@ -222,25 +205,20 @@ mod tracker_api {
mod for_key_resources {
use torrust_tracker::tracker::auth;

use crate::api::{Client, Server};
use crate::api::{start_default_api_server, Client};

#[tokio::test]
async fn should_allow_generating_a_new_auth_key() {
let api_server = Server::new_running_instance().await;
let api_server = start_default_api_server().await;

let seconds_valid = 60;

let auth_key = Client::new(api_server.get_connection_info().unwrap())
let auth_key = Client::new(api_server.get_connection_info())
.generate_auth_key(seconds_valid)
.await;

// Verify the key with the tracker
assert!(api_server
.tracker
.unwrap()
.verify_auth_key(&auth::Key::from(auth_key))
.await
.is_ok());
assert!(api_server.tracker.verify_auth_key(&auth::Key::from(auth_key)).await.is_ok());
}
}
}

0 comments on commit 68d521e

Please sign in to comment.