normal unit test

This commit is contained in:
Felix Ableitner 2024-12-19 15:23:37 +01:00
parent 323b154e0b
commit 1b75fb2d71
4 changed files with 255 additions and 329 deletions

View file

@ -181,17 +181,6 @@ steps:
- cp target/debug/lemmy_server target/lemmy_server - cp target/debug/lemmy_server target/lemmy_server
when: *slow_check_paths when: *slow_check_paths
startup_errors:
image: *rust_image
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
CARGO_HOME: .cargo_home
commands:
- timeout --preserve-status 30 cargo run > lemmy.log 2>&1
- cat lemmy.log
- "! grep ERROR lemmy.log"
when: *slow_check_paths
check_diesel_migration: check_diesel_migration:
# TODO: use willsquire/diesel-cli image when shared libraries become optional in lemmy_server # TODO: use willsquire/diesel-cli image when shared libraries become optional in lemmy_server
image: *rust_image image: *rust_image

View file

@ -370,3 +370,18 @@ fn cors_config(settings: &Settings) -> Cors {
_ => cors_default, _ => cors_default,
} }
} }
#[cfg(test)]
pub mod tests {
use activitypub_federation::config::Data;
use lemmy_api_common::context::LemmyContext;
use std::env::set_current_dir;
pub async fn test_context() -> Data<LemmyContext> {
// hack, necessary so that config file can be loaded from hardcoded, relative path.
// Ignore errors as this gets called once for every test (so changing dir again would fail).
set_current_dir("crates/utils").ok();
LemmyContext::init_test_context().await
}
}

View file

