Skip to content

Commit

Permalink
added test for get
Browse files Browse the repository at this point in the history
  • Loading branch information
0xMimir committed Oct 6, 2023
1 parent 773c1ee commit 62447a0
Show file tree
Hide file tree
Showing 25 changed files with 160 additions and 38 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
.env
/.vscode
tarpaulin-report.*
codecov
codecov
trampolin.sh
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ sea-orm = { version = "0.12.3", features = [
"sqlx-postgres",
] }
tokio = { version = "1.32.0", features = ["full"] }
reqwest = "0.11.20"
reqwest = { version = "0.11.20", features = ["json"] }
serde = { version = "1.0.188", features = ["derive"] }
serde_json = { version = "1.0.107" }
thiserror = "1.0.49"
Expand All @@ -21,10 +21,12 @@ actix = "0.13.1"
actix-web = "4.4.0"
utoipa = { version = "3.5.0", features = ["uuid", "actix_extras"] }
validify = "1.0.11"
uuid = { version = "1.4.1", features = ["v4"] }

error.path = "libs/error"
sdks.path = "libs/sdks"
store.path = "libs/store"
config.path = "libs/config"
api.path = "api"
support.path = "libs/support"
adtest.git = "https://github.com/0xMimir/adtest.git"
10 changes: 8 additions & 2 deletions api/src/api/cryptocurrencies/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,18 @@ use super::data::GetCryptoCurrenciesQuery;
pub trait DbRepositoryContract {
async fn get_issues_for_repository(&self, repository_id: Uuid) -> Result<Vec<Issues>>;
async fn get_cryptocurrency(&self, id: Uuid) -> Result<CryptoCurrencyWithRepositories>;
async fn get_cryptocurrencies(&self, query: GetCryptoCurrenciesQuery) -> Result<Pagination<CryptoCurrencyView>>;
async fn get_cryptocurrencies(
&self,
query: GetCryptoCurrenciesQuery,
) -> Result<Pagination<CryptoCurrencyView>>;
}

#[async_trait]
pub trait CryptocurrenciesContract {
async fn get_issues_for_repository(&self, repository_id: Uuid) -> Result<Vec<Issues>>;
async fn get_cryptocurrency(&self, id: Uuid) -> Result<CryptoCurrencyWithRepositories>;
async fn get_cryptocurrencies(&self, query: GetCryptoCurrenciesQuery) -> Result<Pagination<CryptoCurrencyView>>;
async fn get_cryptocurrencies(
&self,
query: GetCryptoCurrenciesQuery,
) -> Result<Pagination<CryptoCurrencyView>>;
}
4 changes: 1 addition & 3 deletions api/src/api/cryptocurrencies/handlers/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ pub async fn get_cryptocurrencies<S: CryptocurrenciesContract>(
query.validate()?;
let query = query.into_inner().into();

let value = service
.get_cryptocurrencies(query)
.await?;
let value = service.get_cryptocurrencies(query).await?;

Ok(HttpResponse::Ok().json(value))
}
2 changes: 1 addition & 1 deletion api/src/api/cryptocurrencies/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use sea_orm::DatabaseConnection;
use self::{domain::Cryptocurrencies, handlers::*, repository::PgRepository};

mod contract;
pub(super) mod docs;
mod data;
pub(super) mod docs;
mod domain;
mod handlers;
mod repository;
Expand Down
2 changes: 1 addition & 1 deletion api/src/api/kenobi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use actix_web::{get, HttpResponse};
#[get("/hello-there")]
///
/// Route to know that api has started up
///
///
pub async fn hello_there() -> HttpResponse {
HttpResponse::Ok().body("General Kenobi")
}
4 changes: 2 additions & 2 deletions api/tests/setup.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{sync::Arc, time::Duration};
use error::Result;
use reqwest::get;
use sea_orm::Database;
use std::{sync::Arc, time::Duration};
use tokio::time::sleep;

