Skip to content

Commit

Permalink
added tests for github repositories
Browse files Browse the repository at this point in the history
  • Loading branch information
0xMimir committed Oct 7, 2023
1 parent e301c11 commit 22b6aff
Show file tree
Hide file tree
Showing 11 changed files with 154 additions and 11 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ 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"] }
lazy_static = "1.4.0"
serial_test = "2.0.0"

error.path = "libs/error"
sdks.path = "libs/sdks"
Expand Down
2 changes: 2 additions & 0 deletions api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ support.workspace = true
[dev-dependencies]
adtest.workspace = true
reqwest.workspace = true
lazy_static.workspace = true
serial_test.workspace = true

[[bin]]
path = "src/main.rs"
Expand Down
18 changes: 16 additions & 2 deletions api/src/jobs/github_repositories/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
mod contract;
mod domain;
pub mod infrastructure;
#[cfg(test)]
mod test;

pub use domain::GithubRepositoriesCron;
use infrastructure::{PgRepository, PgService};
use sdks::github::Github;
use sea_orm::DatabaseConnection;
use std::sync::Arc;

///
/// Create and spawn github repositories job
///
pub fn setup(sea_pool: Arc<DatabaseConnection>) -> tokio::task::JoinHandle<()> {
let cron = create_gr(sea_pool);
cron.spawn_cron()
}

///
/// Create GithubRepositoriesCron with default implementations
///
fn create_gr(
sea_pool: Arc<DatabaseConnection>,
) -> GithubRepositoriesCron<PgRepository, PgService, Github> {
let repository = PgRepository::new(sea_pool.clone());
let service = PgService::new(sea_pool);
let github_api_key = config::get("GITHUB_KEY").ok();
Expand All @@ -18,6 +33,5 @@ pub fn setup(sea_pool: Arc<DatabaseConnection>) -> tokio::task::JoinHandle<()> {
None => Github::default(),
};

let cron = GithubRepositoriesCron::new(repository, service, github);
cron.spawn_cron()
GithubRepositoriesCron::new(repository, service, github)
}
68 changes: 68 additions & 0 deletions api/src/jobs/github_repositories/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use sea_orm::{prelude::Uuid, sea_query::OnConflict, ColumnTrait, EntityTrait, QueryFilter, Set};
use store::{github_projects, github_repositories};
use support::db_pool::create_db_pool;

lazy_static::lazy_static! {
static ref GITHUB_ID: Uuid = Uuid::parse_str("d7c33c88-8938-4998-a348-da1dd95f897a").unwrap();
}

#[adtest(
setup = async test_setup,
cleanup = async cleanup
)]
#[serial_test::serial]
async fn test_github_repositories() {
config::dotenv_init();
let sea_pool = create_db_pool().await;
let job = super::create_gr(sea_pool.clone());

job.cron_job().await.expect("Error while running job");

let repos = github_repositories::Entity::find()
.filter(github_repositories::Column::Project.eq(*GITHUB_ID))
.all(sea_pool.as_ref())
.await
.unwrap();

assert!(repos
.iter()
.find(|model| model.repository_name == "bitcoin")
.is_some());

assert!(repos
.iter()
.find(|model| model.repository_name == "bips")
.is_some());
}

async fn test_setup() {
let sea_pool = create_db_pool().await;

let model = github_projects::ActiveModel {
name: Set("bitcoin".to_owned()),
id: Set(*GITHUB_ID),
};

github_projects::Entity::insert(model)
.on_conflict(
OnConflict::column(github_projects::Column::Name)
.do_nothing()
.to_owned(),
)
.exec_without_returning(sea_pool.as_ref())
.await
.expect("Error creating model");

github_repositories::Entity::delete_many()
.exec(sea_pool.as_ref())
.await
.unwrap();
}

async fn cleanup() {
let sea_pool = create_db_pool().await;
github_projects::Entity::delete_by_id(*GITHUB_ID)
.exec(sea_pool.as_ref())
.await
.unwrap();
}
21 changes: 18 additions & 3 deletions api/src/jobs/info/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@ use std::time::Duration;

