Skip to content

Commit

Permalink
Merge pull request #2 from containerscrew/fix_tests
Browse files Browse the repository at this point in the history
Fixing tests
  • Loading branch information
containerscrew authored Oct 24, 2023
2 parents 610493e + 5016df9 commit 559629b
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 27 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Test 🛠️
on:
push:
branches:
- "main"
- "*"
tags:
- '*'
env:
Expand Down
10 changes: 10 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM docker.io/rust:1.73-slim-buster as build-env
WORKDIR /app
COPY . /app
RUN cargo build --release

FROM gcr.io/distroless/cc
WORKDIR /app
COPY --from=build-env /app/target/release/ipfinder /app/ipfinder
EXPOSE 8080
CMD ["./app/ipfinder"]
8 changes: 4 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async fn main() -> std::io::Result<()> {

println!("Ipfinder API started!");

// Load env variables with mongodb config
// Load env variables
let db_endpoint : String= env::var("DB_ENDPOINT").expect("You must set the DB_ENDPOINT environment var!");
let db_name: String = env::var("DB_NAME").expect("You must set the DB_NAME environment var!");
let collection_name: String = env::var("COLLECTION_NAME").expect("You must set the COLLECTION_NAME environment var!");
Expand Down Expand Up @@ -51,8 +51,8 @@ pub fn get_env() {

fn start_server(db: Arc<dyn DbOps+Send+Sync>) -> Server {
HttpServer::new(move || {
App::new().service(
web::scope("/api/v1/ipfinder")
App::new()
.service(web::scope("/api/v1/ipfinder")
.app_data(web::Data::new(db.clone()))
.wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i"))
Expand All @@ -63,7 +63,7 @@ fn start_server(db: Arc<dyn DbOps+Send+Sync>) -> Server {
.service(delete_ip)
)
}).workers(5)
.bind(("127.0.0.1", 8081)).expect("Unable to bind address!")
.bind(("127.0.0.1", 8080)).expect("Unable to bind address!")
.shutdown_timeout(30)
.run()
}
77 changes: 55 additions & 22 deletions src/test.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,85 @@
use std::sync::Arc;
use actix_web::{App, test::{call_and_read_body, call_and_read_body_json, init_service, TestRequest}, web, web::Bytes};
use actix_web::{App, http, HttpMessage, HttpRequest, HttpResponse, test::{call_and_read_body, call_and_read_body_json, init_service, TestRequest}, web, web::Bytes};
use actix_web::http::header::{CONTENT_TYPE, ContentType, HeaderValue};
use actix_web::middleware::Logger;
use crate::infrastructure::Db;
use crate::models::{GeoLocation, Ip};
use crate::routes::{delete_ip, get_ip, health, insert_ip, update_ip};
use actix_web::test::call_service;
use reqwest::Method;

use super::*;

#[actix_web::test]
#[ignore = "requires MongoDB instance running"]
// Pending to add container with test containers
async fn test() {
async fn should_insert_ip() {
dotenv().ok();
env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();

let db_endpoint = std::env::var("DB_ENDPOINT").unwrap_or_else(|_| "mongodb://admin:admin@localhost:27017/?maxPoolSize=20&w=majority".into());

// Register client
let db = Arc::new(Db::new(
let db: Arc<dyn DbOps + Send + Sync> = Arc::new(Db::new(
db_endpoint,
"ipfinder".to_string(),
"ips".to_string()
"ips".to_string(),
).await.expect("Can't connect to database"));

db.create_ips_index().await;
//db.create_ips_index().await;

let app = init_service(
let app = test::init_service(
App::new()
.app_data(web::Data::new(db.clone()))
.wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i"))
.service(health)
.service(insert_ip)
.service(get_ip)
.service(update_ip)
.service(delete_ip)
).await;

let ip = Ip{
ip: "4.4.4.4".into(),
let ip = Ip {
ip: "4.4.4.4".to_string(),
};

// Post method
let req = TestRequest::post()
.uri("/api/v1/ipfinder/insert")
.set_form(&ip)
let req = test::TestRequest::post()
.uri("/insert")
.set_json(&ip)
.insert_header(ContentType::json())
.to_request();
println!("{:?}", req);

let response = call_service(&app, req).await;
println!("{:?}", response.response());
assert_eq!(response.status(), http::StatusCode::OK);
}

#[actix_web::test]
async fn should_get_ip() {
dotenv().ok();
env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();

let response = call_and_read_body(&app, req).await;
assert_eq!(response, Bytes::from_static(b"ip saved"));
let db_endpoint = std::env::var("DB_ENDPOINT").unwrap_or_else(|_| "mongodb://admin:admin@localhost:27017/?maxPoolSize=20&w=majority".into());

// Get method
// Register client
let db: Arc<dyn DbOps + Send + Sync> = Arc::new(Db::new(
db_endpoint,
"ipfinder".to_string(),
"ips".to_string(),
).await.expect("Can't connect to database"));

let ip = Ip {
ip: "4.4.4.4".to_string(),
};

let app = test::init_service(
App::new()
.app_data(web::Data::new(db.clone()))
.wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i"))
.service(get_ip)
).await;

// Get method
let ip_geolocation = r#"
{
"status": "success",
Expand All @@ -67,10 +100,10 @@ async fn test() {
"#;

let req = TestRequest::get()
.uri(&format!("/api/v1/ipfinder/{}", &ip.ip))
.uri(&format!("/get/{}", &ip.ip))
.to_request();

let response: GeoLocation = call_and_read_body_json(&app, req).await;
let data: GeoLocation = serde_json::from_str(ip_geolocation).expect("Can't serialize Geolocation json from raw string");
assert_eq!(response, data);
}
}

0 comments on commit 559629b

Please sign in to comment.