#[tokio::test]
Expand All @@ -24,7 +24,7 @@ async fn test_route_setup() -> Result<()> {
.await?
.text()
.await?;

assert_eq!(response, "General Kenobi");
handle.abort();

Expand Down
2 changes: 1 addition & 1 deletion libs/error/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub enum Error {
Validation(#[from] validify::ValidationErrors),

#[error("Unauthorized")]
Unauthorized
Unauthorized,
}

impl Error {
Expand Down
10 changes: 5 additions & 5 deletions libs/sdks/src/coingecko/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ pub(crate) struct ErrorResponse {
}

#[derive(Deserialize)]
pub(crate) struct SimpleError{
pub error: String
pub(crate) struct SimpleError {
pub error: String,
}

#[derive(Deserialize)]
Expand All @@ -89,12 +89,12 @@ impl From<ErrorResponse> for Error {
}
}

impl From<SimpleError> for Error{
impl From<SimpleError> for Error {
fn from(value: SimpleError) -> Self {
if value.error == "coin not found"{
if value.error == "coin not found" {
return Error::NotFound;
}

Self::InternalServer(value.error)
}
}
}
2 changes: 1 addition & 1 deletion libs/sdks/src/github/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl From<ErrorResponse> for Error {
return Error::NotFound;
}

if value.message == "Bad credentials"{
if value.message == "Bad credentials" {
return Error::Unauthorized;
}

Expand Down
2 changes: 1 addition & 1 deletion libs/sdks/src/github/domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,4 @@ impl Github {
Err(_) => Err(Error::InternalServer(response)),
}
}
}
}
7 changes: 5 additions & 2 deletions libs/sdks/tests/github.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use error::{Result, Error};
use error::{Error, Result};
use sdks::github::{Github, GithubContract};

#[tokio::test]
Expand Down Expand Up @@ -31,7 +31,10 @@ async fn test_error_handling() -> Result<()> {
assert!(matches!(error, Error::Unauthorized));

let github = Github::new();
let error = github.get_repos("github-that-does-not-exist", 1).await.unwrap_err();
let error = github
.get_repos("github-that-does-not-exist", 1)
.await
.unwrap_err();
assert!(matches!(error, Error::NotFoundWithCause(_)));

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion libs/store/src/objects/cryptocurrencies.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use sea_orm::{prelude::Uuid, FromQueryResult};

#[derive(FromQueryResult, Serialize)]
#[derive(FromQueryResult, Serialize, Deserialize)]
pub struct CryptoCurrencyView {
pub id: Uuid,
pub name: String,
Expand Down
2 changes: 1 addition & 1 deletion libs/support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
extern crate serde;

pub mod order;
pub mod pagination;
pub mod pagination;
8 changes: 4 additions & 4 deletions libs/support/src/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ pub enum Order {
Desc,
}

impl From<Order> for sea_orm::Order{
impl From<Order> for sea_orm::Order {
fn from(value: Order) -> Self {
match value{
match value {
Order::Asc => Self::Asc,
Order::Desc => Self::Desc
Order::Desc => Self::Desc,
}
}
}
}
8 changes: 4 additions & 4 deletions libs/support/src/pagination.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#[derive(Serialize)]
pub struct Pagination<T>{
#[derive(Serialize, Deserialize)]
pub struct Pagination<T> {
pub page: u64,
pub per_page: u64,
pub order_by: Vec<String>,
pub data: Vec<T>,
pub total_items: u64,
pub last_page: u64
}
pub last_page: u64,
}
2 changes: 1 addition & 1 deletion migrations/2023-09-30-125034_cryptocurrencies/up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ create table cryptocurrencies(
id uuid primary key default uuid_generate_v4() not null,
name varchar(255) not null unique,
coingecko_id varchar(255) not null unique,
github uuid references github_projects(id),
github uuid references github_projects(id) on delete set null,
gitlab varchar(255),
description text
)
2 changes: 1 addition & 1 deletion migrations/2023-10-01-102605_github-repositories/up.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
create table github_repositories(
id uuid primary key default uuid_generate_v4() not null,
project uuid references github_projects(id) not null,
project uuid not null references github_projects(id) on delete cascade,
repository_name varchar(255) not null,
unique(project, repository_name)
)
2 changes: 1 addition & 1 deletion migrations/2023-10-01-145428_issues/up.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
create table issues(
id uuid primary key default uuid_generate_v4() not null,
repository uuid references github_repositories(id) not null,
repository uuid not null references github_repositories(id) on delete cascade,
issue bigint not null,
title text not null,
description text,
Expand Down
7 changes: 7 additions & 0 deletions tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
adtest.workspace = true
api.workspace = true
config.workspace = true
error.workspace = true
reqwest.workspace = true
sea-orm.workspace = true
serde.workspace = true
serde_json.workspace = true
store.workspace = true
support.workspace = true
tokio.workspace = true
uuid.workspace = true
74 changes: 74 additions & 0 deletions tests/src/cryptocurrencies/get.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use crate::request::request;
use error::Result;
use reqwest::Method;
use sea_orm::{
prelude::Uuid, sea_query::OnConflict, DatabaseConnection, EntityTrait, ModelTrait, Set,
};
use store::{cryptocurrencies, github_projects, github_repositories, objects::CryptoCurrencyView};
use support::pagination::Pagination;

///
/// Test function for /api/v1/crypto
///
pub async fn api_v1_crypto(sea_pool: &DatabaseConnection) {
let (github, crypto) = setup(sea_pool).await.unwrap();

let response: Pagination<CryptoCurrencyView> =
request("/api/v1/crypto", Method::GET, ()).await.unwrap();

assert!(!response.data.is_empty());

let response: Pagination<CryptoCurrencyView> =
request("/api/v1/crypto?search=oooooogggggaaaaa", Method::GET, ())
.await
.unwrap();

assert!(response.data.is_empty());

github.delete(sea_pool).await.unwrap();
crypto.delete(sea_pool).await.unwrap();
}

async fn setup(
sea_pool: &DatabaseConnection,
) -> Result<(github_projects::Model, cryptocurrencies::Model)> {
let github = github_projects::ActiveModel {
id: Set(Uuid::new_v4()),
name: Set("TestGit".to_owned()),
};

let github = github_projects::Entity::insert(github)
.on_conflict(
OnConflict::column(github_projects::Column::Name)
.do_nothing()
.to_owned(),
)
.exec_with_returning(sea_pool)
.await?;

let crypto = cryptocurrencies::ActiveModel {
id: Set(Uuid::new_v4()),
name: Set("Test coin 1000".to_owned()),
coingecko_id: Set("test-coin-at-coingecko".to_owned()),
github: Set(Some(github.id)),
..Default::default()
};

let crypto = cryptocurrencies::Entity::insert(crypto)
.on_conflict(OnConflict::default().do_nothing().to_owned())
.exec_with_returning(sea_pool)
.await?;

let github_repo = github_repositories::ActiveModel {
project: Set(github.id),
repository_name: Set("good-repo".to_owned()),
..Default::default()
};

github_repositories::Entity::insert(github_repo)
.on_conflict(OnConflict::default().do_nothing().to_owned())
.exec(sea_pool)
.await?;

Ok((github, crypto))
}
7 changes: 7 additions & 0 deletions tests/src/cryptocurrencies/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use sea_orm::DatabaseConnection;

mod get;

pub async fn test(sea_pool: &DatabaseConnection) {
get::api_v1_crypto(sea_pool).await
}
6 changes: 5 additions & 1 deletion tests/src/e2e_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@ use sea_orm::Database;
use std::{sync::Arc, time::Duration};
use tokio::time::sleep;

use crate::cryptocurrencies;

#[tokio::test]
async fn e2e_api() {
let db_url = config::get("DATABASE_URL").unwrap();
let pool = Database::connect(db_url).await.unwrap();
let sea_pool = Arc::new(pool);
let sea_pool = Arc::new(pool.clone());

let routes = api::create_api(sea_pool);

let handle = tokio::spawn(async move { routes.await });

sleep(Duration::from_secs(1)).await;

cryptocurrencies::test(&pool).await;

handle.abort();
}
10 changes: 7 additions & 3 deletions tests/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
pub (crate) mod request;
pub(crate) mod cryptocurrencies;
#[allow(unused)]
#[macro_use]
extern crate adtest;

pub mod cryptocurrencies;
pub mod request;

#[cfg(test)]
mod e2e_api;
mod e2e_api;
16 changes: 16 additions & 0 deletions tests/src/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use error::{Error, Result};
use reqwest::{Client, Method};
use serde::{de::DeserializeOwned, Serialize};

pub async fn request<U, B, R>(url: U, method: Method, body: B) -> Result<R>
where
U: Into<String>,
B: Serialize,
R: DeserializeOwned + 'static,
{
let client = Client::default();
let url = format!("http://localhost:1111{}", url.into());
let request = client.request(method, url).json(&body).send().await?;
let response_body = request.text().await?;
serde_json::from_str(&response_body).map_err(Error::from)
}

0 comments on commit 62447a0

Please sign in to comment.