1
0

Tests 3 restructure (#754)

* moved files

* moved files

* initial v3 additions

* moves req data

* tests passing, restructuring, remove v2

* fmt; clippy; prepare

* merge conflicts + issues

* merge conflict, fmt, clippy, prepare

* revs

* fixed failing test

* fixed tests
This commit is contained in:
Wyatt Verchere
2023-11-16 10:36:03 -08:00
committed by GitHub
parent f4880d0519
commit 74973e73e6
66 changed files with 4282 additions and 1033 deletions

View File

@@ -6,7 +6,12 @@ use std::rc::Rc;
pub mod oauth;
pub mod oauth_clients;
pub mod organization;
pub mod project;
pub mod request_data;
pub mod tags;
pub mod team;
pub mod version;
#[derive(Clone)]
pub struct ApiV3 {
@@ -17,4 +22,15 @@ impl ApiV3 {
pub async fn call(&self, req: actix_http::Request) -> ServiceResponse {
self.test_app.call(req).await.unwrap()
}
pub async fn reset_search_index(&self) -> ServiceResponse {
let req = actix_web::test::TestRequest::post()
.uri("/v3/admin/_force_reindex")
.append_header((
"Modrinth-Admin",
dotenvy::var("LABRINTH_ADMIN_KEY").unwrap(),
))
.to_request();
self.call(req).await
}
}

View File

@@ -55,7 +55,7 @@ impl ApiV3 {
pub async fn oauth_accept(&self, flow: &str, pat: &str) -> ServiceResponse {
self.call(
TestRequest::post()
.uri("/v3/auth/oauth/accept")
.uri("/v3/oauth/accept")
.append_header((AUTHORIZATION, pat))
.set_json(RespondToOAuthClientScopes {
flow: flow.to_string(),
@@ -68,7 +68,7 @@ impl ApiV3 {
pub async fn oauth_reject(&self, flow: &str, pat: &str) -> ServiceResponse {
self.call(
TestRequest::post()
.uri("/v3/auth/oauth/reject")
.uri("/v3/oauth/reject")
.append_header((AUTHORIZATION, pat))
.set_json(RespondToOAuthClientScopes {
flow: flow.to_string(),
@@ -87,7 +87,7 @@ impl ApiV3 {
) -> ServiceResponse {
self.call(
TestRequest::post()
.uri("/v3/auth/oauth/token")
.uri("/v3/oauth/token")
.append_header((AUTHORIZATION, client_secret))
.set_form(TokenRequest {
grant_type: "authorization_code".to_string(),
@@ -108,7 +108,7 @@ pub fn generate_authorize_uri(
state: Option<&str>,
) -> String {
format!(
"/v3/auth/oauth/authorize?client_id={}{}{}{}",
"/v3/oauth/authorize?client_id={}{}{}{}",
urlencoding::encode(client_id),
optional_query_param("redirect_uri", redirect_uri),
optional_query_param("scope", scope),

View File

@@ -0,0 +1,150 @@
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use bytes::Bytes;
use labrinth::models::{organizations::Organization, v3::projects::Project};
use serde_json::json;
use super::{request_data::ImageData, ApiV3};
impl ApiV3 {
pub async fn create_organization(
&self,
organization_title: &str,
description: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri("/v3/organization")
.append_header(("Authorization", pat))
.set_json(json!({
"title": organization_title,
"description": description,
}))
.to_request();
self.call(req).await
}
pub async fn get_organization(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/organization/{id_or_title}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_organization_deserialized(
&self,
id_or_title: &str,
pat: &str,
) -> Organization {
let resp = self.get_organization(id_or_title, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_organization_projects(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/organization/{id_or_title}/projects"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_organization_projects_deserialized(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<Project> {
let resp = self.get_organization_projects(id_or_title, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn edit_organization(
&self,
id_or_title: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/organization/{id_or_title}"))
.append_header(("Authorization", pat))
.set_json(patch)
.to_request();
self.call(req).await
}
pub async fn edit_organization_icon(
&self,
id_or_title: &str,
icon: Option<ImageData>,
pat: &str,
) -> ServiceResponse {
if let Some(icon) = icon {
// If an icon is provided, upload it
let req = test::TestRequest::patch()
.uri(&format!(
"/v3/organization/{id_or_title}/icon?ext={ext}",
ext = icon.extension
))
.append_header(("Authorization", pat))
.set_payload(Bytes::from(icon.icon))
.to_request();
self.call(req).await
} else {
// If no icon is provided, delete the icon
let req = test::TestRequest::delete()
.uri(&format!("/v3/organization/{id_or_title}/icon"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
}
pub async fn delete_organization(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/organization/{id_or_title}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn organization_add_project(
&self,
id_or_title: &str,
project_id_or_slug: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/organization/{id_or_title}/projects"))
.append_header(("Authorization", pat))
.set_json(json!({
"project_id": project_id_or_slug,
}))
.to_request();
self.call(req).await
}
pub async fn organization_remove_project(
&self,
id_or_title: &str,
project_id_or_slug: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!(
"/v3/organization/{id_or_title}/projects/{project_id_or_slug}"
))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
}

View File

@@ -0,0 +1,256 @@
use std::collections::HashMap;
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use bytes::Bytes;
use chrono::{DateTime, Utc};
use labrinth::{
models::v3::projects::{Project, Version},
search::SearchResults,
util::actix::AppendsMultipart,
};
use rust_decimal::Decimal;
use serde_json::json;
use crate::common::{asserts::assert_status, database::MOD_USER_PAT};
use super::{
request_data::{ImageData, ProjectCreationRequestData},
ApiV3,
};
impl ApiV3 {
pub async fn add_public_project(
&self,
creation_data: ProjectCreationRequestData,
pat: &str,
) -> (Project, Vec<Version>) {
// Add a project.
let req = TestRequest::post()
.uri("/v3/project")
.append_header(("Authorization", pat))
.set_multipart(creation_data.segment_data)
.to_request();
let resp = self.call(req).await;
assert_status(&resp, StatusCode::OK);
// Approve as a moderator.
let req = TestRequest::patch()
.uri(&format!("/v3/project/{}", creation_data.slug))
.append_header(("Authorization", MOD_USER_PAT))
.set_json(json!(
{
"status": "approved"
}
))
.to_request();
let resp = self.call(req).await;
assert_status(&resp, StatusCode::NO_CONTENT);
let project = self
.get_project_deserialized(&creation_data.slug, pat)
.await;
// Get project's versions
let req = TestRequest::get()
.uri(&format!("/v3/project/{}/version", creation_data.slug))
.append_header(("Authorization", pat))
.to_request();
let resp = self.call(req).await;
let versions: Vec<Version> = test::read_body_json(resp).await;
(project, versions)
}
pub async fn remove_project(&self, project_slug_or_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/project/{project_slug_or_id}"))
.append_header(("Authorization", pat))
.to_request();
let resp = self.call(req).await;
assert_eq!(resp.status(), 204);
resp
}
pub async fn get_project(&self, id_or_slug: &str, pat: &str) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/project/{id_or_slug}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_project_deserialized(&self, id_or_slug: &str, pat: &str) -> Project {
let resp = self.get_project(id_or_slug, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_user_projects(&self, user_id_or_username: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/user/{}/projects", user_id_or_username))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_user_projects_deserialized(
&self,
user_id_or_username: &str,
pat: &str,
) -> Vec<Project> {
let resp = self.get_user_projects(user_id_or_username, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn edit_project(
&self,
id_or_slug: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/project/{id_or_slug}"))
.append_header(("Authorization", pat))
.set_json(patch)
.to_request();
self.call(req).await
}
pub async fn edit_project_bulk(
&self,
ids_or_slugs: impl IntoIterator<Item = &str>,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let projects_str = ids_or_slugs
.into_iter()
.map(|s| format!("\"{}\"", s))
.collect::<Vec<_>>()
.join(",");
let req = test::TestRequest::patch()
.uri(&format!(
"/v3/projects?ids={encoded}",
encoded = urlencoding::encode(&format!("[{projects_str}]"))
))
.append_header(("Authorization", pat))
.set_json(patch)
.to_request();
self.call(req).await
}
pub async fn edit_project_icon(
&self,
id_or_slug: &str,
icon: Option<ImageData>,
pat: &str,
) -> ServiceResponse {
if let Some(icon) = icon {
// If an icon is provided, upload it
let req = test::TestRequest::patch()
.uri(&format!(
"/v3/project/{id_or_slug}/icon?ext={ext}",
ext = icon.extension
))
.append_header(("Authorization", pat))
.set_payload(Bytes::from(icon.icon))
.to_request();
self.call(req).await
} else {
// If no icon is provided, delete the icon
let req = test::TestRequest::delete()
.uri(&format!("/v3/project/{id_or_slug}/icon"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
}
pub async fn search_deserialized(
&self,
query: Option<&str>,
facets: Option<serde_json::Value>,
pat: &str,
) -> SearchResults {
let query_field = if let Some(query) = query {
format!("&query={}", urlencoding::encode(query))
} else {
"".to_string()
};
let facets_field = if let Some(facets) = facets {
format!("&facets={}", urlencoding::encode(&facets.to_string()))
} else {
"".to_string()
};
let req = test::TestRequest::get()
.uri(&format!("/v3/search?{}{}", query_field, facets_field))
.append_header(("Authorization", pat))
.to_request();
let resp = self.call(req).await;
let status = resp.status();
assert_eq!(status, 200);
test::read_body_json(resp).await
}
pub async fn get_analytics_revenue(
&self,
id_or_slugs: Vec<&str>,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
resolution_minutes: Option<u32>,
pat: &str,
) -> ServiceResponse {
let projects_string = serde_json::to_string(&id_or_slugs).unwrap();
let projects_string = urlencoding::encode(&projects_string);
let mut extra_args = String::new();
if let Some(start_date) = start_date {
let start_date = start_date.to_rfc3339();
// let start_date = serde_json::to_string(&start_date).unwrap();
let start_date = urlencoding::encode(&start_date);
extra_args.push_str(&format!("&start_date={start_date}"));
}
if let Some(end_date) = end_date {
let end_date = end_date.to_rfc3339();
// let end_date = serde_json::to_string(&end_date).unwrap();
let end_date = urlencoding::encode(&end_date);
extra_args.push_str(&format!("&end_date={end_date}"));
}
if let Some(resolution_minutes) = resolution_minutes {
extra_args.push_str(&format!("&resolution_minutes={}", resolution_minutes));
}
let req = test::TestRequest::get()
.uri(&format!(
"/v3/analytics/revenue?{projects_string}{extra_args}",
))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_analytics_revenue_deserialized(
&self,
id_or_slugs: Vec<&str>,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
resolution_minutes: Option<u32>,
pat: &str,
) -> HashMap<String, HashMap<i64, Decimal>> {
let resp = self
.get_analytics_revenue(id_or_slugs, start_date, end_date, resolution_minutes, pat)
.await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
}

View File

@@ -0,0 +1,146 @@
#![allow(dead_code)]
use serde_json::json;
use crate::common::dummy_data::{DummyImage, TestFile};
use labrinth::{
models::projects::ProjectId,
util::actix::{MultipartSegment, MultipartSegmentData},
};
pub struct ProjectCreationRequestData {
pub slug: String,
pub jar: Option<TestFile>,
pub segment_data: Vec<MultipartSegment>,
}
pub struct VersionCreationRequestData {
pub version: String,
pub jar: Option<TestFile>,
pub segment_data: Vec<MultipartSegment>,
}
pub struct ImageData {
pub filename: String,
pub extension: String,
pub icon: Vec<u8>,
}
pub fn get_public_project_creation_data(
slug: &str,
version_jar: Option<TestFile>,
) -> ProjectCreationRequestData {
let json_data = get_public_project_creation_data_json(slug, version_jar.as_ref());
let multipart_data = get_public_creation_data_multipart(&json_data, version_jar.as_ref());
ProjectCreationRequestData {
slug: slug.to_string(),
jar: version_jar,
segment_data: multipart_data,
}
}
pub fn get_public_version_creation_data(
project_id: ProjectId,
version_number: &str,
version_jar: TestFile,
// closure that takes in a &mut serde_json::Value
// and modifies it before it is serialized and sent
modify_json: Option<impl FnOnce(&mut serde_json::Value)>,
) -> VersionCreationRequestData {
let mut json_data = get_public_version_creation_data_json(version_number, &version_jar);
json_data["project_id"] = json!(project_id);
if let Some(modify_json) = modify_json {
modify_json(&mut json_data);
}
let multipart_data = get_public_creation_data_multipart(&json_data, Some(&version_jar));
VersionCreationRequestData {
version: version_number.to_string(),
jar: Some(version_jar),
segment_data: multipart_data,
}
}
pub fn get_public_version_creation_data_json(
version_number: &str,
version_jar: &TestFile,
) -> serde_json::Value {
let is_modpack = version_jar.project_type() == "modpack";
let mut j = json!({
"file_parts": [version_jar.filename()],
"version_number": version_number,
"version_title": "start",
"dependencies": [],
"release_channel": "release",
"loaders": [if is_modpack { "mrpack" } else { "fabric" }],
"featured": true,
// Loader fields
"game_versions": ["1.20.1"],
"client_side": "required",
"server_side": "optional"
});
if is_modpack {
j["mrpack_loaders"] = json!(["fabric"]);
}
j
}
pub fn get_public_project_creation_data_json(
slug: &str,
version_jar: Option<&TestFile>,
) -> serde_json::Value {
let initial_versions = if let Some(jar) = version_jar {
json!([get_public_version_creation_data_json("1.2.3", jar)])
} else {
json!([])
};
let is_draft = version_jar.is_none();
json!(
{
"title": format!("Test Project {slug}"),
"slug": slug,
"description": "A dummy project for testing with.",
"body": "This project is approved, and versions are listed.",
"initial_versions": initial_versions,
"is_draft": is_draft,
"categories": [],
"license_id": "MIT",
}
)
}
pub fn get_public_creation_data_multipart(
json_data: &serde_json::Value,
version_jar: Option<&TestFile>,
) -> Vec<MultipartSegment> {
// Basic json
let json_segment = MultipartSegment {
name: "data".to_string(),
filename: None,
content_type: Some("application/json".to_string()),
data: MultipartSegmentData::Text(serde_json::to_string(json_data).unwrap()),
};
if let Some(jar) = version_jar {
// Basic file
let file_segment = MultipartSegment {
name: jar.filename(),
filename: Some(jar.filename()),
content_type: Some("application/java-archive".to_string()),
data: MultipartSegmentData::Binary(jar.bytes()),
};
vec![json_segment, file_segment]
} else {
vec![json_segment]
}
}
pub fn get_icon_data(dummy_icon: DummyImage) -> ImageData {
ImageData {
filename: dummy_icon.filename(),
extension: dummy_icon.extension(),
icon: dummy_icon.bytes(),
}
}

View File

@@ -3,12 +3,61 @@ use actix_web::{
test::{self, TestRequest},
};
use labrinth::routes::v3::tags::GameData;
use labrinth::{
database::models::loader_fields::LoaderFieldEnumValue,
routes::v3::tags::{CategoryData, LoaderData},
};
use crate::common::database::ADMIN_USER_PAT;
use super::ApiV3;
impl ApiV3 {
pub async fn get_loaders(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/tag/loader")
.append_header(("Authorization", ADMIN_USER_PAT))
.to_request();
self.call(req).await
}
pub async fn get_loaders_deserialized(&self) -> Vec<LoaderData> {
let resp = self.get_loaders().await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_categories(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/tag/category")
.append_header(("Authorization", ADMIN_USER_PAT))
.to_request();
self.call(req).await
}
pub async fn get_categories_deserialized(&self) -> Vec<CategoryData> {
let resp = self.get_categories().await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_loader_field_variants(&self, loader_field: &str) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/loader_field?loader_field={}", loader_field))
.append_header(("Authorization", ADMIN_USER_PAT))
.to_request();
self.call(req).await
}
pub async fn get_loader_field_variants_deserialized(
&self,
loader_field: &str,
) -> Vec<LoaderFieldEnumValue> {
let resp = self.get_loader_field_variants(loader_field).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
// TODO: fold this into v3 API of other v3 testing PR
pub async fn get_games(&self) -> ServiceResponse {
let req = TestRequest::get()

176
tests/common/api_v3/team.rs Normal file
View File

@@ -0,0 +1,176 @@
use actix_http::StatusCode;
use actix_web::{dev::ServiceResponse, test};
use labrinth::models::{
notifications::Notification,
teams::{OrganizationPermissions, ProjectPermissions, TeamMember},
};
use serde_json::json;
use crate::common::asserts::assert_status;
use super::ApiV3;
impl ApiV3 {
pub async fn get_team_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/team/{id_or_title}/members"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_team_members_deserialized(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
let resp = self.get_team_members(id_or_title, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_project_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/project/{id_or_title}/members"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_project_members_deserialized(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
let resp = self.get_project_members(id_or_title, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_organization_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/organization/{id_or_title}/members"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_organization_members_deserialized(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
let resp = self.get_organization_members(id_or_title, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn join_team(&self, team_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/team/{team_id}/join"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn remove_from_team(
&self,
team_id: &str,
user_id: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/team/{team_id}/members/{user_id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn edit_team_member(
&self,
team_id: &str,
user_id: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/team/{team_id}/members/{user_id}"))
.append_header(("Authorization", pat))
.set_json(patch)
.to_request();
self.call(req).await
}
pub async fn transfer_team_ownership(
&self,
team_id: &str,
user_id: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/team/{team_id}/owner"))
.append_header(("Authorization", pat))
.set_json(json!({
"user_id": user_id,
}))
.to_request();
self.call(req).await
}
pub async fn get_user_notifications(&self, user_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/user/{user_id}/notifications"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_user_notifications_deserialized(
&self,
user_id: &str,
pat: &str,
) -> Vec<Notification> {
let resp = self.get_user_notifications(user_id, pat).await;
assert_status(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn mark_notification_read(
&self,
notification_id: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/notification/{notification_id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn add_user_to_team(
&self,
team_id: &str,
user_id: &str,
project_permissions: Option<ProjectPermissions>,
organization_permissions: Option<OrganizationPermissions>,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/team/{team_id}/members"))
.append_header(("Authorization", pat))
.set_json(json!( {
"user_id": user_id,
"permissions" : project_permissions.map(|p| p.bits()).unwrap_or_default(),
"organization_permissions" : organization_permissions.map(|p| p.bits()),
}))
.to_request();
self.call(req).await
}
pub async fn delete_notification(&self, notification_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/notification/{notification_id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
}

View File

@@ -0,0 +1,422 @@
use std::collections::HashMap;
use actix_http::{header::AUTHORIZATION, StatusCode};
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use labrinth::{
models::{projects::VersionType, v3::projects::Version},
routes::v3::version_file::FileUpdateData,
util::actix::AppendsMultipart,
};
use serde_json::json;
use crate::common::asserts::assert_status;
use super::{request_data::VersionCreationRequestData, ApiV3};
pub fn url_encode_json_serialized_vec(elements: &[String]) -> String {
let serialized = serde_json::to_string(&elements).unwrap();
urlencoding::encode(&serialized).to_string()
}
impl ApiV3 {
pub async fn add_public_version(
&self,
creation_data: VersionCreationRequestData,
pat: &str,
) -> ServiceResponse {
// Add a project.
let req = TestRequest::post()
.uri("/v3/version")
.append_header(("Authorization", pat))
.set_multipart(creation_data.segment_data)
.to_request();
self.call(req).await
}
pub async fn add_public_version_deserialized(
&self,
creation_data: VersionCreationRequestData,
pat: &str,
) -> Version {
let resp = self.add_public_version(creation_data, pat).await;
assert_status(&resp, StatusCode::OK);
let value: serde_json::Value = test::read_body_json(resp).await;
let version_id = value["id"].as_str().unwrap();
self.get_version_deserialized(version_id, pat).await
}
pub async fn get_version(&self, id: &str, pat: &str) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/version/{id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_version_deserialized(&self, id: &str, pat: &str) -> Version {
let resp = self.get_version(id, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn edit_version(
&self,
version_id: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/version/{version_id}"))
.append_header(("Authorization", pat))
.set_json(patch)
.to_request();
self.call(req).await
}
pub async fn get_version_from_hash(
&self,
hash: &str,
algorithm: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/version_file/{hash}?algorithm={algorithm}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_version_from_hash_deserialized(
&self,
hash: &str,
algorithm: &str,
pat: &str,
) -> Version {
let resp = self.get_version_from_hash(hash, algorithm, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_versions_from_hashes(
&self,
hashes: &[&str],
algorithm: &str,
pat: &str,
) -> ServiceResponse {
let req = TestRequest::post()
.uri("/v3/version_files")
.append_header(("Authorization", pat))
.set_json(json!({
"hashes": hashes,
"algorithm": algorithm,
}))
.to_request();
self.call(req).await
}
pub async fn get_versions_from_hashes_deserialized(
&self,
hashes: &[&str],
algorithm: &str,
pat: &str,
) -> HashMap<String, Version> {
let resp = self.get_versions_from_hashes(hashes, algorithm, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_update_from_hash(
&self,
hash: &str,
algorithm: &str,
loaders: Option<Vec<String>>,
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: &str,
) -> ServiceResponse {
let mut json = json!({});
if let Some(loaders) = loaders {
json["loaders"] = serde_json::to_value(loaders).unwrap();
}
if let Some(game_versions) = game_versions {
json["loader_fields"] = json!({
"game_versions": game_versions,
});
}
if let Some(version_types) = version_types {
json["version_types"] = serde_json::to_value(version_types).unwrap();
}
let req = test::TestRequest::post()
.uri(&format!(
"/v3/version_file/{hash}/update?algorithm={algorithm}"
))
.append_header(("Authorization", pat))
.set_json(json)
.to_request();
self.call(req).await
}
pub async fn get_update_from_hash_deserialized(
&self,
hash: &str,
algorithm: &str,
loaders: Option<Vec<String>>,
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: &str,
) -> Version {
let resp = self
.get_update_from_hash(hash, algorithm, loaders, game_versions, version_types, pat)
.await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn update_files(
&self,
algorithm: &str,
hashes: Vec<String>,
loaders: Option<Vec<String>>,
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: &str,
) -> ServiceResponse {
let mut json = json!({
"algorithm": algorithm,
"hashes": hashes,
});
if let Some(loaders) = loaders {
json["loaders"] = serde_json::to_value(loaders).unwrap();
}
if let Some(game_versions) = game_versions {
json["loader_fields"] = json!({
"game_versions": game_versions,
});
}
if let Some(version_types) = version_types {
json["version_types"] = serde_json::to_value(version_types).unwrap();
}
let req = test::TestRequest::post()
.uri("/v3/version_files/update")
.append_header(("Authorization", pat))
.set_json(json)
.to_request();
self.call(req).await
}
pub async fn update_files_deserialized(
&self,
algorithm: &str,
hashes: Vec<String>,
loaders: Option<Vec<String>>,
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: &str,
) -> HashMap<String, Version> {
let resp = self
.update_files(
algorithm,
hashes,
loaders,
game_versions,
version_types,
pat,
)
.await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn update_individual_files(
&self,
algorithm: &str,
hashes: Vec<FileUpdateData>,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri("/v3/version_files/update_individual")
.append_header(("Authorization", pat))
.set_json(json!({
"algorithm": algorithm,
"hashes": hashes
}))
.to_request();
self.call(req).await
}
pub async fn update_individual_files_deserialized(
&self,
algorithm: &str,
hashes: Vec<FileUpdateData>,
pat: &str,
) -> HashMap<String, Version> {
let resp = self.update_individual_files(algorithm, hashes, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
// TODO: Not all fields are tested currently in the v3 tests, only the v2-v3 relevant ones are
#[allow(clippy::too_many_arguments)]
pub async fn get_project_versions(
&self,
project_id_slug: &str,
game_versions: Option<Vec<String>>,
loaders: Option<Vec<String>>,
featured: Option<bool>,
version_type: Option<VersionType>,
limit: Option<usize>,
offset: Option<usize>,
pat: &str,
) -> ServiceResponse {
let mut query_string = String::new();
if let Some(game_versions) = game_versions {
query_string.push_str(&format!(
"&game_versions={}",
urlencoding::encode(&serde_json::to_string(&game_versions).unwrap())
));
}
if let Some(loaders) = loaders {
query_string.push_str(&format!(
"&loaders={}",
urlencoding::encode(&serde_json::to_string(&loaders).unwrap())
));
}
if let Some(featured) = featured {
query_string.push_str(&format!("&featured={}", featured));
}
if let Some(version_type) = version_type {
query_string.push_str(&format!("&version_type={}", version_type));
}
if let Some(limit) = limit {
let limit = limit.to_string();
query_string.push_str(&format!("&limit={}", limit));
}
if let Some(offset) = offset {
let offset = offset.to_string();
query_string.push_str(&format!("&offset={}", offset));
}
let req = test::TestRequest::get()
.uri(&format!(
"/v3/project/{project_id_slug}/version?{}",
query_string.trim_start_matches('&')
))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
#[allow(clippy::too_many_arguments)]
pub async fn get_project_versions_deserialized(
&self,
slug: &str,
game_versions: Option<Vec<String>>,
loaders: Option<Vec<String>>,
featured: Option<bool>,
version_type: Option<VersionType>,
limit: Option<usize>,
offset: Option<usize>,
pat: &str,
) -> Vec<Version> {
let resp = self
.get_project_versions(
slug,
game_versions,
loaders,
featured,
version_type,
limit,
offset,
pat,
)
.await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
// TODO: remove redundancy in these functions
pub async fn create_default_version(
&self,
project_id: &str,
ordering: Option<i32>,
pat: &str,
) -> Version {
let json_data = json!(
{
"project_id": project_id,
"file_parts": ["basic-mod-different.jar"],
"version_number": "1.2.3.4",
"version_title": "start",
"dependencies": [],
"game_versions": ["1.20.1"] ,
"client_side": "required",
"server_side": "optional",
"release_channel": "release",
"loaders": ["fabric"],
"featured": true,
"ordering": ordering,
}
);
let json_segment = labrinth::util::actix::MultipartSegment {
name: "data".to_string(),
filename: None,
content_type: Some("application/json".to_string()),
data: labrinth::util::actix::MultipartSegmentData::Text(
serde_json::to_string(&json_data).unwrap(),
),
};
let file_segment = labrinth::util::actix::MultipartSegment {
name: "basic-mod-different.jar".to_string(),
filename: Some("basic-mod.jar".to_string()),
content_type: Some("application/java-archive".to_string()),
data: labrinth::util::actix::MultipartSegmentData::Binary(
include_bytes!("../../../tests/files/basic-mod-different.jar").to_vec(),
),
};
let request = test::TestRequest::post()
.uri("/v3/version")
.set_multipart(vec![json_segment.clone(), file_segment.clone()])
.append_header((AUTHORIZATION, pat))
.to_request();
let resp = self.call(request).await;
assert_status(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_versions(&self, version_ids: Vec<String>, pat: &str) -> Vec<Version> {
let ids = url_encode_json_serialized_vec(&version_ids);
let request = test::TestRequest::get()
.uri(&format!("/v3/versions?ids={}", ids))
.append_header((AUTHORIZATION, pat))
.to_request();
let resp = self.call(request).await;
assert_status(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn edit_version_ordering(
&self,
version_id: &str,
ordering: Option<i32>,
pat: &str,
) -> ServiceResponse {
let request = test::TestRequest::patch()
.uri(&format!("/v3/version/{version_id}"))
.set_json(json!(
{
"ordering": ordering
}
))
.append_header((AUTHORIZATION, pat))
.to_request();
self.call(request).await
}
}