Skip to content

Commit

Permalink
Replace clippy::unwrap_used in tests (#5064)
Browse files Browse the repository at this point in the history
* Add LemmyResult to session_middleware tests

* Add LemmyResult to inboxes tests

* Add LemmyResult to slurs tests

* Add LemmyResult to markdown tests

* Add LemmyResult to rate_limiter tests

* Add LemmyResult to error tests

* Add LemmyResult to api_common utils tests

* Add LemmyResult to request tests

* Add LemmyResult to claims tests

* Propagate registration_applications errors

* Remove clippy::unwrap_used from community tests

* Add LemmyResult to community_view tests

* Add LemmyResult to db_schema post tests

* Add LemmyResult to site_aggregates tests

* Add LemmyResult to private_message tests

* Add LemmyResult to activity tests

* Add LemmyResult to federation_allowlist tests

* Add LemmyResult to comment_aggregates tests

* Add LemmyResult to post_report tests

* Add LemmyResult to moderator tests

* Add LemmyResult to community_aggregates tests

* Add LemmyResult to person_aggregates tests

* Add LemmyResult to language tests

* Add LemmyResult to post_aggregates tests

* Add LemmyResult to db_schema comment tests

* Add LemmyResult to actor_language tests

* Add LemmyResult to vote_view tests

* Add LemmyResult to registration_application_view tests

* Add LemmyResult to private_message_view tests

* Add LemmyResult to private_message_report_view tests

* Add LemmyResult to post_report_view tests

* Add LemmyResult to comment_report_view tests

* Add LemmyResult to sitemap tests

* Replace .expect() with .unwrap()

* Format code

* Remove clippy::unwrap_used from activity tests

* Add diesel result in db_schema tests

* Format code

* Map to_bytes() error to LemmyErrorType

* Remove clippy::unwrap_used from error tests

* Removing a few more unwraps, and cleaning up language code.

* Replace map_err with unwrap_or_default

* Replace ok_or with and_then

---------

Co-authored-by: Dessalines <[email protected]>
  • Loading branch information
netbrum and dessalines authored Oct 2, 2024
1 parent ffb94fd commit 483bdd5
Show file tree
Hide file tree
Showing 42 changed files with 883 additions and 1,221 deletions.
18 changes: 6 additions & 12 deletions crates/api/src/site/registration_applications/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,10 @@ use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::{error::LemmyResult, LemmyErrorType, CACHE_DURATION_API};
use serial_test::serial;

#[expect(clippy::unwrap_used)]
async fn create_test_site(context: &Data<LemmyContext>) -> LemmyResult<(Instance, LocalUserView)> {
let pool = &mut context.pool();

let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
.await
.expect("Create test instance");
let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?;

let admin_person = Person::create(
pool,
Expand All @@ -57,7 +54,7 @@ async fn create_test_site(context: &Data<LemmyContext>) -> LemmyResult<(Instance
let admin_local_user_view = LocalUserView::read_person(pool, admin_person.id).await?;

let site_form = SiteInsertForm::new("test site".to_string(), inserted_instance.id);
let site = Site::create(pool, &site_form).await.unwrap();
let site = Site::create(pool, &site_form).await?;

// Create a local site, since this is necessary for determining if email verification is
// required
Expand All @@ -68,14 +65,12 @@ async fn create_test_site(context: &Data<LemmyContext>) -> LemmyResult<(Instance
site_setup: Some(true),
..LocalSiteInsertForm::new(site.id)
};
let local_site = LocalSite::create(pool, &local_site_form).await.unwrap();
let local_site = LocalSite::create(pool, &local_site_form).await?;

// Required to have a working local SiteView when updating the site to change email verification
// requirement or registration mode
let rate_limit_form = LocalSiteRateLimitInsertForm::new(local_site.id);
LocalSiteRateLimit::create(pool, &rate_limit_form)
.await
.unwrap();
LocalSiteRateLimit::create(pool, &rate_limit_form).await?;

Ok((inserted_instance, admin_local_user_view))
}
Expand Down Expand Up @@ -109,7 +104,6 @@ async fn signup(
Ok((local_user, application))
}

#[expect(clippy::unwrap_used)]
async fn get_application_statuses(
context: &Data<LemmyContext>,
admin: LocalUserView,
Expand All @@ -122,14 +116,14 @@ async fn get_application_statuses(
get_unread_registration_application_count(context.reset_request_count(), admin.clone()).await?;

let unread_applications = list_registration_applications(
Query::from_query("unread_only=true").unwrap(),
Query::from_query("unread_only=true")?,
context.reset_request_count(),
admin.clone(),
)
.await?;

let all_applications = list_registration_applications(
Query::from_query("unread_only=false").unwrap(),
Query::from_query("unread_only=false")?,
context.reset_request_count(),
admin,
)
Expand Down
62 changes: 28 additions & 34 deletions crates/api/src/sitemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,44 +42,40 @@ pub async fn get_sitemap(context: Data<LemmyContext>) -> LemmyResult<HttpRespons
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
pub(crate) mod tests {

use crate::sitemap::generate_urlset;
use chrono::{DateTime, NaiveDate, Utc};
use elementtree::Element;
use lemmy_db_schema::newtypes::DbUrl;
use lemmy_utils::error::LemmyResult;
use pretty_assertions::assert_eq;
use url::Url;

#[tokio::test]
async fn test_generate_urlset() {
async fn test_generate_urlset() -> LemmyResult<()> {
let posts: Vec<(DbUrl, DateTime<Utc>)> = vec![
(
Url::parse("https://example.com").unwrap().into(),
Url::parse("https://example.com")?.into(),
NaiveDate::from_ymd_opt(2022, 12, 1)
.unwrap()
.unwrap_or_default()
.and_hms_opt(9, 10, 11)
.unwrap()
.unwrap_or_default()
.and_utc(),
),
(
Url::parse("https://lemmy.ml").unwrap().into(),
Url::parse("https://lemmy.ml")?.into(),
NaiveDate::from_ymd_opt(2023, 1, 1)
.unwrap()
.unwrap_or_default()
.and_hms_opt(1, 2, 3)
.unwrap()
.unwrap_or_default()
.and_utc(),
),
];

let mut buf = Vec::<u8>::new();
generate_urlset(posts)
.await
.unwrap()
.write(&mut buf)
.unwrap();
let root = Element::from_reader(buf.as_slice()).unwrap();
generate_urlset(posts).await?.write(&mut buf)?;
let root = Element::from_reader(buf.as_slice())?;

assert_eq!(root.tag().name(), "urlset");
assert_eq!(root.child_count(), 2);
Expand All @@ -99,45 +95,43 @@ pub(crate) mod tests {
root
.children()
.next()
.unwrap()
.children()
.find(|element| element.tag().name() == "loc")
.unwrap()
.text(),
.and_then(|n| n.children().find(|element| element.tag().name() == "loc"))
.map(Element::text)
.unwrap_or_default(),
"https://example.com/"
);
assert_eq!(
root
.children()
.next()
.unwrap()
.children()
.find(|element| element.tag().name() == "lastmod")
.unwrap()
.text(),
.and_then(|n| n
.children()
.find(|element| element.tag().name() == "lastmod"))
.map(Element::text)
.unwrap_or_default(),
"2022-12-01T09:10:11+00:00"
);
assert_eq!(
root
.children()
.nth(1)
.unwrap()
.children()
.find(|element| element.tag().name() == "loc")
.unwrap()
.text(),
.and_then(|n| n.children().find(|element| element.tag().name() == "loc"))
.map(Element::text)
.unwrap_or_default(),
"https://lemmy.ml/"
);
assert_eq!(
root
.children()
.nth(1)
.unwrap()
.children()
.find(|element| element.tag().name() == "lastmod")
.unwrap()
.text(),
.and_then(|n| n
.children()
.find(|element| element.tag().name() == "lastmod"))
.map(Element::text)
.unwrap_or_default(),
"2023-01-01T01:02:03+00:00"
);

Ok(())
}
}
25 changes: 10 additions & 15 deletions crates/api_common/src/claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ impl Claims {
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {

use crate::{claims::Claims, context::LemmyContext};
Expand All @@ -84,48 +83,44 @@ mod tests {
traits::Crud,
utils::build_db_pool_for_tests,
};
use lemmy_utils::rate_limit::RateLimitCell;
use lemmy_utils::{error::LemmyResult, rate_limit::RateLimitCell};
use pretty_assertions::assert_eq;
use reqwest::Client;
use reqwest_middleware::ClientBuilder;
use serial_test::serial;

#[tokio::test]
#[serial]
async fn test_should_not_validate_user_token_after_password_change() {
async fn test_should_not_validate_user_token_after_password_change() -> LemmyResult<()> {
let pool_ = build_db_pool_for_tests().await;
let pool = &mut (&pool_).into();
let secret = Secret::init(pool).await.unwrap().unwrap();
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
.unwrap();
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 inserted_person = Person::create(pool, &new_person).await.unwrap();
let inserted_person = Person::create(pool, &new_person).await?;

let local_user_form = LocalUserInsertForm::test_form(inserted_person.id);

let inserted_local_user = LocalUser::create(pool, &local_user_form, vec![])
.await
.unwrap();
let inserted_local_user = LocalUser::create(pool, &local_user_form, vec![]).await?;

let req = TestRequest::default().to_http_request();
let jwt = Claims::generate(inserted_local_user.id, req, &context)
.await
.unwrap();
let jwt = Claims::generate(inserted_local_user.id, req, &context).await?;

let valid = Claims::validate(&jwt, &context).await;
assert!(valid.is_ok());

let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap();
let num_deleted = Person::delete(pool, inserted_person.id).await?;
assert_eq!(1, num_deleted);

Ok(())
}
}
31 changes: 15 additions & 16 deletions crates/api_common/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,24 +471,24 @@ pub async fn replace_image(
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {

use crate::{
context::LemmyContext,
request::{extract_opengraph_data, fetch_link_metadata},
};
use lemmy_utils::error::LemmyResult;
use pretty_assertions::assert_eq;
use serial_test::serial;
use url::Url;

// These helped with testing
#[tokio::test]
#[serial]
async fn test_link_metadata() {
async fn test_link_metadata() -> LemmyResult<()> {
let context = LemmyContext::init_test_context().await;
let sample_url = Url::parse("https://gitlab.com/IzzyOnDroid/repo/-/wikis/FAQ").unwrap();
let sample_res = fetch_link_metadata(&sample_url, &context).await.unwrap();
let sample_url = Url::parse("https://gitlab.com/IzzyOnDroid/repo/-/wikis/FAQ")?;
let sample_res = fetch_link_metadata(&sample_url, &context).await?;
assert_eq!(
Some("FAQ · Wiki · IzzyOnDroid / repo · GitLab".to_string()),
sample_res.opengraph_data.title
Expand All @@ -499,8 +499,7 @@ mod tests {
);
assert_eq!(
Some(
Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
.unwrap()
Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")?
.into()
),
sample_res.opengraph_data.image
Expand All @@ -510,47 +509,47 @@ mod tests {
Some(mime::TEXT_HTML_UTF_8.to_string()),
sample_res.content_type
);

Ok(())
}

#[test]
fn test_resolve_image_url() {
fn test_resolve_image_url() -> LemmyResult<()> {
// url that lists the opengraph fields
let url = Url::parse("https://example.com/one/two.html").unwrap();
let url = Url::parse("https://example.com/one/two.html")?;

// root relative url
let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='/image.jpg'></head><body></body></html>";
let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
assert_eq!(
metadata.image,
Some(Url::parse("https://example.com/image.jpg").unwrap().into())
Some(Url::parse("https://example.com/image.jpg")?.into())
);

// base relative url
let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='image.jpg'></head><body></body></html>";
let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
assert_eq!(
metadata.image,
Some(
Url::parse("https://example.com/one/image.jpg")
.unwrap()
.into()
)
Some(Url::parse("https://example.com/one/image.jpg")?.into())
);

// absolute url
let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='https://cdn.host.com/image.jpg'></head><body></body></html>";
let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
assert_eq!(
metadata.image,
Some(Url::parse("https://cdn.host.com/image.jpg").unwrap().into())
Some(Url::parse("https://cdn.host.com/image.jpg")?.into())
);

// protocol relative url
let html_bytes = b"<!DOCTYPE html><html><head><meta property='og:image' content='//example.com/image.jpg'></head><body></body></html>";
let metadata = extract_opengraph_data(html_bytes, &url).expect("Unable to parse metadata");
assert_eq!(
metadata.image,
Some(Url::parse("https://example.com/image.jpg").unwrap().into())
Some(Url::parse("https://example.com/image.jpg")?.into())
);

Ok(())
}
}
14 changes: 5 additions & 9 deletions crates/api_crud/src/comment/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,9 @@ pub async fn create_comment(
check_comment_depth(parent)?;
}

CommunityLanguage::is_allowed_community_language(
&mut context.pool(),
data.language_id,
community_id,
)
.await?;

// attempt to set default language if none was provided
let language_id = match data.language_id {
Some(lid) => Some(lid),
Some(lid) => lid,
None => {
default_post_language(
&mut context.pool(),
Expand All @@ -108,8 +101,11 @@ pub async fn create_comment(
}
};

CommunityLanguage::is_allowed_community_language(&mut context.pool(), language_id, community_id)
.await?;

let comment_form = CommentInsertForm {
language_id,
language_id: Some(language_id),
..CommentInsertForm::new(local_user_view.person.id, data.post_id, content.clone())
};

Expand Down
Loading

0 comments on commit 483bdd5

Please sign in to comment.