use sea_orm::EntityTrait;
use store::{cryptocurrencies, github_projects};
use support::db_pool::create_db_pool;
use support::{count::count, db_pool::create_db_pool};
use tokio::time::sleep;

#[adtest(cleanup = async cleanup_db)]
#[adtest(
setup = async cleanup_db,
cleanup = async cleanup_db
)]
#[serial_test::serial]
async fn test_info() {
config::dotenv_init();
let sea_pool = create_db_pool().await;
let job = super::create_info(sea_pool);
let job = super::create_info(sea_pool.clone());

let initial_count = count::<cryptocurrencies::Entity>(&sea_pool)
.await
.expect("Error getting count");

let handle = tokio::spawn(async move {
job.preform_init().await.expect("Error running init");
Expand All @@ -18,9 +26,16 @@ async fn test_info() {
sleep(Duration::from_secs(30)).await;

handle.abort();

let count = count::<cryptocurrencies::Entity>(&sea_pool)
.await
.expect("Error getting count");

assert!(count > initial_count);
}

async fn cleanup_db() {
config::dotenv_init();
let sea_pool = create_db_pool().await;

let _ = cryptocurrencies::Entity::delete_many()
Expand Down
19 changes: 14 additions & 5 deletions api/tests/setup.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use error::Result;
use reqwest::get;
use sea_orm::Database;
use std::{sync::Arc, time::Duration};
use std::time::Duration;
use support::db_pool::create_db_pool;
use tokio::time::sleep;

#[tokio::test]
Expand All @@ -10,9 +10,7 @@ use tokio::time::sleep;
/// be in env for api to start, not to function
///
async fn test_route_setup() -> Result<()> {
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 = create_db_pool().await;

let routes = api::create_api(sea_pool);

Expand All @@ -30,3 +28,14 @@ async fn test_route_setup() -> Result<()> {

Ok(())
}

#[tokio::test]
async fn test_job_setup() {
let db_pool = create_db_pool().await;
let jobs = api::setup_jobs(db_pool);

for job in jobs {
assert!(!job.is_finished());
job.abort();
}
}
11 changes: 11 additions & 0 deletions libs/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,25 @@ use std::env;

use error::{Error, Result};

///
/// Get variable from env
///
pub fn get(key: &str) -> Result<String> {
env::var(key).map_err(|_| Error::NotFoundWithCause(key.to_owned()))
}

///
/// Load env variables from .env file
/// if file is not found not variables will be loaded
///
pub fn dotenv_init() {
let _ = dotenv::dotenv();
}

///
/// Get variable from env if it doesn't exist
/// take default variable
///
pub fn get_default(key: &str, default: &str) -> String {
get(key).unwrap_or(default.to_owned())
}
1 change: 1 addition & 0 deletions libs/support/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ edition = "2021"

[dependencies]
config.workspace = true
error.workspace = true
sea-orm.workspace = true
serde.workspace = true
17 changes: 17 additions & 0 deletions libs/support/src/count.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use error::{Error, Result};
use sea_orm::{
prelude::{EntityTrait, PaginatorTrait},
DatabaseConnection,
};

///
/// Function that takes count of entities in table
///
pub async fn count<T>(db: &DatabaseConnection) -> Result<u64>
where
T: EntityTrait + Send + Sync,
<T as EntityTrait>::Model: Sync,
{
let query = T::find();
PaginatorTrait::count(query, db).await.map_err(Error::from)
}
3 changes: 3 additions & 0 deletions libs/support/src/db_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use std::sync::Arc;

use sea_orm::{Database, DatabaseConnection};

///
/// Create sea orm db pool
///
pub async fn create_db_pool() -> Arc<DatabaseConnection> {
let db_url = config::get("DATABASE_URL").expect("DATABASE_URL not set in env");
let pool = Database::connect(db_url)
Expand Down
3 changes: 2 additions & 1 deletion libs/support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ extern crate serde;

pub mod order;
pub mod pagination;
pub mod db_pool;
pub mod db_pool;
pub mod count;

0 comments on commit 22b6aff

Please sign in to comment.