@ -40,16 +40,19 @@ use lemmy_db_schema::{
utils::{find_action, functions::coalesce, get_conn, now, DbPool, DELETED_REPLACEMENT_TEXT}, utils::{find_action, functions::coalesce, get_conn, now, DbPool, DELETED_REPLACEMENT_TEXT},
}; };
use lemmy_routes::nodeinfo::{NodeInfo, NodeInfoWellKnown}; use lemmy_routes::nodeinfo::{NodeInfo, NodeInfoWellKnown};
use lemmy_utils::error::LemmyResult; use lemmy_utils::error::{LemmyErrorType, LemmyResult};
use reqwest_middleware::ClientWithMiddleware; use reqwest_middleware::ClientWithMiddleware;
use std::time::Duration; use std::time::Duration;
use tracing::{error, info, warn}; use tracing::{info, warn};
/// Schedules various cleanup tasks for lemmy in a background thread /// Schedules various cleanup tasks for lemmy in a background thread
pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> { pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
// Setup the connections // Setup the connections
let mut scheduler = AsyncScheduler::new(); let mut scheduler = AsyncScheduler::new();
startup_jobs(&mut context.pool()).await; startup_jobs(&mut context.pool())
.await
.inspect_err(|e| warn!("Failed to run startup tasks: {e}"))
.ok();
let context_1 = context.clone(); let context_1 = context.clone();
// Update active counts expired bans and unpublished posts every hour // Update active counts expired bans and unpublished posts every hour
@ -57,9 +60,18 @@ pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
let context = context_1.clone(); let context = context_1.clone();
async move { async move {
active_counts(&mut context.pool()).await; active_counts(&mut context.pool())
update_banned_when_expired(&mut context.pool()).await; .await
delete_instance_block_when_expired(&mut context.pool()).await; .inspect_err(|e| warn!("Failed to update active counts: {e}"))
.ok();
update_banned_when_expired(&mut context.pool())
.await
.inspect_err(|e| warn!("Failed to update expired bans: {e}"))
.ok();
delete_instance_block_when_expired(&mut context.pool())
.await
.inspect_err(|e| warn!("Failed to delete expired instance bans: {e}"))
.ok();
} }
}); });
@ -69,9 +81,18 @@ pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
let context = context_1.reset_request_count(); let context = context_1.reset_request_count();
async move { async move {
update_hot_ranks(&mut context.pool()).await; update_hot_ranks(&mut context.pool())
delete_expired_captcha_answers(&mut context.pool()).await; .await
publish_scheduled_posts(&context).await; .inspect_err(|e| warn!("Failed to update hot ranks: {e}"))
.ok();
delete_expired_captcha_answers(&mut context.pool())
.await
.inspect_err(|e| warn!("Failed to delete expired captcha answers: {e}"))
.ok();
publish_scheduled_posts(&context)
.await
.inspect_err(|e| warn!("Failed to publish scheduled posts: {e}"))
.ok();
} }
}); });
@ -81,7 +102,10 @@ pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
let context = context_1.clone(); let context = context_1.clone();
async move { async move {
clear_old_activities(&mut context.pool()).await; clear_old_activities(&mut context.pool())
.await
.inspect_err(|e| warn!("Failed to clear old activities: {e}"))
.ok();
} }
}); });
@ -94,8 +118,14 @@ pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
let context = context_1.clone(); let context = context_1.clone();
async move { async move {
overwrite_deleted_posts_and_comments(&mut context.pool()).await; overwrite_deleted_posts_and_comments(&mut context.pool())
delete_old_denied_users(&mut context.pool()).await; .await
.inspect_err(|e| warn!("Failed to overwrite deleted posts/comments: {e}"))
.ok();
delete_old_denied_users(&mut context.pool())
.await
.inspect_err(|e| warn!("Failed to delete old denied users: {e}"))
.ok();
update_instance_software(&mut context.pool(), context.client()) update_instance_software(&mut context.pool(), context.client())
.await .await
.inspect_err(|e| warn!("Failed to update instance software: {e}")) .inspect_err(|e| warn!("Failed to update instance software: {e}"))
@ -111,26 +141,25 @@ pub async fn setup(context: Data<LemmyContext>) -> LemmyResult<()> {
} }
/// Run these on server startup /// Run these on server startup
async fn startup_jobs(pool: &mut DbPool<'_>) { async fn startup_jobs(pool: &mut DbPool<'_>) -> LemmyResult<()> {
active_counts(pool).await; active_counts(pool).await?;
update_hot_ranks(pool).await; update_hot_ranks(pool).await?;
update_banned_when_expired(pool).await; update_banned_when_expired(pool).await?;
delete_instance_block_when_expired(pool).await; delete_instance_block_when_expired(pool).await?;
clear_old_activities(pool).await; clear_old_activities(pool).await?;
overwrite_deleted_posts_and_comments(pool).await; overwrite_deleted_posts_and_comments(pool).await?;
delete_old_denied_users(pool).await; delete_old_denied_users(pool).await?;
Ok(())
} }
/// Update the hot_rank columns for the aggregates tables /// Update the hot_rank columns for the aggregates tables
/// Runs in batches until all necessary rows are updated once /// Runs in batches until all necessary rows are updated once
async fn update_hot_ranks(pool: &mut DbPool<'_>) { async fn update_hot_ranks(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Updating hot ranks for all history..."); info!("Updating hot ranks for all history...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn { process_post_aggregates_ranks_in_batches(&mut conn).await?;
Ok(mut conn) => {
process_post_aggregates_ranks_in_batches(&mut conn).await;
process_ranks_in_batches( process_ranks_in_batches(
&mut conn, &mut conn,
@ -138,7 +167,7 @@ async fn update_hot_ranks(pool: &mut DbPool<'_>) {
"a.hot_rank != 0", "a.hot_rank != 0",
"SET hot_rank = r.hot_rank(a.score, a.published)", "SET hot_rank = r.hot_rank(a.score, a.published)",
) )
.await; .await?;
process_ranks_in_batches( process_ranks_in_batches(
&mut conn, &mut conn,
@ -146,14 +175,10 @@ async fn update_hot_ranks(pool: &mut DbPool<'_>) {
"a.hot_rank != 0", "a.hot_rank != 0",
"SET hot_rank = r.hot_rank(a.subscribers, a.published)", "SET hot_rank = r.hot_rank(a.subscribers, a.published)",
) )
.await; .await?;
info!("Finished hot ranks update!"); info!("Finished hot ranks update!");
} Ok(())
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
#[derive(QueryableByName)] #[derive(QueryableByName)]
@ -171,7 +196,7 @@ async fn process_ranks_in_batches(
table_name: &str, table_name: &str,
where_clause: &str, where_clause: &str,
set_clause: &str, set_clause: &str,
) { ) -> LemmyResult<()> {
let process_start_time: DateTime<Utc> = Utc.timestamp_opt(0, 0).single().unwrap_or_default(); let process_start_time: DateTime<Utc> = Utc.timestamp_opt(0, 0).single().unwrap_or_default();
let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
@ -180,7 +205,7 @@ async fn process_ranks_in_batches(
while let Some(previous_batch_last_published) = previous_batch_result { while let Some(previous_batch_last_published) = previous_batch_result {
// Raw `sql_query` is used as a performance optimization - Diesel does not support doing this // Raw `sql_query` is used as a performance optimization - Diesel does not support doing this
// in a single query (neither as a CTE, nor using a subquery) // in a single query (neither as a CTE, nor using a subquery)
let result = sql_query(format!( let updated_rows = sql_query(format!(
r#"WITH batch AS (SELECT a.{id_column} r#"WITH batch AS (SELECT a.{id_column}
FROM {aggregates_table} a FROM {aggregates_table} a
WHERE a.published > $1 AND ({where_clause}) WHERE a.published > $1 AND ({where_clause})
@ -198,35 +223,31 @@ async fn process_ranks_in_batches(
.bind::<Timestamptz, _>(previous_batch_last_published) .bind::<Timestamptz, _>(previous_batch_last_published)
.bind::<Integer, _>(update_batch_size) .bind::<Integer, _>(update_batch_size)
.get_results::<HotRanksUpdateResult>(conn) .get_results::<HotRanksUpdateResult>(conn)
.await; .await
.map_err(|e| {
LemmyErrorType::Unknown(format!("Failed to update {} hot_ranks: {}", table_name, e))
})?;
match result {
Ok(updated_rows) => {
processed_rows_count += updated_rows.len(); processed_rows_count += updated_rows.len();
previous_batch_result = updated_rows.last().map(|row| row.published); previous_batch_result = updated_rows.last().map(|row| row.published);
} }
Err(e) => {
error!("Failed to update {} hot_ranks: {}", table_name, e);
break;
}
}
}
info!( info!(
"Finished process_hot_ranks_in_batches execution for {} (processed {} rows)", "Finished process_hot_ranks_in_batches execution for {} (processed {} rows)",
table_name, processed_rows_count table_name, processed_rows_count
); );
Ok(())
} }
/// Post aggregates is a special case, since it needs to join to the community_aggregates /// Post aggregates is a special case, since it needs to join to the community_aggregates
/// table, to get the active monthly user counts. /// table, to get the active monthly user counts.
async fn process_post_aggregates_ranks_in_batches(conn: &mut AsyncPgConnection) { async fn process_post_aggregates_ranks_in_batches(conn: &mut AsyncPgConnection) -> LemmyResult<()> {
let process_start_time: DateTime<Utc> = Utc.timestamp_opt(0, 0).single().unwrap_or_default(); let process_start_time: DateTime<Utc> = Utc.timestamp_opt(0, 0).single().unwrap_or_default();
let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans let update_batch_size = 1000; // Bigger batches than this tend to cause seq scans
let mut processed_rows_count = 0; let mut processed_rows_count = 0;
let mut previous_batch_result = Some(process_start_time); let mut previous_batch_result = Some(process_start_time);
while let Some(previous_batch_last_published) = previous_batch_result { while let Some(previous_batch_last_published) = previous_batch_result {
let result = sql_query( let updated_rows = sql_query(
r#"WITH batch AS (SELECT pa.post_id r#"WITH batch AS (SELECT pa.post_id
FROM post_aggregates pa FROM post_aggregates pa
WHERE pa.published > $1 WHERE pa.published > $1
@ -245,96 +266,66 @@ async fn process_post_aggregates_ranks_in_batches(conn: &mut AsyncPgConnection)
.bind::<Timestamptz, _>(previous_batch_last_published) .bind::<Timestamptz, _>(previous_batch_last_published)
.bind::<Integer, _>(update_batch_size) .bind::<Integer, _>(update_batch_size)
.get_results::<HotRanksUpdateResult>(conn) .get_results::<HotRanksUpdateResult>(conn)
.await; .await.map_err(|e| LemmyErrorType::Unknown(format!("Failed to update {} hot_ranks: {}", "post_aggregates", e)))?;
match result {
Ok(updated_rows) => {
processed_rows_count += updated_rows.len(); processed_rows_count += updated_rows.len();
previous_batch_result = updated_rows.last().map(|row| row.published); previous_batch_result = updated_rows.last().map(|row| row.published);
} }
Err(e) => {
error!("Failed to update {} hot_ranks: {}", "post_aggregates", e);
break;
}
}
}
info!( info!(
"Finished process_hot_ranks_in_batches execution for {} (processed {} rows)", "Finished process_hot_ranks_in_batches execution for {} (processed {} rows)",
"post_aggregates", processed_rows_count "post_aggregates", processed_rows_count
); );
Ok(())
} }
async fn delete_expired_captcha_answers(pool: &mut DbPool<'_>) { async fn delete_expired_captcha_answers(pool: &mut DbPool<'_>) -> LemmyResult<()> {
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
diesel::delete( diesel::delete(
captcha_answer::table captcha_answer::table.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))),
.filter(captcha_answer::published.lt(now() - IntervalDsl::minutes(10))),
) )
.execute(&mut conn) .execute(&mut conn)
.await .await
.map(|_| { .map(|_| {})?;
info!("Done."); info!("Done.");
})
.inspect_err(|e| error!("Failed to clear old captcha answers: {e}")) Ok(())
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Clear old activities (this table gets very large) /// Clear old activities (this table gets very large)
async fn clear_old_activities(pool: &mut DbPool<'_>) { async fn clear_old_activities(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Clearing old activities..."); info!("Clearing old activities...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
diesel::delete( diesel::delete(
sent_activity::table.filter(sent_activity::published.lt(now() - IntervalDsl::days(7))), sent_activity::table.filter(sent_activity::published.lt(now() - IntervalDsl::days(7))),
) )
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.inspect_err(|e| error!("Failed to clear old sent activities: {e}"))
.ok();
diesel::delete( diesel::delete(
received_activity::table received_activity::table.filter(received_activity::published.lt(now() - IntervalDsl::days(7))),
.filter(received_activity::published.lt(now() - IntervalDsl::days(7))),
) )
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.map(|_| info!("Done.")) info!("Done.");
.inspect_err(|e| error!("Failed to clear old received activities: {e}")) Ok(())
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
async fn delete_old_denied_users(pool: &mut DbPool<'_>) { async fn delete_old_denied_users(pool: &mut DbPool<'_>) -> LemmyResult<()> {
LocalUser::delete_old_denied_local_users(pool) LocalUser::delete_old_denied_local_users(pool)
.await .await
.map(|_| { .map(|_| {
info!("Done."); info!("Done.");
}) })?;
.inspect_err(|e| error!("Failed to deleted old denied users: {e}")) Ok(())
.ok();
} }
/// overwrite posts and comments 30d after deletion /// overwrite posts and comments 30d after deletion
async fn overwrite_deleted_posts_and_comments(pool: &mut DbPool<'_>) { async fn overwrite_deleted_posts_and_comments(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Overwriting deleted posts..."); info!("Overwriting deleted posts...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
diesel::update( diesel::update(
post::table post::table
.filter(post::deleted.eq(true)) .filter(post::deleted.eq(true))
@ -346,12 +337,7 @@ async fn overwrite_deleted_posts_and_comments(pool: &mut DbPool<'_>) {
post::name.eq(DELETED_REPLACEMENT_TEXT), post::name.eq(DELETED_REPLACEMENT_TEXT),
)) ))
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.map(|_| {
info!("Done.");
})
.inspect_err(|e| error!("Failed to overwrite deleted posts: {e}"))
.ok();
info!("Overwriting deleted comments..."); info!("Overwriting deleted comments...");
diesel::update( diesel::update(
@ -362,27 +348,17 @@ async fn overwrite_deleted_posts_and_comments(pool: &mut DbPool<'_>) {
) )
.set(comment::content.eq(DELETED_REPLACEMENT_TEXT)) .set(comment::content.eq(DELETED_REPLACEMENT_TEXT))
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.map(|_| {
info!("Done."); info!("Done.");
}) Ok(())
.inspect_err(|e| error!("Failed to overwrite deleted comments: {e}"))
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Re-calculate the site and community active counts every 12 hours /// Re-calculate the site and community active counts every 12 hours
async fn active_counts(pool: &mut DbPool<'_>) { async fn active_counts(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Updating active site and community aggregates ..."); info!("Updating active site and community aggregates ...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
let intervals = vec![ let intervals = vec![
("1 day", "day"), ("1 day", "day"),
("1 week", "week"), ("1 week", "week"),
@ -395,35 +371,21 @@ async fn active_counts(pool: &mut DbPool<'_>) {
"update site_aggregates set users_active_{} = (select * from r.site_aggregates_activity('{}')) where site_id = 1", "update site_aggregates set users_active_{} = (select * from r.site_aggregates_activity('{}')) where site_id = 1",
abbr, full_form abbr, full_form
); );
sql_query(update_site_stmt) sql_query(update_site_stmt).execute(&mut conn).await?;
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to update site stats: {e}"))
.ok();
let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from r.community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", abbr, full_form); let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from r.community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", abbr, full_form);
sql_query(update_community_stmt) sql_query(update_community_stmt).execute(&mut conn).await?;
.execute(&mut conn)
.await
.inspect_err(|e| error!("Failed to update community stats: {e}"))
.ok();
} }
info!("Done."); info!("Done.");
} Ok(())
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Set banned to false after ban expires /// Set banned to false after ban expires
async fn update_banned_when_expired(pool: &mut DbPool<'_>) { async fn update_banned_when_expired(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Updating banned column if it expires ..."); info!("Updating banned column if it expires ...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
diesel::update( diesel::update(
person::table person::table
.filter(person::banned.eq(true)) .filter(person::banned.eq(true))
@ -431,52 +393,34 @@ async fn update_banned_when_expired(pool: &mut DbPool<'_>) {
) )
.set(person::banned.eq(false)) .set(person::banned.eq(false))
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.inspect_err(|e| error!("Failed to update person.banned when expires: {e}"))
.ok();
diesel::delete( diesel::delete(
community_actions::table.filter(community_actions::ban_expires.lt(now().nullable())), community_actions::table.filter(community_actions::ban_expires.lt(now().nullable())),
) )
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.inspect_err(|e| error!("Failed to remove community_ban expired rows: {e}")) Ok(())
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Set banned to false after ban expires /// Set banned to false after ban expires
async fn delete_instance_block_when_expired(pool: &mut DbPool<'_>) { async fn delete_instance_block_when_expired(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Delete instance blocks when expired ..."); info!("Delete instance blocks when expired ...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
diesel::delete( diesel::delete(
federation_blocklist::table.filter(federation_blocklist::expires.lt(now().nullable())), federation_blocklist::table.filter(federation_blocklist::expires.lt(now().nullable())),
) )
.execute(&mut conn) .execute(&mut conn)
.await .await?;
.inspect_err(|e| error!("Failed to remove federation_blocklist expired rows: {e}")) Ok(())
.ok();
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Find all unpublished posts with scheduled date in the future, and publish them. /// Find all unpublished posts with scheduled date in the future, and publish them.
async fn publish_scheduled_posts(context: &Data<LemmyContext>) { async fn publish_scheduled_posts(context: &Data<LemmyContext>) -> LemmyResult<()> {
let pool = &mut context.pool(); let pool = &mut context.pool();
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
let scheduled_posts: Vec<_> = post::table let scheduled_posts: Vec<_> = post::table
.inner_join(community::table) .inner_join(community::table)
.inner_join(person::table) .inner_join(person::table)
@ -494,10 +438,7 @@ async fn publish_scheduled_posts(context: &Data<LemmyContext>) {
)))) ))))
.select((post::all_columns, community::all_columns)) .select((post::all_columns, community::all_columns))
.get_results::<(Post, Community)>(&mut conn) .get_results::<(Post, Community)>(&mut conn)
.await .await?;
.inspect_err(|e| error!("Failed to read unpublished posts: {e}"))
.ok()
.unwrap_or_default();
for (post, community) in scheduled_posts { for (post, community) in scheduled_posts {
// mark post as published in db // mark post as published in db
@ -505,23 +446,14 @@ async fn publish_scheduled_posts(context: &Data<LemmyContext>) {
scheduled_publish_time: Some(None), scheduled_publish_time: Some(None),
..Default::default() ..Default::default()
}; };
Post::update(&mut context.pool(), post.id, &form) Post::update(&mut context.pool(), post.id, &form).await?;
.await
.inspect_err(|e| error!("Failed update scheduled post: {e}"))
.ok();
// send out post via federation and webmention // send out post via federation and webmention
let send_activity = SendActivityData::CreatePost(post.clone()); let send_activity = SendActivityData::CreatePost(post.clone());
ActivityChannel::submit_activity(send_activity, context) ActivityChannel::submit_activity(send_activity, context)?;
.inspect_err(|e| error!("Failed federate scheduled post: {e}"))
.ok();
send_webmention(post, community); send_webmention(post, community);
} }
} Ok(())
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
} }
/// Updates the instance software and version. /// Updates the instance software and version.
@ -535,10 +467,8 @@ async fn update_instance_software(
client: &ClientWithMiddleware, client: &ClientWithMiddleware,
) -> LemmyResult<()> { ) -> LemmyResult<()> {
info!("Updating instances software and versions..."); info!("Updating instances software and versions...");
let conn = get_conn(pool).await; let mut conn = get_conn(pool).await?;
match conn {
Ok(mut conn) => {
let instances = instance::table.get_results::<Instance>(&mut conn).await?; let instances = instance::table.get_results::<Instance>(&mut conn).await?;
for instance in instances { for instance in instances {
@ -547,11 +477,6 @@ async fn update_instance_software(
} }
} }
info!("Finished updating instances software and versions..."); info!("Finished updating instances software and versions...");
}
Err(e) => {
error!("Failed to get connection from pool: {e}");
}
}
Ok(()) Ok(())
} }
@ -623,7 +548,8 @@ async fn build_update_instance_form(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::scheduled_tasks::build_update_instance_form; use super::*;
use crate::{scheduled_tasks::build_update_instance_form, tests::test_context};
use lemmy_api_common::request::client_builder; use lemmy_api_common::request::client_builder;
use lemmy_utils::{ use lemmy_utils::{
error::{LemmyErrorType, LemmyResult}, error::{LemmyErrorType, LemmyResult},
@ -654,4 +580,16 @@ mod tests {
assert_eq!(form.software.ok_or(LemmyErrorType::NotFound)?, "mastodon"); assert_eq!(form.software.ok_or(LemmyErrorType::NotFound)?, "mastodon");
Ok(()) Ok(())
} }
#[tokio::test]
#[serial]
async fn test_scheduled_tasks() -> LemmyResult<()> {
let context = test_context().await;
startup_jobs(&mut context.pool()).await?;
update_instance_software(&mut context.pool(), context.client()).await?;
delete_expired_captcha_answers(&mut context.pool()).await?;
publish_scheduled_posts(&context).await?;
Ok(())
}
} }

