move to monorepo dir

This commit is contained in:
Jai A
2024-10-16 14:11:42 -07:00
parent ff7975773e
commit e3a3379615
756 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,159 @@
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use bytes::Bytes;
use labrinth::models::{collections::Collection, v3::projects::Project};
use serde_json::json;
use crate::{
assert_status,
common::api_common::{request_data::ImageData, Api, AppendsOptionalPat},
};
use super::ApiV3;
impl ApiV3 {
pub async fn create_collection(
&self,
collection_title: &str,
description: &str,
projects: &[&str],
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri("/v3/collection")
.append_pat(pat)
.set_json(json!({
"name": collection_title,
"description": description,
"projects": projects,
}))
.to_request();
self.call(req).await
}
pub async fn get_collection(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/collection/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_collection_deserialized(&self, id: &str, pat: Option<&str>) -> Collection {
let resp = self.get_collection(id, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_collections(&self, ids: &[&str], pat: Option<&str>) -> ServiceResponse {
let ids = serde_json::to_string(ids).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/collections?ids={}",
urlencoding::encode(&ids)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_collection_projects(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/collection/{id}/projects"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_collection_projects_deserialized(
&self,
id: &str,
pat: Option<&str>,
) -> Vec<Project> {
let resp = self.get_collection_projects(id, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn edit_collection(
&self,
id: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/collection/{id}"))
.append_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
pub async fn edit_collection_icon(
&self,
id: &str,
icon: Option<ImageData>,
pat: Option<&str>,
) -> ServiceResponse {
if let Some(icon) = icon {
// If an icon is provided, upload it
let req = test::TestRequest::patch()
.uri(&format!(
"/v3/collection/{id}/icon?ext={ext}",
ext = icon.extension
))
.append_pat(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/collection/{id}/icon"))
.append_pat(pat)
.to_request();
self.call(req).await
}
}
pub async fn delete_collection(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/collection/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_user_collections(
&self,
user_id_or_username: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/user/{}/collections", user_id_or_username))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_user_collections_deserialized_common(
&self,
user_id_or_username: &str,
pat: Option<&str>,
) -> Vec<Collection> {
let resp = self.get_user_collections(user_id_or_username, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let projects: Vec<Project> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(projects).unwrap();
serde_json::from_value(value).unwrap()
}
}

View File

@@ -0,0 +1,54 @@
#![allow(dead_code)]
use super::{
api_common::{Api, ApiBuildable},
environment::LocalService,
};
use actix_web::{dev::ServiceResponse, test, App};
use async_trait::async_trait;
use labrinth::LabrinthConfig;
use std::rc::Rc;
pub mod collections;
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 user;
pub mod version;
#[derive(Clone)]
pub struct ApiV3 {
pub test_app: Rc<dyn LocalService>,
}
#[async_trait(?Send)]
impl ApiBuildable for ApiV3 {
async fn build(labrinth_config: LabrinthConfig) -> Self {
let app = App::new().configure(|cfg| labrinth::app_config(cfg, labrinth_config.clone()));
let test_app: Rc<dyn LocalService> = Rc::new(test::init_service(app).await);
Self { test_app }
}
}
#[async_trait(?Send)]
impl Api for ApiV3 {
async fn call(&self, req: actix_http::Request) -> ServiceResponse {
self.test_app.call(req).await.unwrap()
}
async fn reset_search_index(&self) -> ServiceResponse {
let req = actix_web::test::TestRequest::post()
.uri("/_internal/admin/_force_reindex")
.append_header((
"Modrinth-Admin",
dotenvy::var("LABRINTH_ADMIN_KEY").unwrap(),
))
.to_request();
self.call(req).await
}
}

View File

@@ -0,0 +1,161 @@
use std::collections::HashMap;
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use labrinth::auth::oauth::{
OAuthClientAccessRequest, RespondToOAuthClientScopes, TokenRequest, TokenResponse,
};
use reqwest::header::{AUTHORIZATION, LOCATION};
use crate::{
assert_status,
common::api_common::{Api, AppendsOptionalPat},
};
use super::ApiV3;
impl ApiV3 {
pub async fn complete_full_authorize_flow(
&self,
client_id: &str,
client_secret: &str,
scope: Option<&str>,
redirect_uri: Option<&str>,
state: Option<&str>,
user_pat: Option<&str>,
) -> String {
let auth_resp = self
.oauth_authorize(client_id, scope, redirect_uri, state, user_pat)
.await;
let flow_id = get_authorize_accept_flow_id(auth_resp).await;
let redirect_resp = self.oauth_accept(&flow_id, user_pat).await;
let auth_code = get_auth_code_from_redirect_params(&redirect_resp).await;
let token_resp = self
.oauth_token(auth_code, None, client_id.to_string(), client_secret)
.await;
get_access_token(token_resp).await
}
pub async fn oauth_authorize(
&self,
client_id: &str,
scope: Option<&str>,
redirect_uri: Option<&str>,
state: Option<&str>,
pat: Option<&str>,
) -> ServiceResponse {
let uri = generate_authorize_uri(client_id, scope, redirect_uri, state);
let req = TestRequest::get().uri(&uri).append_pat(pat).to_request();
self.call(req).await
}
pub async fn oauth_accept(&self, flow: &str, pat: Option<&str>) -> ServiceResponse {
self.call(
TestRequest::post()
.uri("/_internal/oauth/accept")
.append_pat(pat)
.set_json(RespondToOAuthClientScopes {
flow: flow.to_string(),
})
.to_request(),
)
.await
}
pub async fn oauth_reject(&self, flow: &str, pat: Option<&str>) -> ServiceResponse {
self.call(
TestRequest::post()
.uri("/_internal/oauth/reject")
.append_pat(pat)
.set_json(RespondToOAuthClientScopes {
flow: flow.to_string(),
})
.to_request(),
)
.await
}
pub async fn oauth_token(
&self,
auth_code: String,
original_redirect_uri: Option<String>,
client_id: String,
client_secret: &str,
) -> ServiceResponse {
self.call(
TestRequest::post()
.uri("/_internal/oauth/token")
.append_header((AUTHORIZATION, client_secret))
.set_form(TokenRequest {
grant_type: "authorization_code".to_string(),
code: auth_code,
redirect_uri: original_redirect_uri,
client_id: serde_json::from_str(&format!("\"{}\"", client_id)).unwrap(),
})
.to_request(),
)
.await
}
}
pub fn generate_authorize_uri(
client_id: &str,
scope: Option<&str>,
redirect_uri: Option<&str>,
state: Option<&str>,
) -> String {
format!(
"/_internal/oauth/authorize?client_id={}{}{}{}",
urlencoding::encode(client_id),
optional_query_param("redirect_uri", redirect_uri),
optional_query_param("scope", scope),
optional_query_param("state", state),
)
}
pub async fn get_authorize_accept_flow_id(response: ServiceResponse) -> String {
assert_status!(&response, StatusCode::OK);
test::read_body_json::<OAuthClientAccessRequest, _>(response)
.await
.flow_id
}
pub async fn get_auth_code_from_redirect_params(response: &ServiceResponse) -> String {
assert_status!(response, StatusCode::OK);
let query_params = get_redirect_location_query_params(response);
query_params.get("code").unwrap().to_string()
}
pub async fn get_access_token(response: ServiceResponse) -> String {
assert_status!(&response, StatusCode::OK);
test::read_body_json::<TokenResponse, _>(response)
.await
.access_token
}
pub fn get_redirect_location_query_params(
response: &ServiceResponse,
) -> actix_web::web::Query<HashMap<String, String>> {
let redirect_location = response
.headers()
.get(LOCATION)
.unwrap()
.to_str()
.unwrap()
.to_string();
actix_web::web::Query::<HashMap<String, String>>::from_query(
redirect_location.split_once('?').unwrap().1,
)
.unwrap()
}
fn optional_query_param(key: &str, value: Option<&str>) -> String {
if let Some(val) = value {
format!("&{key}={}", urlencoding::encode(val))
} else {
"".to_string()
}
}

View File

@@ -0,0 +1,123 @@
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use labrinth::{
models::{
oauth_clients::{OAuthClient, OAuthClientAuthorization},
pats::Scopes,
},
routes::v3::oauth_clients::OAuthClientEdit,
};
use serde_json::json;
use crate::{
assert_status,
common::api_common::{Api, AppendsOptionalPat},
};
use super::ApiV3;
impl ApiV3 {
pub async fn add_oauth_client(
&self,
name: String,
max_scopes: Scopes,
redirect_uris: Vec<String>,
pat: Option<&str>,
) -> ServiceResponse {
let max_scopes = max_scopes.bits();
let req = TestRequest::post()
.uri("/_internal/oauth/app")
.append_pat(pat)
.set_json(json!({
"name": name,
"max_scopes": max_scopes,
"redirect_uris": redirect_uris
}))
.to_request();
self.call(req).await
}
pub async fn get_user_oauth_clients(
&self,
user_id: &str,
pat: Option<&str>,
) -> Vec<OAuthClient> {
let req = TestRequest::get()
.uri(&format!("/v3/user/{}/oauth_apps", user_id))
.append_pat(pat)
.to_request();
let resp = self.call(req).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_oauth_client(&self, client_id: String, pat: Option<&str>) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/_internal/oauth/app/{}", client_id))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn edit_oauth_client(
&self,
client_id: &str,
edit: OAuthClientEdit,
pat: Option<&str>,
) -> ServiceResponse {
let req = TestRequest::patch()
.uri(&format!(
"/_internal/oauth/app/{}",
urlencoding::encode(client_id)
))
.set_json(edit)
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn delete_oauth_client(&self, client_id: &str, pat: Option<&str>) -> ServiceResponse {
let req = TestRequest::delete()
.uri(&format!("/_internal/oauth/app/{}", client_id))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn revoke_oauth_authorization(
&self,
client_id: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = TestRequest::delete()
.uri(&format!(
"/_internal/oauth/authorizations?client_id={}",
urlencoding::encode(client_id)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_user_oauth_authorizations(
&self,
pat: Option<&str>,
) -> Vec<OAuthClientAuthorization> {
let req = TestRequest::get()
.uri("/_internal/oauth/authorizations")
.append_pat(pat)
.to_request();
let resp = self.call(req).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}

View File

@@ -0,0 +1,186 @@
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use bytes::Bytes;
use labrinth::models::{organizations::Organization, users::UserId, v3::projects::Project};
use serde_json::json;
use crate::{
assert_status,
common::api_common::{request_data::ImageData, Api, AppendsOptionalPat},
};
use super::ApiV3;
impl ApiV3 {
pub async fn create_organization(
&self,
organization_title: &str,
organization_slug: &str,
description: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri("/v3/organization")
.append_pat(pat)
.set_json(json!({
"name": organization_title,
"slug": organization_slug,
"description": description,
}))
.to_request();
self.call(req).await
}
pub async fn get_organization(&self, id_or_title: &str, pat: Option<&str>) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/organization/{id_or_title}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_organization_deserialized(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> Organization {
let resp = self.get_organization(id_or_title, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_organizations(
&self,
ids_or_titles: &[&str],
pat: Option<&str>,
) -> ServiceResponse {
let ids_or_titles = serde_json::to_string(ids_or_titles).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/organizations?ids={}",
urlencoding::encode(&ids_or_titles)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_organization_projects(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/organization/{id_or_title}/projects"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_organization_projects_deserialized(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> Vec<Project> {
let resp = self.get_organization_projects(id_or_title, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn edit_organization(
&self,
id_or_title: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/organization/{id_or_title}"))
.append_pat(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: Option<&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_pat(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_pat(pat)
.to_request();
self.call(req).await
}
}
pub async fn delete_organization(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/organization/{id_or_title}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn organization_add_project(
&self,
id_or_title: &str,
project_id_or_slug: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/organization/{id_or_title}/projects"))
.append_pat(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,
new_owner_user_id: UserId,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!(
"/v3/organization/{id_or_title}/projects/{project_id_or_slug}"
))
.set_json(json!({
"new_owner": new_owner_user_id,
}))
.append_pat(pat)
.to_request();
self.call(req).await
}
}

View File

@@ -0,0 +1,602 @@
use std::collections::HashMap;
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use labrinth::{
models::{organizations::Organization, projects::Project},
search::SearchResults,
util::actix::AppendsMultipart,
};
use rust_decimal::Decimal;
use serde_json::json;
use crate::{
assert_status,
common::{
api_common::{
models::{CommonItemType, CommonProject, CommonVersion},
request_data::{ImageData, ProjectCreationRequestData},
Api, ApiProject, AppendsOptionalPat,
},
database::MOD_USER_PAT,
dummy_data::TestFile,
},
};
use super::{
request_data::{self, get_public_project_creation_data},
ApiV3,
};
#[async_trait(?Send)]
impl ApiProject for ApiV3 {
async fn add_public_project(
&self,
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
pat: Option<&str>,
) -> (CommonProject, Vec<CommonVersion>) {
let creation_data = get_public_project_creation_data(slug, version_jar, modify_json);
// Add a project.
let slug = creation_data.slug.clone();
let resp = self.create_project(creation_data, pat).await;
assert_status!(&resp, StatusCode::OK);
// Approve as a moderator.
let req = TestRequest::patch()
.uri(&format!("/v3/project/{}", slug))
.append_pat(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(&slug, pat).await;
let project = test::read_body_json(project).await;
// Get project's versions
let req = TestRequest::get()
.uri(&format!("/v3/project/{}/version", slug))
.append_pat(pat)
.to_request();
let resp = self.call(req).await;
let versions: Vec<CommonVersion> = test::read_body_json(resp).await;
(project, versions)
}
async fn get_public_project_creation_data_json(
&self,
slug: &str,
version_jar: Option<&TestFile>,
) -> serde_json::Value {
request_data::get_public_project_creation_data_json(slug, version_jar)
}
async fn create_project(
&self,
creation_data: ProjectCreationRequestData,
pat: Option<&str>,
) -> ServiceResponse {
let req = TestRequest::post()
.uri("/v3/project")
.append_pat(pat)
.set_multipart(creation_data.segment_data)
.to_request();
self.call(req).await
}
async fn remove_project(&self, project_slug_or_id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/project/{project_slug_or_id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_project(&self, id_or_slug: &str, pat: Option<&str>) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/project/{id_or_slug}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_project_deserialized_common(
&self,
id_or_slug: &str,
pat: Option<&str>,
) -> CommonProject {
let resp = self.get_project(id_or_slug, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let project: Project = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(project).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_projects(&self, ids_or_slugs: &[&str], pat: Option<&str>) -> ServiceResponse {
let ids_or_slugs = serde_json::to_string(ids_or_slugs).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/projects?ids={encoded}",
encoded = urlencoding::encode(&ids_or_slugs)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_project_dependencies(
&self,
id_or_slug: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/project/{id_or_slug}/dependencies"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_user_projects(
&self,
user_id_or_username: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/user/{}/projects", user_id_or_username))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_user_projects_deserialized_common(
&self,
user_id_or_username: &str,
pat: Option<&str>,
) -> Vec<CommonProject> {
let resp = self.get_user_projects(user_id_or_username, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let projects: Vec<Project> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(projects).unwrap();
serde_json::from_value(value).unwrap()
}
async fn edit_project(
&self,
id_or_slug: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/project/{id_or_slug}"))
.append_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
async fn edit_project_bulk(
&self,
ids_or_slugs: &[&str],
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let projects_str = ids_or_slugs
.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_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
async fn edit_project_icon(
&self,
id_or_slug: &str,
icon: Option<ImageData>,
pat: Option<&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_pat(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_pat(pat)
.to_request();
self.call(req).await
}
}
async fn create_report(
&self,
report_type: &str,
id: &str,
item_type: CommonItemType,
body: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri("/v3/report")
.append_pat(pat)
.set_json(json!(
{
"report_type": report_type,
"item_id": id,
"item_type": item_type.as_str(),
"body": body,
}
))
.to_request();
self.call(req).await
}
async fn get_report(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/report/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_reports(&self, ids: &[&str], pat: Option<&str>) -> ServiceResponse {
let ids_str = serde_json::to_string(ids).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/reports?ids={encoded}",
encoded = urlencoding::encode(&ids_str)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_user_reports(&self, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri("/v3/report")
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn edit_report(
&self,
id: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/report/{id}"))
.append_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
async fn delete_report(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/report/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
#[allow(clippy::too_many_arguments)]
async fn add_gallery_item(
&self,
id_or_slug: &str,
image: ImageData,
featured: bool,
title: Option<String>,
description: Option<String>,
ordering: Option<i32>,
pat: Option<&str>,
) -> ServiceResponse {
let mut url = format!(
"/v3/project/{id_or_slug}/gallery?ext={ext}&featured={featured}",
ext = image.extension,
featured = featured
);
if let Some(title) = title {
url.push_str(&format!("&title={}", title));
}
if let Some(description) = description {
url.push_str(&format!("&description={}", description));
}
if let Some(ordering) = ordering {
url.push_str(&format!("&ordering={}", ordering));
}
let req = test::TestRequest::post()
.uri(&url)
.append_pat(pat)
.set_payload(Bytes::from(image.icon))
.to_request();
self.call(req).await
}
async fn edit_gallery_item(
&self,
id_or_slug: &str,
image_url: &str,
patch: HashMap<String, String>,
pat: Option<&str>,
) -> ServiceResponse {
let mut url = format!(
"/v3/project/{id_or_slug}/gallery?url={image_url}",
image_url = urlencoding::encode(image_url)
);
for (key, value) in patch {
url.push_str(&format!(
"&{key}={value}",
key = key,
value = urlencoding::encode(&value)
));
}
let req = test::TestRequest::patch()
.uri(&url)
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn remove_gallery_item(
&self,
id_or_slug: &str,
url: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!(
"/v3/project/{id_or_slug}/gallery?url={url}",
url = url
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_thread(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/thread/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_threads(&self, ids: &[&str], pat: Option<&str>) -> ServiceResponse {
let ids_str = serde_json::to_string(ids).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/threads?ids={encoded}",
encoded = urlencoding::encode(&ids_str)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn write_to_thread(
&self,
id: &str,
r#type: &str,
content: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/thread/{id}"))
.append_pat(pat)
.set_json(json!({
"body": {
"type": r#type,
"body": content
}
}))
.to_request();
self.call(req).await
}
async fn get_moderation_inbox(&self, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri("/v3/thread/inbox")
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn read_thread(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/thread/{id}/read"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn delete_thread_message(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/message/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
}
impl ApiV3 {
pub async fn get_project_deserialized(&self, id_or_slug: &str, pat: Option<&str>) -> Project {
let resp = self.get_project(id_or_slug, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_project_organization(
&self,
id_or_slug: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/project/{id_or_slug}/organization"))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_project_organization_deserialized(
&self,
id_or_slug: &str,
pat: Option<&str>,
) -> Organization {
let resp = self.get_project_organization(id_or_slug, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn search_deserialized(
&self,
query: Option<&str>,
facets: Option<serde_json::Value>,
pat: Option<&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_pat(pat)
.to_request();
let resp = self.call(req).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_analytics_revenue(
&self,
id_or_slugs: Vec<&str>,
ids_are_version_ids: bool,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
resolution_minutes: Option<u32>,
pat: Option<&str>,
) -> ServiceResponse {
let pv_string = if ids_are_version_ids {
let version_string: String = serde_json::to_string(&id_or_slugs).unwrap();
let version_string = urlencoding::encode(&version_string);
format!("version_ids={}", version_string)
} else {
let projects_string: String = serde_json::to_string(&id_or_slugs).unwrap();
let projects_string = urlencoding::encode(&projects_string);
format!("project_ids={}", 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?{pv_string}{extra_args}",))
.append_pat(pat)
.to_request();
self.call(req).await
}
pub async fn get_analytics_revenue_deserialized(
&self,
id_or_slugs: Vec<&str>,
ids_are_version_ids: bool,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
resolution_minutes: Option<u32>,
pat: Option<&str>,
) -> HashMap<String, HashMap<i64, Decimal>> {
let resp = self
.get_analytics_revenue(
id_or_slugs,
ids_are_version_ids,
start_date,
end_date,
resolution_minutes,
pat,
)
.await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}

View File

@@ -0,0 +1,135 @@
#![allow(dead_code)]
use serde_json::json;
use crate::common::{
api_common::request_data::{ProjectCreationRequestData, VersionCreationRequestData},
dummy_data::TestFile,
};
use labrinth::{
models::projects::ProjectId,
util::actix::{MultipartSegment, MultipartSegmentData},
};
pub fn get_public_project_creation_data(
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
) -> ProjectCreationRequestData {
let mut json_data = get_public_project_creation_data_json(slug, version_jar.as_ref());
if let Some(modify_json) = modify_json {
json_patch::patch(&mut json_data, &modify_json).unwrap();
}
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,
ordering: Option<i32>,
// closure that takes in a &mut serde_json::Value
// and modifies it before it is serialized and sent
modify_json: Option<json_patch::Patch>,
) -> VersionCreationRequestData {
let mut json_data =
get_public_version_creation_data_json(version_number, ordering, &version_jar);
json_data["project_id"] = json!(project_id);
if let Some(modify_json) = modify_json {
json_patch::patch(&mut json_data, &modify_json).unwrap();
}
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,
ordering: Option<i32>,
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"],
"singleplayer": true,
"client_and_server": true,
"client_only": true,
"server_only": false,
});
if is_modpack {
j["mrpack_loaders"] = json!(["fabric"]);
}
if let Some(ordering) = ordering {
j["ordering"] = json!(ordering);
}
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", None, jar)])
} else {
json!([])
};
let is_draft = version_jar.is_none();
json!(
{
"name": format!("Test Project {slug}"),
"slug": slug,
"summary": "A dummy project for testing with.",
"description": "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]
}
}

View File

@@ -0,0 +1,101 @@
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use labrinth::routes::v3::tags::{GameData, LoaderData};
use labrinth::{
database::models::loader_fields::LoaderFieldEnumValue, routes::v3::tags::CategoryData,
};
use crate::{
assert_status,
common::{
api_common::{
models::{CommonCategoryData, CommonLoaderData},
Api, ApiTags, AppendsOptionalPat,
},
database::ADMIN_USER_PAT,
},
};
use super::ApiV3;
#[async_trait(?Send)]
impl ApiTags for ApiV3 {
async fn get_loaders(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/tag/loader")
.append_pat(ADMIN_USER_PAT)
.to_request();
self.call(req).await
}
async fn get_loaders_deserialized_common(&self) -> Vec<CommonLoaderData> {
let resp = self.get_loaders().await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<LoaderData> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_categories(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/tag/category")
.append_pat(ADMIN_USER_PAT)
.to_request();
self.call(req).await
}
async fn get_categories_deserialized_common(&self) -> Vec<CommonCategoryData> {
let resp = self.get_categories().await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<CategoryData> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
}
impl ApiV3 {
pub async fn get_loaders_deserialized(&self) -> Vec<LoaderData> {
let resp = self.get_loaders().await;
assert_status!(&resp, StatusCode::OK);
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_pat(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_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
async fn get_games(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/games")
.append_pat(ADMIN_USER_PAT)
.to_request();
self.call(req).await
}
pub async fn get_games_deserialized(&self) -> Vec<GameData> {
let resp = self.get_games().await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}

View File

@@ -0,0 +1,313 @@
use actix_http::StatusCode;
use actix_web::{dev::ServiceResponse, test};
use async_trait::async_trait;
use labrinth::models::{
notifications::Notification,
teams::{OrganizationPermissions, ProjectPermissions, TeamMember},
};
use serde_json::json;
use crate::{
assert_status,
common::api_common::{
models::{CommonNotification, CommonTeamMember},
Api, ApiTeams, AppendsOptionalPat,
},
};
use super::ApiV3;
impl ApiV3 {
pub async fn get_organization_members_deserialized(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> Vec<TeamMember> {
let resp = self.get_organization_members(id_or_title, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_team_members_deserialized(
&self,
team_id: &str,
pat: Option<&str>,
) -> Vec<TeamMember> {
let resp = self.get_team_members(team_id, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_project_members_deserialized(
&self,
project_id: &str,
pat: Option<&str>,
) -> Vec<TeamMember> {
let resp = self.get_project_members(project_id, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}
#[async_trait(?Send)]
impl ApiTeams for ApiV3 {
async fn get_team_members(&self, id_or_title: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/team/{id_or_title}/members"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_team_members_deserialized_common(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> Vec<CommonTeamMember> {
let resp = self.get_team_members(id_or_title, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<TeamMember> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_teams_members(
&self,
ids_or_titles: &[&str],
pat: Option<&str>,
) -> ServiceResponse {
let ids_or_titles = serde_json::to_string(ids_or_titles).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/teams?ids={}",
urlencoding::encode(&ids_or_titles)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_project_members(&self, id_or_title: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/project/{id_or_title}/members"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_project_members_deserialized_common(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> Vec<CommonTeamMember> {
let resp = self.get_project_members(id_or_title, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<TeamMember> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_organization_members(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/organization/{id_or_title}/members"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_organization_members_deserialized_common(
&self,
id_or_title: &str,
pat: Option<&str>,
) -> Vec<CommonTeamMember> {
let resp = self.get_organization_members(id_or_title, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<TeamMember> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn join_team(&self, team_id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/team/{team_id}/join"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn remove_from_team(
&self,
team_id: &str,
user_id: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/team/{team_id}/members/{user_id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn edit_team_member(
&self,
team_id: &str,
user_id: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/team/{team_id}/members/{user_id}"))
.append_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
async fn transfer_team_ownership(
&self,
team_id: &str,
user_id: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/team/{team_id}/owner"))
.append_pat(pat)
.set_json(json!({
"user_id": user_id,
}))
.to_request();
self.call(req).await
}
async fn get_user_notifications(&self, user_id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/user/{user_id}/notifications"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_user_notifications_deserialized_common(
&self,
user_id: &str,
pat: Option<&str>,
) -> Vec<CommonNotification> {
let resp = self.get_user_notifications(user_id, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<Notification> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_notification(&self, notification_id: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/notification/{notification_id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_notifications(
&self,
notification_ids: &[&str],
pat: Option<&str>,
) -> ServiceResponse {
let notification_ids = serde_json::to_string(notification_ids).unwrap();
let req = test::TestRequest::get()
.uri(&format!(
"/v3/notifications?ids={}",
urlencoding::encode(&notification_ids)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn mark_notification_read(
&self,
notification_id: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/notification/{notification_id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn mark_notifications_read(
&self,
notification_ids: &[&str],
pat: Option<&str>,
) -> ServiceResponse {
let notification_ids = serde_json::to_string(notification_ids).unwrap();
let req = test::TestRequest::patch()
.uri(&format!(
"/v3/notifications?ids={}",
urlencoding::encode(&notification_ids)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn add_user_to_team(
&self,
team_id: &str,
user_id: &str,
project_permissions: Option<ProjectPermissions>,
organization_permissions: Option<OrganizationPermissions>,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v3/team/{team_id}/members"))
.append_pat(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
}
async fn delete_notification(
&self,
notification_id: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/notification/{notification_id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn delete_notifications(
&self,
notification_ids: &[&str],
pat: Option<&str>,
) -> ServiceResponse {
let notification_ids = serde_json::to_string(notification_ids).unwrap();
let req = test::TestRequest::delete()
.uri(&format!(
"/v3/notifications?ids={}",
urlencoding::encode(&notification_ids)
))
.append_pat(pat)
.to_request();
self.call(req).await
}
}

View File

@@ -0,0 +1,48 @@
use actix_web::{dev::ServiceResponse, test};
use async_trait::async_trait;
use crate::common::api_common::{Api, ApiUser, AppendsOptionalPat};
use super::ApiV3;
#[async_trait(?Send)]
impl ApiUser for ApiV3 {
async fn get_user(&self, user_id_or_username: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/user/{}", user_id_or_username))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_current_user(&self, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::get()
.uri("/v3/user")
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn edit_user(
&self,
user_id_or_username: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/user/{}", user_id_or_username))
.append_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
async fn delete_user(&self, user_id_or_username: &str, pat: Option<&str>) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v3/user/{}", user_id_or_username))
.append_pat(pat)
.to_request();
self.call(req).await
}
}

View File

@@ -0,0 +1,547 @@
use std::collections::HashMap;
use super::{
request_data::{self, get_public_version_creation_data},
ApiV3,
};
use crate::{
assert_status,
common::{
api_common::{models::CommonVersion, Api, ApiVersion, AppendsOptionalPat},
dummy_data::TestFile,
},
};
use actix_http::StatusCode;
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use labrinth::{
models::{
projects::{ProjectId, VersionType},
v3::projects::Version,
},
routes::v3::version_file::FileUpdateData,
util::actix::AppendsMultipart,
};
use serde_json::json;
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_deserialized(
&self,
project_id: ProjectId,
version_number: &str,
version_jar: TestFile,
ordering: Option<i32>,
modify_json: Option<json_patch::Patch>,
pat: Option<&str>,
) -> Version {
let resp = self
.add_public_version(
project_id,
version_number,
version_jar,
ordering,
modify_json,
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();
let version = self.get_version(version_id, pat).await;
assert_status!(&version, StatusCode::OK);
test::read_body_json(version).await
}
pub async fn get_version_deserialized(&self, id: &str, pat: Option<&str>) -> Version {
let resp = self.get_version(id, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn get_versions_deserialized(
&self,
version_ids: Vec<String>,
pat: Option<&str>,
) -> Vec<Version> {
let resp = self.get_versions(version_ids, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
pub async fn update_individual_files(
&self,
algorithm: &str,
hashes: Vec<FileUpdateData>,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::post()
.uri("/v3/version_files/update_individual")
.append_pat(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: Option<&str>,
) -> HashMap<String, Version> {
let resp = self.update_individual_files(algorithm, hashes, pat).await;
assert_status!(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}
#[async_trait(?Send)]
impl ApiVersion for ApiV3 {
async fn add_public_version(
&self,
project_id: ProjectId,
version_number: &str,
version_jar: TestFile,
ordering: Option<i32>,
modify_json: Option<json_patch::Patch>,
pat: Option<&str>,
) -> ServiceResponse {
let creation_data = get_public_version_creation_data(
project_id,
version_number,
version_jar,
ordering,
modify_json,
);
// Add a versiom.
let req = TestRequest::post()
.uri("/v3/version")
.append_pat(pat)
.set_multipart(creation_data.segment_data)
.to_request();
self.call(req).await
}
async fn add_public_version_deserialized_common(
&self,
project_id: ProjectId,
version_number: &str,
version_jar: TestFile,
ordering: Option<i32>,
modify_json: Option<json_patch::Patch>,
pat: Option<&str>,
) -> CommonVersion {
let resp = self
.add_public_version(
project_id,
version_number,
version_jar,
ordering,
modify_json,
pat,
)
.await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Version = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_version(&self, id: &str, pat: Option<&str>) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v3/version/{id}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_version_deserialized_common(&self, id: &str, pat: Option<&str>) -> CommonVersion {
let resp = self.get_version(id, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Version = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn edit_version(
&self,
version_id: &str,
patch: serde_json::Value,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v3/version/{version_id}"))
.append_pat(pat)
.set_json(patch)
.to_request();
self.call(req).await
}
async fn download_version_redirect(
&self,
hash: &str,
algorithm: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/version_file/{hash}/download",))
.set_json(json!({
"algorithm": algorithm,
}))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_version_from_hash(
&self,
hash: &str,
algorithm: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v3/version_file/{hash}?algorithm={algorithm}"))
.append_pat(pat)
.to_request();
self.call(req).await
}
async fn get_version_from_hash_deserialized_common(
&self,
hash: &str,
algorithm: &str,
pat: Option<&str>,
) -> CommonVersion {
let resp = self.get_version_from_hash(hash, algorithm, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Version = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn get_versions_from_hashes(
&self,
hashes: &[&str],
algorithm: &str,
pat: Option<&str>,
) -> ServiceResponse {
let req = TestRequest::post()
.uri("/v3/version_files")
.append_pat(pat)
.set_json(json!({
"hashes": hashes,
"algorithm": algorithm,
}))
.to_request();
self.call(req).await
}
async fn get_versions_from_hashes_deserialized_common(
&self,
hashes: &[&str],
algorithm: &str,
pat: Option<&str>,
) -> HashMap<String, CommonVersion> {
let resp = self.get_versions_from_hashes(hashes, algorithm, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: HashMap<String, Version> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
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: Option<&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_pat(pat)
.set_json(json)
.to_request();
self.call(req).await
}
async fn get_update_from_hash_deserialized_common(
&self,
hash: &str,
algorithm: &str,
loaders: Option<Vec<String>>,
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: Option<&str>,
) -> CommonVersion {
let resp = self
.get_update_from_hash(hash, algorithm, loaders, game_versions, version_types, pat)
.await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Version = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
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: Option<&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["game_versions"] = serde_json::to_value(game_versions).unwrap();
}
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_pat(pat)
.set_json(json)
.to_request();
self.call(req).await
}
async fn update_files_deserialized_common(
&self,
algorithm: &str,
hashes: Vec<String>,
loaders: Option<Vec<String>>,
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: Option<&str>,
) -> HashMap<String, CommonVersion> {
let resp = self
.update_files(
algorithm,
hashes,
loaders,
game_versions,
version_types,
pat,
)
.await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: HashMap<String, Version> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
// TODO: Not all fields are tested currently in the v3 tests, only the v2-v3 relevant ones are
#[allow(clippy::too_many_arguments)]
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: Option<&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_pat(pat)
.to_request();
self.call(req).await
}
#[allow(clippy::too_many_arguments)]
async fn get_project_versions_deserialized_common(
&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: Option<&str>,
) -> Vec<CommonVersion> {
let resp = self
.get_project_versions(
slug,
game_versions,
loaders,
featured,
version_type,
limit,
offset,
pat,
)
.await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<Version> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn edit_version_ordering(
&self,
version_id: &str,
ordering: Option<i32>,
pat: Option<&str>,
) -> ServiceResponse {
let request = test::TestRequest::patch()
.uri(&format!("/v3/version/{version_id}"))
.set_json(json!(
{
"ordering": ordering
}
))
.append_pat(pat)
.to_request();
self.call(request).await
}
async fn get_versions(&self, version_ids: Vec<String>, pat: Option<&str>) -> ServiceResponse {
let ids = url_encode_json_serialized_vec(&version_ids);
let request = test::TestRequest::get()
.uri(&format!("/v3/versions?ids={}", ids))
.append_pat(pat)
.to_request();
self.call(request).await
}
async fn get_versions_deserialized_common(
&self,
version_ids: Vec<String>,
pat: Option<&str>,
) -> Vec<CommonVersion> {
let resp = self.get_versions(version_ids, pat).await;
assert_status!(&resp, StatusCode::OK);
// First, deserialize to the non-common format (to test the response is valid for this api version)
let v: Vec<Version> = test::read_body_json(resp).await;
// Then, deserialize to the common format
let value = serde_json::to_value(v).unwrap();
serde_json::from_value(value).unwrap()
}
async fn upload_file_to_version(
&self,
version_id: &str,
file: &TestFile,
pat: Option<&str>,
) -> ServiceResponse {
let m = request_data::get_public_creation_data_multipart(
&json!({
"file_parts": [file.filename()]
}),
Some(file),
);
let request = test::TestRequest::post()
.uri(&format!(
"/v3/version/{version_id}/file",
version_id = version_id
))
.append_pat(pat)
.set_multipart(m)
.to_request();
self.call(request).await
}
async fn remove_version(&self, version_id: &str, pat: Option<&str>) -> ServiceResponse {
let request = test::TestRequest::delete()
.uri(&format!(
"/v3/version/{version_id}",
version_id = version_id
))
.append_pat(pat)
.to_request();
self.call(request).await
}
async fn remove_version_file(&self, hash: &str, pat: Option<&str>) -> ServiceResponse {
let request = test::TestRequest::delete()
.uri(&format!("/v3/version_file/{hash}"))
.append_pat(pat)
.to_request();
self.call(request).await
}
}