Skip to content

Commit

Permalink
Restructre tests
Browse files Browse the repository at this point in the history
Because of issue rust-lang/rust#46379
  • Loading branch information
Bastian Oppermann committed Jul 25, 2024
1 parent 3e73463 commit b63ab6e
Show file tree
Hide file tree
Showing 12 changed files with 164 additions and 192 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"cSpell.words": ["bukkit", "bungeecord"]
"cSpell.words": ["bukkit", "bungeecord", "testcontainer"]
}
104 changes: 17 additions & 87 deletions Cargo.lock

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

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ serde_json = "1.0"
validator = { version = "0.16", features = ["derive"] }
actix-web = "4"
serde_with = "3.9.0"
mockall = "0.13.0"
regex = "1.10.5"
once_cell = "1.19.0"
redis = { version = "0.25.4", features = ["tokio-comp", "aio"] }
mockall_double = "0.3.1"
redis = { version = "0.25.4", features = ["tokio-comp", "aio", "connection-manager"] }
redis-test = "0.4.0"
testcontainers = "0.20.1"
tokio = "1.39.1"

[dev-dependencies]
testcontainers = "0.20.1"
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,36 @@ pub mod charts;
pub mod parser;
pub mod software;
pub mod submit_data_schema;

use actix_web::{error, get, post, web, Responder};
use charts::simple_pie::SimplePie;
use software::find_by_url;
use submit_data_schema::SubmitDataSchema;

#[get("/")]
async fn index() -> impl Responder {
web::Json(SimplePie {
value: String::from("Test"),
})
}

#[post("/{software_url}")]
async fn handle_data_submission(
redis: web::Data<redis::Client>,
software_url: web::Path<String>,
_data: web::Json<SubmitDataSchema>,
) -> actix_web::Result<impl Responder> {
let mut con = redis
.get_connection_manager()
.await
.map_err(error::ErrorInternalServerError)?;

let software = find_by_url(&mut con, software_url.as_str()).await;

// TODO: This does not make sense, it's only here for testing
match software {
Ok(Some(s)) => Ok(web::Json(s)),
Ok(None) => Err(error::ErrorNotFound("Software not found")),
Err(e) => Err(error::ErrorInternalServerError(e)),
}
}
100 changes: 12 additions & 88 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,93 +1,17 @@
use actix_web::{get, post, web, App, HttpServer, Responder};
use data_processor::{charts::simple_pie::SimplePie, submit_data_schema::SubmitDataSchema};

#[get("/")]
async fn index() -> impl Responder {
web::Json(SimplePie {
value: String::from("Test"),
})
}

#[post("/{software_url}")]
async fn handle_data_submission(
_software_url: web::Path<String>,
_data: web::Json<SubmitDataSchema>,
) -> impl Responder {
web::Json(SimplePie {
value: String::from("Test"),
})
}
use actix_web::{web, App, HttpServer};
use data_processor::{handle_data_submission, index};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index).service(handle_data_submission))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
let redis = redis::Client::open("redis://127.0.0.1:6379").unwrap();

#[cfg(test)]
mod tests {
use actix_web::{http::header::ContentType, test, App};
use serde_json::json;

use super::*;

#[actix_web::test]
async fn test_submit_data() {
let app = test::init_service(App::new().service(handle_data_submission)).await;
let req = test::TestRequest::post()
.uri("/bukkit")
.insert_header(ContentType::json())
.set_payload(
json!({
"playerAmount": 0,
"onlineMode": 1,
"bukkitVersion": "1.21-38-1f5db50 (MC: 1.21)",
"bukkitName": "Paper",
"javaVersion": "21.0.2",
"osName": "Windows 11",
"osArch": "amd64",
"osVersion": "10.0",
"coreCount": 24,
"service": {
"pluginVersion": "1.0.0-SNAPSHOT",
"id": 1234,
"customCharts": [
{
"chartId": "chart_id",
"data": {
"value": "My value"
}
}
]
},
"serverUUID": "7386d410-f71e-447c-b356-ee809c7db098",
"metricsVersion": "3.0.2"
})
.to_string(),
)
.to_request();

let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
}

#[actix_web::test]
async fn test_index_get() {
let app = test::init_service(App::new().service(index)).await;
let req = test::TestRequest::default()
.insert_header(ContentType::plaintext())
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
}

#[actix_web::test]
async fn test_index_post() {
let app = test::init_service(App::new().service(index)).await;
let req = test::TestRequest::post().uri("/").to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_client_error());
}
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(redis.clone()))
.service(index)
.service(handle_data_submission)
})
.bind(("127.0.0.1", 1234))?
.run()
.await
}
17 changes: 16 additions & 1 deletion src/software.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::collections::{HashMap, HashSet};
extern crate redis;
use redis::{aio::ConnectionLike, AsyncCommands};
use serde::{Deserialize, Serialize};

use crate::charts::chart::DefaultChartTemplate;

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Software {
pub id: i16,
pub name: String,
Expand All @@ -29,9 +30,23 @@ pub async fn find_all<C: ConnectionLike + AsyncCommands>(
}
}

software.sort_by_key(|s| s.id);

Ok(software)
}

pub async fn find_by_url<C: ConnectionLike + AsyncCommands>(
con: &mut C,
url: &str,
) -> Result<Option<Software>, redis::RedisError> {
let id = _find_software_id_by_url(con, url).await?;
if id.is_none() {
return Ok(None);
}

find_by_id(con, id.unwrap()).await
}

pub async fn find_by_id<C: ConnectionLike + AsyncCommands>(
con: &mut C,
id: i16,
Expand Down
2 changes: 2 additions & 0 deletions tests/integration_tests/helper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod redis_testcontainer;
pub mod test_environment;
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ use testcontainers::{
ContainerAsync, GenericImage,
};

pub struct BoundRedisClient {
pub struct RedisTestcontainer {
client: redis::Client,
// Bind the container to the struct to keep it alive
_container: ContainerAsync<GenericImage>,
}

impl BoundRedisClient {
impl RedisTestcontainer {
pub async fn new() -> Self {
let container = GenericImage::new("redis", "7.2.4")
.with_exposed_port(6379.tcp())
Expand Down
Loading

0 comments on commit b63ab6e

Please sign in to comment.