View file

@ -99,7 +99,7 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use crate::tests::test_context;
use actix_web::test::TestRequest; use actix_web::test::TestRequest;
use lemmy_api_common::claims::Claims; use lemmy_api_common::claims::Claims;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -107,45 +107,29 @@ mod tests {
instance::Instance, instance::Instance,
local_user::{LocalUser, LocalUserInsertForm}, local_user::{LocalUser, LocalUserInsertForm},
person::{Person, PersonInsertForm}, person::{Person, PersonInsertForm},
secret::Secret,
}, },
traits::Crud, traits::Crud,
utils::build_db_pool_for_tests,
}; };
use lemmy_utils::{error::LemmyResult, rate_limit::RateLimitCell}; use lemmy_utils::error::LemmyResult;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use reqwest::Client;
use reqwest_middleware::ClientBuilder;
use serial_test::serial; use serial_test::serial;
use std::env::set_current_dir;
#[tokio::test] #[tokio::test]
#[serial] #[serial]
async fn test_session_auth() -> LemmyResult<()> { async fn test_session_auth() -> LemmyResult<()> {
// hack, necessary so that config file can be loaded from hardcoded, relative path let context = test_context().await;
set_current_dir("crates/utils")?;
let pool_ = build_db_pool_for_tests(); let inserted_instance =
let pool = &mut (&pool_).into(); Instance::read_or_create(&mut context.pool(), "my_domain.tld".to_string()).await?;
let secret = Secret::init(pool).await?;
let context = LemmyContext::create(
pool_.clone(),
ClientBuilder::new(Client::default()).build(),
secret,
RateLimitCell::with_test_config(),
);
let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?;
let new_person = PersonInsertForm::test_form(inserted_instance.id, "Gerry9812"); let new_person = PersonInsertForm::test_form(inserted_instance.id, "Gerry9812");
let inserted_person = Person::create(pool, &new_person).await?; let inserted_person = Person::create(&mut context.pool(), &new_person).await?;
let local_user_form = LocalUserInsertForm::test_form(inserted_person.id); let local_user_form = LocalUserInsertForm::test_form(inserted_person.id);
let inserted_local_user = LocalUser::create(pool, &local_user_form, vec![]).await?; let inserted_local_user =
LocalUser::create(&mut context.pool(), &local_user_form, vec![]).await?;
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let jwt = Claims::generate(inserted_local_user.id, req, &context).await?; let jwt = Claims::generate(inserted_local_user.id, req, &context).await?;
@ -153,7 +137,7 @@ mod tests {
let valid = Claims::validate(&jwt, &context).await; let valid = Claims::validate(&jwt, &context).await;
assert!(valid.is_ok()); assert!(valid.is_ok());
let num_deleted = Person::delete(pool, inserted_person.id).await?; let num_deleted = Person::delete(&mut context.pool(), inserted_person.id).await?;
assert_eq!(1, num_deleted); assert_eq!(1, num_deleted);
Ok(()) Ok(())