Tests v2 recreate (#760)

* added common project information; setup for v2 test change

* all tests now use with_test_environment

* progress, failing

* finished re-adding tests

* prepare

* cargo sqlx prepare -- --tests

* fmt; clippy; prepare

* sqlx prepare

* adds version_create fix and corresponding test

* merge fixes; rev

* fmt, clippy, prepare

* test cargo sqlx prepare
This commit is contained in:
Wyatt Verchere
2023-11-25 13:42:39 -08:00
committed by GitHub
parent ade8c162cd
commit 172b93d07f
51 changed files with 7573 additions and 6631 deletions

View File

@@ -0,0 +1,136 @@
use std::collections::HashMap;
use actix_web::dev::ServiceResponse;
use async_trait::async_trait;
use labrinth::{
models::{
projects::{ProjectId, VersionType},
teams::{OrganizationPermissions, ProjectPermissions},
},
search::SearchResults,
};
use crate::common::{api_v2::ApiV2, api_v3::ApiV3, dummy_data::TestFile};
use super::{
models::{CommonImageData, CommonProject, CommonVersion},
Api, ApiProject, ApiTags, ApiTeams, ApiVersion,
};
#[derive(Clone)]
pub enum GenericApi {
V2(ApiV2),
V3(ApiV3),
}
macro_rules! delegate_api_variant {
(
$(#[$meta:meta])*
impl $impl_name:ident for $struct_name:ident {
$(
[$method_name:ident, $ret:ty, $($param_name:ident: $param_type:ty),*]
),* $(,)?
}
) => {
$(#[$meta])*
impl $impl_name for $struct_name {
$(
async fn $method_name(&self, $($param_name: $param_type),*) -> $ret {
match self {
$struct_name::V2(api) => api.$method_name($($param_name),*).await,
$struct_name::V3(api) => api.$method_name($($param_name),*).await,
}
}
)*
}
};
}
#[async_trait(?Send)]
impl Api for GenericApi {
async fn call(&self, req: actix_http::Request) -> ServiceResponse {
match self {
Self::V2(api) => api.call(req).await,
Self::V3(api) => api.call(req).await,
}
}
async fn reset_search_index(&self) -> ServiceResponse {
match self {
Self::V2(api) => api.reset_search_index().await,
Self::V3(api) => api.reset_search_index().await,
}
}
}
delegate_api_variant!(
#[async_trait(?Send)]
impl ApiProject for GenericApi {
[add_public_project, (CommonProject, Vec<CommonVersion>), slug: &str, version_jar: Option<TestFile>, modify_json: Option<json_patch::Patch>, pat: &str],
[remove_project, ServiceResponse, project_slug_or_id: &str, pat: &str],
[get_project, ServiceResponse, id_or_slug: &str, pat: &str],
[get_project_deserialized_common, CommonProject, id_or_slug: &str, pat: &str],
[get_user_projects, ServiceResponse, user_id_or_username: &str, pat: &str],
[get_user_projects_deserialized_common, Vec<CommonProject>, user_id_or_username: &str, pat: &str],
[edit_project, ServiceResponse, id_or_slug: &str, patch: serde_json::Value, pat: &str],
[edit_project_bulk, ServiceResponse, ids_or_slugs: &[&str], patch: serde_json::Value, pat: &str],
[edit_project_icon, ServiceResponse, id_or_slug: &str, icon: Option<CommonImageData>, pat: &str],
[search_deserialized_common, SearchResults, query: Option<&str>, facets: Option<serde_json::Value>, pat: &str],
}
);
delegate_api_variant!(
#[async_trait(?Send)]
impl ApiTags for GenericApi {
[get_loaders, ServiceResponse,],
[get_loaders_deserialized_common, Vec<crate::common::api_common::models::CommonLoaderData>,],
[get_categories, ServiceResponse,],
[get_categories_deserialized_common, Vec<crate::common::api_common::models::CommonCategoryData>,],
}
);
delegate_api_variant!(
#[async_trait(?Send)]
impl ApiTeams for GenericApi {
[get_team_members, ServiceResponse, team_id: &str, pat: &str],
[get_team_members_deserialized_common, Vec<crate::common::api_common::models::CommonTeamMember>, team_id: &str, pat: &str],
[get_project_members, ServiceResponse, id_or_slug: &str, pat: &str],
[get_project_members_deserialized_common, Vec<crate::common::api_common::models::CommonTeamMember>, id_or_slug: &str, pat: &str],
[get_organization_members, ServiceResponse, id_or_title: &str, pat: &str],
[get_organization_members_deserialized_common, Vec<crate::common::api_common::models::CommonTeamMember>, id_or_title: &str, pat: &str],
[join_team, ServiceResponse, team_id: &str, pat: &str],
[remove_from_team, ServiceResponse, team_id: &str, user_id: &str, pat: &str],
[edit_team_member, ServiceResponse, team_id: &str, user_id: &str, patch: serde_json::Value, pat: &str],
[transfer_team_ownership, ServiceResponse, team_id: &str, user_id: &str, pat: &str],
[get_user_notifications, ServiceResponse, user_id: &str, pat: &str],
[get_user_notifications_deserialized_common, Vec<crate::common::api_common::models::CommonNotification>, user_id: &str, pat: &str],
[mark_notification_read, ServiceResponse, notification_id: &str, pat: &str],
[add_user_to_team, ServiceResponse, team_id: &str, user_id: &str, project_permissions: Option<ProjectPermissions>, organization_permissions: Option<OrganizationPermissions>, pat: &str],
[delete_notification, ServiceResponse, notification_id: &str, pat: &str],
}
);
delegate_api_variant!(
#[async_trait(?Send)]
impl ApiVersion for GenericApi {
[add_public_version, ServiceResponse, project_id: ProjectId, version_number: &str, version_jar: TestFile, ordering: Option<i32>, modify_json: Option<json_patch::Patch>, pat: &str],
[add_public_version_deserialized_common, CommonVersion, project_id: ProjectId, version_number: &str, version_jar: TestFile, ordering: Option<i32>, modify_json: Option<json_patch::Patch>, pat: &str],
[get_version, ServiceResponse, id_or_slug: &str, pat: &str],
[get_version_deserialized_common, CommonVersion, id_or_slug: &str, pat: &str],
[get_versions, ServiceResponse, ids_or_slugs: Vec<String>, pat: &str],
[get_versions_deserialized_common, Vec<CommonVersion>, ids_or_slugs: Vec<String>, pat: &str],
[edit_version, ServiceResponse, id_or_slug: &str, patch: serde_json::Value, pat: &str],
[get_version_from_hash, ServiceResponse, id_or_slug: &str, hash: &str, pat: &str],
[get_version_from_hash_deserialized_common, CommonVersion, id_or_slug: &str, hash: &str, pat: &str],
[get_versions_from_hashes, ServiceResponse, hashes: &[&str], algorithm: &str, pat: &str],
[get_versions_from_hashes_deserialized_common, HashMap<String, CommonVersion>, hashes: &[&str], algorithm: &str, pat: &str],
[get_update_from_hash, ServiceResponse, hash: &str, algorithm: &str, loaders: Option<Vec<String>>,game_versions: Option<Vec<String>>, version_types: Option<Vec<String>>, pat: &str],
[get_update_from_hash_deserialized_common, CommonVersion, hash: &str, algorithm: &str,loaders: Option<Vec<String>>,game_versions: Option<Vec<String>>,version_types: Option<Vec<String>>, pat: &str],
[update_files, ServiceResponse, algorithm: &str, hashes: Vec<String>, loaders: Option<Vec<String>>, game_versions: Option<Vec<String>>, version_types: Option<Vec<String>>, pat: &str],
[update_files_deserialized_common, HashMap<String, CommonVersion>, algorithm: &str, hashes: Vec<String>, loaders: Option<Vec<String>>, game_versions: Option<Vec<String>>, version_types: Option<Vec<String>>, pat: &str],
[get_project_versions, ServiceResponse, 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],
[get_project_versions_deserialized_common, Vec<CommonVersion>, 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],
[edit_version_ordering, ServiceResponse, version_id: &str,ordering: Option<i32>,pat: &str],
}
);

View File

@@ -0,0 +1,262 @@
use std::collections::HashMap;
use self::models::{
CommonCategoryData, CommonImageData, CommonLoaderData, CommonNotification, CommonProject,
CommonTeamMember, CommonVersion,
};
use actix_web::dev::ServiceResponse;
use async_trait::async_trait;
use labrinth::{
models::{
projects::{ProjectId, VersionType},
teams::{OrganizationPermissions, ProjectPermissions},
},
search::SearchResults,
LabrinthConfig,
};
use super::dummy_data::TestFile;
pub mod generic;
pub mod models;
#[async_trait(?Send)]
pub trait ApiBuildable: Api {
async fn build(labrinth_config: LabrinthConfig) -> Self;
}
#[async_trait(?Send)]
pub trait Api: ApiProject + ApiTags + ApiTeams + ApiVersion {
async fn call(&self, req: actix_http::Request) -> ServiceResponse;
async fn reset_search_index(&self) -> ServiceResponse;
}
#[async_trait(?Send)]
pub trait ApiProject {
async fn add_public_project(
&self,
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
pat: &str,
) -> (CommonProject, Vec<CommonVersion>);
async fn remove_project(&self, id_or_slug: &str, pat: &str) -> ServiceResponse;
async fn get_project(&self, id_or_slug: &str, pat: &str) -> ServiceResponse;
async fn get_project_deserialized_common(&self, id_or_slug: &str, pat: &str) -> CommonProject;
async fn get_user_projects(&self, user_id_or_username: &str, pat: &str) -> ServiceResponse;
async fn get_user_projects_deserialized_common(
&self,
user_id_or_username: &str,
pat: &str,
) -> Vec<CommonProject>;
async fn edit_project(
&self,
id_or_slug: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse;
async fn edit_project_bulk(
&self,
ids_or_slugs: &[&str],
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse;
async fn edit_project_icon(
&self,
id_or_slug: &str,
icon: Option<CommonImageData>,
pat: &str,
) -> ServiceResponse;
async fn search_deserialized_common(
&self,
query: Option<&str>,
facets: Option<serde_json::Value>,
pat: &str,
) -> SearchResults;
}
#[async_trait(?Send)]
pub trait ApiTags {
async fn get_loaders(&self) -> ServiceResponse;
async fn get_loaders_deserialized_common(&self) -> Vec<CommonLoaderData>;
async fn get_categories(&self) -> ServiceResponse;
async fn get_categories_deserialized_common(&self) -> Vec<CommonCategoryData>;
}
#[async_trait(?Send)]
pub trait ApiTeams {
async fn get_team_members(&self, team_id: &str, pat: &str) -> ServiceResponse;
async fn get_team_members_deserialized_common(
&self,
team_id: &str,
pat: &str,
) -> Vec<CommonTeamMember>;
async fn get_project_members(&self, id_or_slug: &str, pat: &str) -> ServiceResponse;
async fn get_project_members_deserialized_common(
&self,
id_or_slug: &str,
pat: &str,
) -> Vec<CommonTeamMember>;
async fn get_organization_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse;
async fn get_organization_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<CommonTeamMember>;
async fn join_team(&self, team_id: &str, pat: &str) -> ServiceResponse;
async fn remove_from_team(&self, team_id: &str, user_id: &str, pat: &str) -> ServiceResponse;
async fn edit_team_member(
&self,
team_id: &str,
user_id: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse;
async fn transfer_team_ownership(
&self,
team_id: &str,
user_id: &str,
pat: &str,
) -> ServiceResponse;
async fn get_user_notifications(&self, user_id: &str, pat: &str) -> ServiceResponse;
async fn get_user_notifications_deserialized_common(
&self,
user_id: &str,
pat: &str,
) -> Vec<CommonNotification>;
async fn mark_notification_read(&self, notification_id: &str, pat: &str) -> ServiceResponse;
async fn add_user_to_team(
&self,
team_id: &str,
user_id: &str,
project_permissions: Option<ProjectPermissions>,
organization_permissions: Option<OrganizationPermissions>,
pat: &str,
) -> ServiceResponse;
async fn delete_notification(&self, notification_id: &str, pat: &str) -> ServiceResponse;
}
#[async_trait(?Send)]
pub trait ApiVersion {
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: &str,
) -> ServiceResponse;
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: &str,
) -> CommonVersion;
async fn get_version(&self, id_or_slug: &str, pat: &str) -> ServiceResponse;
async fn get_version_deserialized_common(&self, id_or_slug: &str, pat: &str) -> CommonVersion;
async fn get_versions(&self, ids_or_slugs: Vec<String>, pat: &str) -> ServiceResponse;
async fn get_versions_deserialized_common(
&self,
ids_or_slugs: Vec<String>,
pat: &str,
) -> Vec<CommonVersion>;
async fn edit_version(
&self,
id_or_slug: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse;
async fn get_version_from_hash(
&self,
id_or_slug: &str,
hash: &str,
pat: &str,
) -> ServiceResponse;
async fn get_version_from_hash_deserialized_common(
&self,
id_or_slug: &str,
hash: &str,
pat: &str,
) -> CommonVersion;
async fn get_versions_from_hashes(
&self,
hashes: &[&str],
algorithm: &str,
pat: &str,
) -> ServiceResponse;
async fn get_versions_from_hashes_deserialized_common(
&self,
hashes: &[&str],
algorithm: &str,
pat: &str,
) -> HashMap<String, CommonVersion>;
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;
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: &str,
) -> CommonVersion;
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;
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: &str,
) -> HashMap<String, CommonVersion>;
#[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: &str,
) -> ServiceResponse;
#[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: &str,
) -> Vec<CommonVersion>;
async fn edit_version_ordering(
&self,
version_id: &str,
ordering: Option<i32>,
pat: &str,
) -> ServiceResponse;
}

View File

@@ -0,0 +1,141 @@
use chrono::{DateTime, Utc};
use labrinth::models::{
notifications::{NotificationAction, NotificationBody, NotificationId},
organizations::OrganizationId,
projects::{
Dependency, DonationLink, GalleryItem, License, ModeratorMessage, MonetizationStatus,
ProjectId, ProjectStatus, VersionFile, VersionId, VersionStatus, VersionType,
},
teams::{OrganizationPermissions, ProjectPermissions, TeamId},
threads::ThreadId,
users::{User, UserId},
};
use rust_decimal::Decimal;
use serde::Deserialize;
// Fields shared by every version of the API.
// No struct in here should have ANY field that
// is not present in *every* version of the API.
// These are used for common tests- tests that can be used on both V2 AND v3 of the API and have the same results.
// Any test that requires version-specific fields should have its own test that is not done for each version,
// as the environment generator for both uses common fields.
#[derive(Deserialize)]
pub struct CommonProject {
// For example, for CommonProject, we do not include:
// - game_versions (v2 only)
// - loader_fields (v3 only)
// - etc.
// For any tests that require those fields, we make a separate test with separate API functions tht do not use Common models.
pub id: ProjectId,
pub slug: Option<String>,
pub team: TeamId,
pub organization: Option<OrganizationId>,
pub title: String,
pub description: String,
pub body: String,
pub body_url: Option<String>,
pub published: DateTime<Utc>,
pub updated: DateTime<Utc>,
pub approved: Option<DateTime<Utc>>,
pub queued: Option<DateTime<Utc>>,
pub status: ProjectStatus,
pub requested_status: Option<ProjectStatus>,
pub moderator_message: Option<ModeratorMessage>,
pub license: License,
pub downloads: u32,
pub followers: u32,
pub categories: Vec<String>,
pub additional_categories: Vec<String>,
pub loaders: Vec<String>,
pub versions: Vec<VersionId>,
pub icon_url: Option<String>,
pub issues_url: Option<String>,
pub source_url: Option<String>,
pub wiki_url: Option<String>,
pub discord_url: Option<String>,
pub donation_urls: Option<Vec<DonationLink>>,
pub gallery: Vec<GalleryItem>,
pub color: Option<u32>,
pub thread_id: ThreadId,
pub monetization_status: MonetizationStatus,
}
#[derive(Deserialize, Clone)]
pub struct CommonVersion {
pub id: VersionId,
pub loaders: Vec<String>,
pub project_id: ProjectId,
pub author_id: UserId,
pub featured: bool,
pub name: String,
pub version_number: String,
pub changelog: String,
pub changelog_url: Option<String>,
pub date_published: DateTime<Utc>,
pub downloads: u32,
pub version_type: VersionType,
pub status: VersionStatus,
pub requested_status: Option<VersionStatus>,
pub files: Vec<VersionFile>,
pub dependencies: Vec<Dependency>,
// TODO: should ordering be in v2?
pub ordering: Option<i32>,
}
#[derive(Deserialize)]
pub struct CommonImageData {
pub filename: String,
pub extension: String,
pub icon: Vec<u8>,
}
#[derive(Deserialize)]
pub struct CommonLoaderData {
pub icon: String,
pub name: String,
pub supported_project_types: Vec<String>,
}
#[derive(Deserialize)]
pub struct CommonCategoryData {
pub icon: String,
pub name: String,
pub project_type: String,
pub header: String,
}
/// A member of a team
#[derive(Deserialize)]
pub struct CommonTeamMember {
pub team_id: TeamId,
pub user: User,
pub role: String,
// TODO: Should these be removed from the Common?
pub permissions: Option<ProjectPermissions>,
pub organization_permissions: Option<OrganizationPermissions>,
pub accepted: bool,
pub payouts_split: Option<Decimal>,
pub ordering: i64,
}
#[derive(Deserialize)]
pub struct CommonNotification {
pub id: NotificationId,
pub user_id: UserId,
pub read: bool,
pub created: DateTime<Utc>,
pub body: NotificationBody,
// DEPRECATED: use body field instead
#[serde(rename = "type")]
pub type_: Option<String>,
pub title: String,
pub text: String,
pub link: String,
pub actions: Vec<NotificationAction>,
}

View File

@@ -1,7 +1,12 @@
#![allow(dead_code)]
use super::environment::LocalService;
use actix_web::dev::ServiceResponse;
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 project;
@@ -15,12 +20,23 @@ pub struct ApiV2 {
pub test_app: Rc<dyn LocalService>,
}
impl ApiV2 {
pub async fn call(&self, req: actix_http::Request) -> ServiceResponse {
#[async_trait(?Send)]
impl ApiBuildable for ApiV2 {
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 ApiV2 {
async fn call(&self, req: actix_http::Request) -> ServiceResponse {
self.test_app.call(req).await.unwrap()
}
pub async fn reset_search_index(&self) -> ServiceResponse {
async fn reset_search_index(&self) -> ServiceResponse {
let req = actix_web::test::TestRequest::post()
.uri("/v2/admin/_force_reindex")
.append_header((

View File

@@ -1,30 +1,55 @@
use crate::common::api_v2::request_data::ProjectCreationRequestData;
use crate::common::{
api_common::{
models::{CommonImageData, CommonProject, CommonVersion},
Api, ApiProject,
},
dummy_data::TestFile,
};
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::v2::projects::{LegacyProject, LegacyVersion},
search::SearchResults,
util::actix::AppendsMultipart,
models::v2::projects::LegacyProject, search::SearchResults, util::actix::AppendsMultipart,
};
use rust_decimal::Decimal;
use serde_json::json;
use std::collections::HashMap;
use crate::common::{asserts::assert_status, database::MOD_USER_PAT};
use super::{request_data::ImageData, ApiV2};
use super::{request_data::get_public_project_creation_data, ApiV2};
impl ApiV2 {
pub async fn add_public_project(
pub async fn get_project_deserialized(&self, id_or_slug: &str, pat: &str) -> LegacyProject {
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_deserialized(
&self,
creation_data: ProjectCreationRequestData,
user_id_or_username: &str,
pat: &str,
) -> (LegacyProject, Vec<LegacyVersion>) {
) -> Vec<LegacyProject> {
let resp = self.get_user_projects(user_id_or_username, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
}
#[async_trait(?Send)]
impl ApiProject for ApiV2 {
async fn add_public_project(
&self,
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
pat: &str,
) -> (CommonProject, Vec<CommonVersion>) {
let creation_data = get_public_project_creation_data(slug, version_jar, modify_json);
// Add a project.
let req = TestRequest::post()
.uri("/v2/project")
@@ -48,7 +73,7 @@ impl ApiV2 {
assert_status(&resp, StatusCode::NO_CONTENT);
let project = self
.get_project_deserialized(&creation_data.slug, pat)
.get_project_deserialized_common(&creation_data.slug, pat)
.await;
// Get project's versions
@@ -57,12 +82,12 @@ impl ApiV2 {
.append_header(("Authorization", pat))
.to_request();
let resp = self.call(req).await;
let versions: Vec<LegacyVersion> = test::read_body_json(resp).await;
let versions: Vec<CommonVersion> = test::read_body_json(resp).await;
(project, versions)
}
pub async fn remove_project(&self, project_slug_or_id: &str, pat: &str) -> ServiceResponse {
async fn remove_project(&self, project_slug_or_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v2/project/{project_slug_or_id}"))
.append_header(("Authorization", pat))
@@ -72,20 +97,21 @@ impl ApiV2 {
resp
}
pub async fn get_project(&self, id_or_slug: &str, pat: &str) -> ServiceResponse {
async fn get_project(&self, id_or_slug: &str, pat: &str) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v2/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) -> LegacyProject {
async fn get_project_deserialized_common(&self, id_or_slug: &str, pat: &str) -> CommonProject {
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 {
async fn get_user_projects(&self, user_id_or_username: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v2/user/{}/projects", user_id_or_username))
.append_header(("Authorization", pat))
@@ -93,17 +119,17 @@ impl ApiV2 {
self.call(req).await
}
pub async fn get_user_projects_deserialized(
async fn get_user_projects_deserialized_common(
&self,
user_id_or_username: &str,
pat: &str,
) -> Vec<LegacyProject> {
) -> Vec<CommonProject> {
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(
async fn edit_project(
&self,
id_or_slug: &str,
patch: serde_json::Value,
@@ -118,14 +144,14 @@ impl ApiV2 {
self.call(req).await
}
pub async fn edit_project_bulk(
async fn edit_project_bulk(
&self,
ids_or_slugs: impl IntoIterator<Item = &str>,
ids_or_slugs: &[&str],
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let projects_str = ids_or_slugs
.into_iter()
.iter()
.map(|s| format!("\"{}\"", s))
.collect::<Vec<_>>()
.join(",");
@@ -141,10 +167,10 @@ impl ApiV2 {
self.call(req).await
}
pub async fn edit_project_icon(
async fn edit_project_icon(
&self,
id_or_slug: &str,
icon: Option<ImageData>,
icon: Option<CommonImageData>,
pat: &str,
) -> ServiceResponse {
if let Some(icon) = icon {
@@ -170,7 +196,7 @@ impl ApiV2 {
}
}
pub async fn search_deserialized(
async fn search_deserialized_common(
&self,
query: Option<&str>,
facets: Option<serde_json::Value>,
@@ -197,57 +223,4 @@ impl ApiV2 {
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!(
"/v2/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

@@ -28,8 +28,12 @@ pub struct ImageData {
pub fn get_public_project_creation_data(
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
) -> ProjectCreationRequestData {
let json_data = get_public_project_creation_data_json(slug, version_jar.as_ref());
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(),
@@ -42,9 +46,15 @@ pub fn get_public_version_creation_data(
project_id: ProjectId,
version_number: &str,
version_jar: TestFile,
ordering: Option<i32>,
modify_json: Option<json_patch::Patch>,
) -> VersionCreationRequestData {
let mut json_data = get_public_version_creation_data_json(version_number, &version_jar);
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(),
@@ -55,9 +65,10 @@ pub fn get_public_version_creation_data(
pub fn get_public_version_creation_data_json(
version_number: &str,
ordering: Option<i32>,
version_jar: &TestFile,
) -> serde_json::Value {
json!({
let mut j = json!({
"file_parts": [version_jar.filename()],
"version_number": version_number,
"version_title": "start",
@@ -66,7 +77,11 @@ pub fn get_public_version_creation_data_json(
"release_channel": "release",
"loaders": ["fabric"],
"featured": true
})
});
if let Some(ordering) = ordering {
j["ordering"] = json!(ordering);
}
j
}
pub fn get_public_project_creation_data_json(
@@ -74,7 +89,7 @@ pub fn get_public_project_creation_data_json(
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)])
json!([get_public_version_creation_data_json("1.2.3", None, jar)])
} else {
json!([])
};

View File

@@ -2,16 +2,23 @@ use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use labrinth::routes::v2::tags::{CategoryData, GameVersionQueryData, LoaderData};
use crate::common::database::ADMIN_USER_PAT;
use crate::common::{
api_common::{
models::{CommonCategoryData, CommonLoaderData},
Api, ApiTags,
},
database::ADMIN_USER_PAT,
};
use super::ApiV2;
impl ApiV2 {
// Tag gets do not include PAT, as they are public.
// TODO: Tag gets do not include PAT, as they are public.
pub async fn get_side_types(&self) -> ServiceResponse {
impl ApiV2 {
async fn get_side_types(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v2/tag/side_type")
.append_header(("Authorization", ADMIN_USER_PAT))
@@ -25,34 +32,6 @@ impl ApiV2 {
test::read_body_json(resp).await
}
pub async fn get_loaders(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v2/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("/v2/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_game_versions(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v2/tag/game_version")
@@ -66,4 +45,47 @@ impl ApiV2 {
assert_eq!(resp.status(), 200);
test::read_body_json(resp).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_deserialized(&self) -> Vec<CategoryData> {
let resp = self.get_categories().await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
}
#[async_trait(?Send)]
impl ApiTags for ApiV2 {
async fn get_loaders(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v2/tag/loader")
.append_header(("Authorization", 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_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
async fn get_categories(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v2/tag/category")
.append_header(("Authorization", 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_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
}

View File

@@ -1,17 +1,22 @@
use actix_http::StatusCode;
use actix_web::{dev::ServiceResponse, test};
use labrinth::models::{
notifications::Notification,
teams::{OrganizationPermissions, ProjectPermissions, TeamMember},
};
use async_trait::async_trait;
use labrinth::models::teams::{OrganizationPermissions, ProjectPermissions};
use serde_json::json;
use crate::common::asserts::assert_status;
use crate::common::{
api_common::{
models::{CommonNotification, CommonTeamMember},
Api, ApiTeams,
},
asserts::assert_status,
};
use super::ApiV2;
impl ApiV2 {
pub async fn get_team_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
#[async_trait(?Send)]
impl ApiTeams for ApiV2 {
async fn get_team_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v2/team/{id_or_title}/members"))
.append_header(("Authorization", pat))
@@ -19,17 +24,17 @@ impl ApiV2 {
self.call(req).await
}
pub async fn get_team_members_deserialized(
async fn get_team_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
) -> Vec<CommonTeamMember> {
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 {
async fn get_project_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v2/project/{id_or_title}/members"))
.append_header(("Authorization", pat))
@@ -37,17 +42,17 @@ impl ApiV2 {
self.call(req).await
}
pub async fn get_project_members_deserialized(
async fn get_project_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
) -> Vec<CommonTeamMember> {
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 {
async fn get_organization_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v2/organization/{id_or_title}/members"))
.append_header(("Authorization", pat))
@@ -55,17 +60,17 @@ impl ApiV2 {
self.call(req).await
}
pub async fn get_organization_members_deserialized(
async fn get_organization_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
) -> Vec<CommonTeamMember> {
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 {
async fn join_team(&self, team_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::post()
.uri(&format!("/v2/team/{team_id}/join"))
.append_header(("Authorization", pat))
@@ -73,12 +78,7 @@ impl ApiV2 {
self.call(req).await
}
pub async fn remove_from_team(
&self,
team_id: &str,
user_id: &str,
pat: &str,
) -> ServiceResponse {
async fn remove_from_team(&self, team_id: &str, user_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v2/team/{team_id}/members/{user_id}"))
.append_header(("Authorization", pat))
@@ -86,7 +86,7 @@ impl ApiV2 {
self.call(req).await
}
pub async fn edit_team_member(
async fn edit_team_member(
&self,
team_id: &str,
user_id: &str,
@@ -101,7 +101,7 @@ impl ApiV2 {
self.call(req).await
}
pub async fn transfer_team_ownership(
async fn transfer_team_ownership(
&self,
team_id: &str,
user_id: &str,
@@ -117,7 +117,7 @@ impl ApiV2 {
self.call(req).await
}
pub async fn get_user_notifications(&self, user_id: &str, pat: &str) -> ServiceResponse {
async fn get_user_notifications(&self, user_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v2/user/{user_id}/notifications"))
.append_header(("Authorization", pat))
@@ -125,28 +125,25 @@ impl ApiV2 {
self.call(req).await
}
pub async fn get_user_notifications_deserialized(
async fn get_user_notifications_deserialized_common(
&self,
user_id: &str,
pat: &str,
) -> Vec<Notification> {
) -> Vec<CommonNotification> {
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 {
async fn mark_notification_read(&self, notification_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v2/notification/{notification_id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn add_user_to_team(
async fn add_user_to_team(
&self,
team_id: &str,
user_id: &str,
@@ -166,7 +163,7 @@ impl ApiV2 {
self.call(req).await
}
pub async fn delete_notification(&self, notification_id: &str, pat: &str) -> ServiceResponse {
async fn delete_notification(&self, notification_id: &str, pat: &str) -> ServiceResponse {
let req = test::TestRequest::delete()
.uri(&format!("/v2/notification/{notification_id}"))
.append_header(("Authorization", pat))

View File

@@ -1,101 +1,39 @@
use std::collections::HashMap;
use super::{request_data::get_public_version_creation_data, ApiV2};
use crate::common::{
api_common::{models::CommonVersion, Api, ApiVersion},
asserts::assert_status,
dummy_data::TestFile,
};
use actix_http::{header::AUTHORIZATION, StatusCode};
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use labrinth::{
models::{projects::VersionType, v2::projects::LegacyVersion},
models::{
projects::{ProjectId, VersionType},
v2::projects::LegacyVersion,
},
routes::v2::version_file::FileUpdateData,
util::actix::AppendsMultipart,
};
use serde_json::json;
use crate::common::asserts::assert_status;
use super::{request_data::VersionCreationRequestData, ApiV2};
pub fn url_encode_json_serialized_vec(elements: &[String]) -> String {
let serialized = serde_json::to_string(&elements).unwrap();
urlencoding::encode(&serialized).to_string()
}
impl ApiV2 {
pub async fn add_public_version(
&self,
creation_data: VersionCreationRequestData,
pat: &str,
) -> LegacyVersion {
// Add a project.
let req = TestRequest::post()
.uri("/v2/version")
.append_header(("Authorization", pat))
.set_multipart(creation_data.segment_data)
.to_request();
let resp = self.call(req).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();
// // Approve as a moderator.
// let req = TestRequest::patch()
// .uri(&format!("/v2/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);
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!("/v2/version/{id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
pub async fn get_version_deserialized(&self, id: &str, pat: &str) -> LegacyVersion {
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!("/v2/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!("/v2/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,
@@ -107,23 +45,6 @@ impl ApiV2 {
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("/v2/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],
@@ -135,91 +56,6 @@ impl ApiV2 {
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 req = test::TestRequest::post()
.uri(&format!(
"/v2/version_file/{hash}/update?algorithm={algorithm}"
))
.append_header(("Authorization", pat))
.set_json(json!({
"loaders": loaders,
"game_versions": game_versions,
"version_types": version_types,
}))
.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,
) -> LegacyVersion {
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 req = test::TestRequest::post()
.uri("/v2/version_files/update")
.append_header(("Authorization", pat))
.set_json(json!({
"algorithm": algorithm,
"hashes": hashes,
"loaders": loaders,
"game_versions": game_versions,
"version_types": version_types,
}))
.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, LegacyVersion> {
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,
@@ -247,10 +83,228 @@ impl ApiV2 {
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
}
#[async_trait(?Send)]
impl ApiVersion for ApiV2 {
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: &str,
) -> ServiceResponse {
let creation_data = get_public_version_creation_data(
project_id,
version_number,
version_jar,
ordering,
modify_json,
);
// Add a project.
let req = TestRequest::post()
.uri("/v2/version")
.append_header(("Authorization", 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: &str,
) -> CommonVersion {
let resp = self
.add_public_version(
project_id,
version_number,
version_jar,
ordering,
modify_json,
pat,
)
.await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
async fn get_version(&self, id: &str, pat: &str) -> ServiceResponse {
let req = TestRequest::get()
.uri(&format!("/v2/version/{id}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
async fn get_version_deserialized_common(&self, id: &str, pat: &str) -> CommonVersion {
let resp = self.get_version(id, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
async fn edit_version(
&self,
version_id: &str,
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::patch()
.uri(&format!("/v2/version/{version_id}"))
.append_header(("Authorization", pat))
.set_json(patch)
.to_request();
self.call(req).await
}
async fn get_version_from_hash(
&self,
hash: &str,
algorithm: &str,
pat: &str,
) -> ServiceResponse {
let req = test::TestRequest::get()
.uri(&format!("/v2/version_file/{hash}?algorithm={algorithm}"))
.append_header(("Authorization", pat))
.to_request();
self.call(req).await
}
async fn get_version_from_hash_deserialized_common(
&self,
hash: &str,
algorithm: &str,
pat: &str,
) -> CommonVersion {
let resp = self.get_version_from_hash(hash, algorithm, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
async fn get_versions_from_hashes(
&self,
hashes: &[&str],
algorithm: &str,
pat: &str,
) -> ServiceResponse {
let req = TestRequest::post()
.uri("/v2/version_files")
.append_header(("Authorization", 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: &str,
) -> HashMap<String, CommonVersion> {
let resp = self.get_versions_from_hashes(hashes, algorithm, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
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 req = test::TestRequest::post()
.uri(&format!(
"/v2/version_file/{hash}/update?algorithm={algorithm}"
))
.append_header(("Authorization", pat))
.set_json(json!({
"loaders": loaders,
"game_versions": game_versions,
"version_types": version_types,
}))
.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: &str,
) -> CommonVersion {
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
}
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 req = test::TestRequest::post()
.uri("/v2/version_files/update")
.append_header(("Authorization", pat))
.set_json(json!({
"algorithm": algorithm,
"hashes": hashes,
"loaders": loaders,
"game_versions": game_versions,
"version_types": version_types,
}))
.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: &str,
) -> HashMap<String, CommonVersion> {
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
}
// TODO: Not all fields are tested currently in the V2 tests, only the v2-v3 relevant ones are
#[allow(clippy::too_many_arguments)]
pub async fn get_project_versions(
async fn get_project_versions(
&self,
project_id_slug: &str,
game_versions: Option<Vec<String>>,
@@ -300,7 +354,7 @@ impl ApiV2 {
}
#[allow(clippy::too_many_arguments)]
pub async fn get_project_versions_deserialized(
async fn get_project_versions_deserialized_common(
&self,
slug: &str,
game_versions: Option<Vec<String>>,
@@ -310,7 +364,7 @@ impl ApiV2 {
limit: Option<usize>,
offset: Option<usize>,
pat: &str,
) -> Vec<LegacyVersion> {
) -> Vec<CommonVersion> {
let resp = self
.get_project_versions(
slug,
@@ -327,66 +381,7 @@ impl ApiV2 {
test::read_body_json(resp).await
}
// TODO: remove redundancy in these functions- some are essentially repeats
pub async fn create_default_version(
&self,
project_id: &str,
ordering: Option<i32>,
pat: &str,
) -> LegacyVersion {
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"] ,
"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("/v2/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<LegacyVersion> {
let ids = url_encode_json_serialized_vec(&version_ids);
let request = test::TestRequest::get()
.uri(&format!("/v2/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(
async fn edit_version_ordering(
&self,
version_id: &str,
ordering: Option<i32>,
@@ -403,4 +398,23 @@ impl ApiV2 {
.to_request();
self.call(request).await
}
async fn get_versions(&self, version_ids: Vec<String>, pat: &str) -> ServiceResponse {
let ids = url_encode_json_serialized_vec(&version_ids);
let request = test::TestRequest::get()
.uri(&format!("/v2/versions?ids={}", ids))
.append_header((AUTHORIZATION, pat))
.to_request();
self.call(request).await
}
async fn get_versions_deserialized_common(
&self,
version_ids: Vec<String>,
pat: &str,
) -> Vec<CommonVersion> {
let resp = self.get_versions(version_ids, pat).await;
assert_status(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}

View File

@@ -1,7 +1,12 @@
#![allow(dead_code)]
use super::environment::LocalService;
use actix_web::dev::ServiceResponse;
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 oauth;
@@ -18,12 +23,23 @@ pub struct ApiV3 {
pub test_app: Rc<dyn LocalService>,
}
impl ApiV3 {
pub async fn call(&self, req: actix_http::Request) -> ServiceResponse {
#[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()
}
pub async fn reset_search_index(&self) -> ServiceResponse {
async fn reset_search_index(&self) -> ServiceResponse {
let req = actix_web::test::TestRequest::post()
.uri("/v3/admin/_force_reindex")
.append_header((

View File

@@ -10,7 +10,7 @@ use labrinth::auth::oauth::{
};
use reqwest::header::{AUTHORIZATION, LOCATION};
use crate::common::asserts::assert_status;
use crate::common::{api_common::Api, asserts::assert_status};
use super::ApiV3;

View File

@@ -13,7 +13,7 @@ use labrinth::{
use reqwest::header::AUTHORIZATION;
use serde_json::json;
use crate::common::asserts::assert_status;
use crate::common::{api_common::Api, asserts::assert_status};
use super::ApiV3;

View File

@@ -6,6 +6,8 @@ use bytes::Bytes;
use labrinth::models::{organizations::Organization, v3::projects::Project};
use serde_json::json;
use crate::common::api_common::Api;
use super::{request_data::ImageData, ApiV3};
impl ApiV3 {

View File

@@ -5,29 +5,36 @@ use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use labrinth::{
models::v3::projects::{Project, Version},
search::SearchResults,
util::actix::AppendsMultipart,
};
use labrinth::{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,
use crate::common::{
api_common::{
models::{CommonImageData, CommonProject, CommonVersion},
Api, ApiProject,
},
asserts::assert_status,
database::MOD_USER_PAT,
dummy_data::TestFile,
};
impl ApiV3 {
pub async fn add_public_project(
use super::{request_data::get_public_project_creation_data, ApiV3};
#[async_trait(?Send)]
impl ApiProject for ApiV3 {
async fn add_public_project(
&self,
creation_data: ProjectCreationRequestData,
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
pat: &str,
) -> (Project, Vec<Version>) {
) -> (CommonProject, Vec<CommonVersion>) {
let creation_data = get_public_project_creation_data(slug, version_jar, modify_json);
// Add a project.
let req = TestRequest::post()
.uri("/v3/project")
@@ -50,9 +57,8 @@ impl ApiV3 {
let resp = self.call(req).await;
assert_status(&resp, StatusCode::NO_CONTENT);
let project = self
.get_project_deserialized(&creation_data.slug, pat)
.await;
let project = self.get_project(&creation_data.slug, pat).await;
let project = test::read_body_json(project).await;
// Get project's versions
let req = TestRequest::get()
@@ -60,12 +66,12 @@ impl ApiV3 {
.append_header(("Authorization", pat))
.to_request();
let resp = self.call(req).await;
let versions: Vec<Version> = test::read_body_json(resp).await;
let versions: Vec<CommonVersion> = test::read_body_json(resp).await;
(project, versions)
}
pub async fn remove_project(&self, project_slug_or_id: &str, pat: &str) -> ServiceResponse {
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))
@@ -75,20 +81,21 @@ impl ApiV3 {
resp
}
pub async fn get_project(&self, id_or_slug: &str, pat: &str) -> ServiceResponse {
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 {
async fn get_project_deserialized_common(&self, id_or_slug: &str, pat: &str) -> CommonProject {
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 {
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))
@@ -96,17 +103,17 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_user_projects_deserialized(
async fn get_user_projects_deserialized_common(
&self,
user_id_or_username: &str,
pat: &str,
) -> Vec<Project> {
) -> Vec<CommonProject> {
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(
async fn edit_project(
&self,
id_or_slug: &str,
patch: serde_json::Value,
@@ -121,14 +128,14 @@ impl ApiV3 {
self.call(req).await
}
pub async fn edit_project_bulk(
async fn edit_project_bulk(
&self,
ids_or_slugs: impl IntoIterator<Item = &str>,
ids_or_slugs: &[&str],
patch: serde_json::Value,
pat: &str,
) -> ServiceResponse {
let projects_str = ids_or_slugs
.into_iter()
.iter()
.map(|s| format!("\"{}\"", s))
.collect::<Vec<_>>()
.join(",");
@@ -144,10 +151,10 @@ impl ApiV3 {
self.call(req).await
}
pub async fn edit_project_icon(
async fn edit_project_icon(
&self,
id_or_slug: &str,
icon: Option<ImageData>,
icon: Option<CommonImageData>,
pat: &str,
) -> ServiceResponse {
if let Some(icon) = icon {
@@ -173,7 +180,7 @@ impl ApiV3 {
}
}
pub async fn search_deserialized(
async fn search_deserialized_common(
&self,
query: Option<&str>,
facets: Option<serde_json::Value>,
@@ -200,7 +207,9 @@ impl ApiV3 {
assert_eq!(status, 200);
test::read_body_json(resp).await
}
}
impl ApiV3 {
pub async fn get_analytics_revenue(
&self,
id_or_slugs: Vec<&str>,

View File

@@ -28,8 +28,12 @@ pub struct ImageData {
pub fn get_public_project_creation_data(
slug: &str,
version_jar: Option<TestFile>,
modify_json: Option<json_patch::Patch>,
) -> ProjectCreationRequestData {
let json_data = get_public_project_creation_data_json(slug, version_jar.as_ref());
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(),
@@ -42,14 +46,16 @@ 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<impl FnOnce(&mut serde_json::Value)>,
modify_json: Option<json_patch::Patch>,
) -> VersionCreationRequestData {
let mut json_data = get_public_version_creation_data_json(version_number, &version_jar);
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 {
modify_json(&mut json_data);
json_patch::patch(&mut json_data, &modify_json).unwrap();
}
let multipart_data = get_public_creation_data_multipart(&json_data, Some(&version_jar));
@@ -62,6 +68,7 @@ pub fn get_public_version_creation_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";
@@ -82,6 +89,9 @@ pub fn get_public_version_creation_data_json(
if is_modpack {
j["mrpack_loaders"] = json!(["fabric"]);
}
if let Some(ordering) = ordering {
j["ordering"] = json!(ordering);
}
j
}
@@ -90,7 +100,7 @@ pub fn get_public_project_creation_data_json(
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)])
json!([get_public_version_creation_data_json("1.2.3", None, jar)])
} else {
json!([])
};

View File

@@ -2,18 +2,23 @@ use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use labrinth::database::models::loader_fields::LoaderFieldEnumValue;
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 crate::common::{
api_common::{
models::{CommonCategoryData, CommonLoaderData},
Api, ApiTags,
},
database::ADMIN_USER_PAT,
};
use super::ApiV3;
impl ApiV3 {
pub async fn get_loaders(&self) -> ServiceResponse {
#[async_trait(?Send)]
impl ApiTags for ApiV3 {
async fn get_loaders(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/tag/loader")
.append_header(("Authorization", ADMIN_USER_PAT))
@@ -21,13 +26,13 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_loaders_deserialized(&self) -> Vec<LoaderData> {
async fn get_loaders_deserialized_common(&self) -> Vec<CommonLoaderData> {
let resp = self.get_loaders().await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
pub async fn get_categories(&self) -> ServiceResponse {
async fn get_categories(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/tag/category")
.append_header(("Authorization", ADMIN_USER_PAT))
@@ -35,12 +40,14 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_categories_deserialized(&self) -> Vec<CategoryData> {
async fn get_categories_deserialized_common(&self) -> Vec<CommonCategoryData> {
let resp = self.get_categories().await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
}
impl ApiV3 {
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))
@@ -59,7 +66,7 @@ impl ApiV3 {
}
// TODO: fold this into v3 API of other v3 testing PR
pub async fn get_games(&self) -> ServiceResponse {
async fn get_games(&self) -> ServiceResponse {
let req = TestRequest::get()
.uri("/v3/games")
.append_header(("Authorization", ADMIN_USER_PAT))

View File

@@ -1,17 +1,22 @@
use actix_http::StatusCode;
use actix_web::{dev::ServiceResponse, test};
use labrinth::models::{
notifications::Notification,
teams::{OrganizationPermissions, ProjectPermissions, TeamMember},
};
use async_trait::async_trait;
use labrinth::models::teams::{OrganizationPermissions, ProjectPermissions};
use serde_json::json;
use crate::common::asserts::assert_status;
use crate::common::{
api_common::{
models::{CommonNotification, CommonTeamMember},
Api, ApiTeams,
},
asserts::assert_status,
};
use super::ApiV3;
impl ApiV3 {
pub async fn get_team_members(&self, id_or_title: &str, pat: &str) -> ServiceResponse {
#[async_trait(?Send)]
impl ApiTeams for ApiV3 {
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))
@@ -19,17 +24,17 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_team_members_deserialized(
async fn get_team_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
) -> Vec<CommonTeamMember> {
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 {
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))
@@ -37,17 +42,17 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_project_members_deserialized(
async fn get_project_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
) -> Vec<CommonTeamMember> {
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 {
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))
@@ -55,17 +60,17 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_organization_members_deserialized(
async fn get_organization_members_deserialized_common(
&self,
id_or_title: &str,
pat: &str,
) -> Vec<TeamMember> {
) -> Vec<CommonTeamMember> {
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 {
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))
@@ -73,12 +78,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn remove_from_team(
&self,
team_id: &str,
user_id: &str,
pat: &str,
) -> ServiceResponse {
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))
@@ -86,7 +86,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn edit_team_member(
async fn edit_team_member(
&self,
team_id: &str,
user_id: &str,
@@ -101,7 +101,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn transfer_team_ownership(
async fn transfer_team_ownership(
&self,
team_id: &str,
user_id: &str,
@@ -117,7 +117,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_user_notifications(&self, user_id: &str, pat: &str) -> ServiceResponse {
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))
@@ -125,28 +125,24 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_user_notifications_deserialized(
async fn get_user_notifications_deserialized_common(
&self,
user_id: &str,
pat: &str,
) -> Vec<Notification> {
) -> Vec<CommonNotification> {
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 {
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(
async fn add_user_to_team(
&self,
team_id: &str,
user_id: &str,
@@ -166,7 +162,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn delete_notification(&self, notification_id: &str, pat: &str) -> ServiceResponse {
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))

View File

@@ -1,59 +1,58 @@
use std::collections::HashMap;
use super::{request_data::get_public_version_creation_data, ApiV3};
use crate::common::{
api_common::{models::CommonVersion, Api, ApiVersion},
asserts::assert_status,
dummy_data::TestFile,
};
use actix_http::{header::AUTHORIZATION, StatusCode};
use actix_web::{
dev::ServiceResponse,
test::{self, TestRequest},
};
use async_trait::async_trait;
use labrinth::{
models::{projects::VersionType, v3::projects::Version},
models::{
projects::{ProjectId, 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,
project_id: ProjectId,
version_number: &str,
version_jar: TestFile,
ordering: Option<i32>,
modify_json: Option<json_patch::Patch>,
pat: &str,
) -> Version {
let resp = self.add_public_version(creation_data, pat).await;
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();
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
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: &str) -> Version {
@@ -62,7 +61,101 @@ impl ApiV3 {
test::read_body_json(resp).await
}
pub async fn edit_version(
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
}
}
#[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: &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_header(("Authorization", 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: &str,
) -> CommonVersion {
let resp = self
.add_public_version(
project_id,
version_number,
version_jar,
ordering,
modify_json,
pat,
)
.await;
assert_status(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
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
}
async fn get_version_deserialized_common(&self, id: &str, pat: &str) -> CommonVersion {
let resp = self.get_version(id, pat).await;
assert_eq!(resp.status(), 200);
test::read_body_json(resp).await
}
async fn edit_version(
&self,
version_id: &str,
patch: serde_json::Value,
@@ -77,7 +170,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_version_from_hash(
async fn get_version_from_hash(
&self,
hash: &str,
algorithm: &str,
@@ -90,18 +183,18 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_version_from_hash_deserialized(
async fn get_version_from_hash_deserialized_common(
&self,
hash: &str,
algorithm: &str,
pat: &str,
) -> Version {
) -> CommonVersion {
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(
async fn get_versions_from_hashes(
&self,
hashes: &[&str],
algorithm: &str,
@@ -118,18 +211,18 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_versions_from_hashes_deserialized(
async fn get_versions_from_hashes_deserialized_common(
&self,
hashes: &[&str],
algorithm: &str,
pat: &str,
) -> HashMap<String, Version> {
) -> HashMap<String, CommonVersion> {
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(
async fn get_update_from_hash(
&self,
hash: &str,
algorithm: &str,
@@ -161,7 +254,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn get_update_from_hash_deserialized(
async fn get_update_from_hash_deserialized_common(
&self,
hash: &str,
algorithm: &str,
@@ -169,7 +262,7 @@ impl ApiV3 {
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: &str,
) -> Version {
) -> CommonVersion {
let resp = self
.get_update_from_hash(hash, algorithm, loaders, game_versions, version_types, pat)
.await;
@@ -177,7 +270,7 @@ impl ApiV3 {
test::read_body_json(resp).await
}
pub async fn update_files(
async fn update_files(
&self,
algorithm: &str,
hashes: Vec<String>,
@@ -210,7 +303,7 @@ impl ApiV3 {
self.call(req).await
}
pub async fn update_files_deserialized(
async fn update_files_deserialized_common(
&self,
algorithm: &str,
hashes: Vec<String>,
@@ -218,7 +311,7 @@ impl ApiV3 {
game_versions: Option<Vec<String>>,
version_types: Option<Vec<String>>,
pat: &str,
) -> HashMap<String, Version> {
) -> HashMap<String, CommonVersion> {
let resp = self
.update_files(
algorithm,
@@ -233,37 +326,9 @@ impl ApiV3 {
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(
async fn get_project_versions(
&self,
project_id_slug: &str,
game_versions: Option<Vec<String>>,
@@ -313,7 +378,7 @@ impl ApiV3 {
}
#[allow(clippy::too_many_arguments)]
pub async fn get_project_versions_deserialized(
async fn get_project_versions_deserialized_common(
&self,
slug: &str,
game_versions: Option<Vec<String>>,
@@ -323,7 +388,7 @@ impl ApiV3 {
limit: Option<usize>,
offset: Option<usize>,
pat: &str,
) -> Vec<Version> {
) -> Vec<CommonVersion> {
let resp = self
.get_project_versions(
slug,
@@ -341,68 +406,7 @@ impl ApiV3 {
}
// 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(
async fn edit_version_ordering(
&self,
version_id: &str,
ordering: Option<i32>,
@@ -419,4 +423,23 @@ impl ApiV3 {
.to_request();
self.call(request).await
}
async fn get_versions(&self, version_ids: Vec<String>, pat: &str) -> ServiceResponse {
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();
self.call(request).await
}
async fn get_versions_deserialized_common(
&self,
version_ids: Vec<String>,
pat: &str,
) -> Vec<CommonVersion> {
let resp = self.get_versions(version_ids, pat).await;
assert_status(&resp, StatusCode::OK);
test::read_body_json(resp).await
}
}

View File

@@ -4,6 +4,8 @@ use crate::common::get_json_val_str;
use itertools::Itertools;
use labrinth::models::v3::projects::Version;
use super::api_common::models::CommonVersion;
pub fn assert_status(response: &actix_web::dev::ServiceResponse, status: actix_http::StatusCode) {
assert_eq!(response.status(), status, "{:#?}", response.response());
}
@@ -16,6 +18,14 @@ pub fn assert_version_ids(versions: &[Version], expected_ids: Vec<String>) {
assert_eq!(version_ids, expected_ids);
}
pub fn assert_common_version_ids(versions: &[CommonVersion], expected_ids: Vec<String>) {
let version_ids = versions
.iter()
.map(|v| get_json_val_str(v.id))
.collect_vec();
assert_eq!(version_ids, expected_ids);
}
pub fn assert_any_status_except(
response: &actix_web::dev::ServiceResponse,
status: actix_http::StatusCode,

View File

@@ -7,7 +7,7 @@ use url::Url;
use crate::common::{dummy_data, environment::TestEnvironment};
use super::dummy_data::DUMMY_DATA_UPDATE;
use super::{api_v3::ApiV3, dummy_data::DUMMY_DATA_UPDATE};
// The dummy test database adds a fair bit of 'dummy' data to test with.
// Some constants are used to refer to that data, and are described here.
@@ -168,13 +168,20 @@ impl TemporaryDatabase {
if !dummy_data_exists {
// Add dummy data
let temporary_test_env = TestEnvironment::build_with_db(TemporaryDatabase {
pool: pool.clone(),
database_name: TEMPLATE_DATABASE_NAME.to_string(),
redis_pool: RedisPool::new(Some(generate_random_name("test_template_"))),
})
let temporary_test_env =
TestEnvironment::<ApiV3>::build_with_db(TemporaryDatabase {
pool: pool.clone(),
database_name: TEMPLATE_DATABASE_NAME.to_string(),
redis_pool: RedisPool::new(Some(generate_random_name(
"test_template_",
))),
})
.await;
dummy_data::add_dummy_data(
&temporary_test_env.setup_api,
temporary_test_env.db.clone(),
)
.await;
dummy_data::add_dummy_data(&temporary_test_env).await;
temporary_test_env.db.pool.close().await;
}
pool.close().await;

View File

@@ -4,19 +4,23 @@ use std::io::{Cursor, Write};
use actix_http::StatusCode;
use actix_web::test::{self, TestRequest};
use labrinth::models::{
oauth_clients::OAuthClient,
organizations::Organization,
pats::Scopes,
v3::projects::{Project, Version},
oauth_clients::OAuthClient, organizations::Organization, pats::Scopes, projects::ProjectId,
};
use serde_json::json;
use sqlx::Executor;
use zip::{write::FileOptions, CompressionMethod, ZipWriter};
use crate::common::database::USER_USER_PAT;
use crate::common::{api_common::Api, database::USER_USER_PAT};
use labrinth::util::actix::{AppendsMultipart, MultipartSegment, MultipartSegmentData};
use super::{api_v3::request_data::get_public_project_creation_data, environment::TestEnvironment};
use super::{
api_common::{
models::{CommonProject, CommonVersion},
ApiProject,
},
api_v3::ApiV3,
database::TemporaryDatabase,
};
use super::{asserts::assert_status, database::USER_USER_ID, get_json_val_str};
@@ -170,10 +174,10 @@ pub struct DummyData {
impl DummyData {
pub fn new(
project_alpha: Project,
project_alpha_version: Version,
project_beta: Project,
project_beta_version: Version,
project_alpha: CommonProject,
project_alpha_version: CommonVersion,
project_beta: CommonProject,
project_beta_version: CommonVersion,
organization_zeta: Organization,
oauth_client_alpha: OAuthClient,
) -> Self {
@@ -182,6 +186,7 @@ impl DummyData {
team_id: project_alpha.team.to_string(),
project_id: project_alpha.id.to_string(),
project_slug: project_alpha.slug.unwrap(),
project_id_parsed: project_alpha.id,
version_id: project_alpha_version.id.to_string(),
thread_id: project_alpha.thread_id.to_string(),
file_hash: project_alpha_version.files[0].hashes["sha1"].clone(),
@@ -191,6 +196,7 @@ impl DummyData {
team_id: project_beta.team.to_string(),
project_id: project_beta.id.to_string(),
project_slug: project_beta.slug.unwrap(),
project_id_parsed: project_beta.id,
version_id: project_beta_version.id.to_string(),
thread_id: project_beta.thread_id.to_string(),
file_hash: project_beta_version.files[0].hashes["sha1"].clone(),
@@ -220,6 +226,7 @@ impl DummyData {
pub struct DummyProjectAlpha {
pub project_id: String,
pub project_slug: String,
pub project_id_parsed: ProjectId,
pub version_id: String,
pub thread_id: String,
pub file_hash: String,
@@ -230,6 +237,7 @@ pub struct DummyProjectAlpha {
pub struct DummyProjectBeta {
pub project_id: String,
pub project_slug: String,
pub project_id_parsed: ProjectId,
pub version_id: String,
pub thread_id: String,
pub file_hash: String,
@@ -250,9 +258,9 @@ pub struct DummyOAuthClientAlpha {
pub valid_redirect_uri: String,
}
pub async fn add_dummy_data(test_env: &TestEnvironment) -> DummyData {
pub async fn add_dummy_data(api: &ApiV3, db: TemporaryDatabase) -> DummyData {
// Adds basic dummy data to the database directly with sql (user, pats)
let pool = &test_env.db.pool.clone();
let pool = &db.pool.clone();
pool.execute(
include_str!("../files/dummy_data.sql")
@@ -262,12 +270,12 @@ pub async fn add_dummy_data(test_env: &TestEnvironment) -> DummyData {
.await
.unwrap();
let (alpha_project, alpha_version) = add_project_alpha(test_env).await;
let (beta_project, beta_version) = add_project_beta(test_env).await;
let (alpha_project, alpha_version) = add_project_alpha(api).await;
let (beta_project, beta_version) = add_project_beta(api).await;
let zeta_organization = add_organization_zeta(test_env).await;
let zeta_organization = add_organization_zeta(api).await;
let oauth_client_alpha = get_oauth_client_alpha(test_env).await;
let oauth_client_alpha = get_oauth_client_alpha(api).await;
sqlx::query("INSERT INTO dummy_data (update_id) VALUES ($1)")
.bind(DUMMY_DATA_UPDATE)
@@ -285,13 +293,13 @@ pub async fn add_dummy_data(test_env: &TestEnvironment) -> DummyData {
)
}
pub async fn get_dummy_data(test_env: &TestEnvironment) -> DummyData {
let (alpha_project, alpha_version) = get_project_alpha(test_env).await;
let (beta_project, beta_version) = get_project_beta(test_env).await;
pub async fn get_dummy_data(api: &ApiV3) -> DummyData {
let (alpha_project, alpha_version) = get_project_alpha(api).await;
let (beta_project, beta_version) = get_project_beta(api).await;
let zeta_organization = get_organization_zeta(test_env).await;
let zeta_organization = get_organization_zeta(api).await;
let oauth_client_alpha = get_oauth_client_alpha(test_env).await;
let oauth_client_alpha = get_oauth_client_alpha(api).await;
DummyData::new(
alpha_project,
@@ -303,18 +311,19 @@ pub async fn get_dummy_data(test_env: &TestEnvironment) -> DummyData {
)
}
pub async fn add_project_alpha(test_env: &TestEnvironment) -> (Project, Version) {
let (project, versions) = test_env
.v3
pub async fn add_project_alpha(api: &ApiV3) -> (CommonProject, CommonVersion) {
let (project, versions) = api
.add_public_project(
get_public_project_creation_data("alpha", Some(TestFile::DummyProjectAlpha)),
"alpha",
Some(TestFile::DummyProjectAlpha),
None,
USER_USER_PAT,
)
.await;
(project, versions.into_iter().next().unwrap())
}
pub async fn add_project_beta(test_env: &TestEnvironment) -> (Project, Version) {
pub async fn add_project_beta(api: &ApiV3) -> (CommonProject, CommonVersion) {
// Adds dummy data to the database with sqlx (projects, versions, threads)
// Generate test project data.
let jar = TestFile::DummyProjectBeta;
@@ -367,13 +376,13 @@ pub async fn add_project_beta(test_env: &TestEnvironment) -> (Project, Version)
.append_header(("Authorization", USER_USER_PAT))
.set_multipart(vec![json_segment.clone(), file_segment.clone()])
.to_request();
let resp = test_env.call(req).await;
let resp = api.call(req).await;
assert_eq!(resp.status(), 200);
get_project_beta(test_env).await
get_project_beta(api).await
}
pub async fn add_organization_zeta(test_env: &TestEnvironment) -> Organization {
pub async fn add_organization_zeta(api: &ApiV3) -> Organization {
// Add an organzation.
let req = TestRequest::post()
.uri("/v3/organization")
@@ -383,73 +392,72 @@ pub async fn add_organization_zeta(test_env: &TestEnvironment) -> Organization {
"description": "A dummy organization for testing with."
}))
.to_request();
let resp = test_env.call(req).await;
let resp = api.call(req).await;
assert_eq!(resp.status(), 200);
get_organization_zeta(test_env).await
get_organization_zeta(api).await
}
pub async fn get_project_alpha(test_env: &TestEnvironment) -> (Project, Version) {
pub async fn get_project_alpha(api: &ApiV3) -> (CommonProject, CommonVersion) {
// Get project
let req = TestRequest::get()
.uri("/v3/project/alpha")
.append_header(("Authorization", USER_USER_PAT))
.to_request();
let resp = test_env.call(req).await;
let project: Project = test::read_body_json(resp).await;
let resp = api.call(req).await;
let project: CommonProject = test::read_body_json(resp).await;
// Get project's versions
let req = TestRequest::get()
.uri("/v3/project/alpha/version")
.append_header(("Authorization", USER_USER_PAT))
.to_request();
let resp = test_env.call(req).await;
let versions: Vec<Version> = test::read_body_json(resp).await;
let resp = api.call(req).await;
let versions: Vec<CommonVersion> = test::read_body_json(resp).await;
let version = versions.into_iter().next().unwrap();
(project, version)
}
pub async fn get_project_beta(test_env: &TestEnvironment) -> (Project, Version) {
pub async fn get_project_beta(api: &ApiV3) -> (CommonProject, CommonVersion) {
// Get project
let req = TestRequest::get()
.uri("/v3/project/beta")
.append_header(("Authorization", USER_USER_PAT))
.to_request();
let resp = test_env.call(req).await;
let resp = api.call(req).await;
assert_status(&resp, StatusCode::OK);
let project: serde_json::Value = test::read_body_json(resp).await;
let project: Project = serde_json::from_value(project).unwrap();
let project: CommonProject = serde_json::from_value(project).unwrap();
// Get project's versions
let req = TestRequest::get()
.uri("/v3/project/beta/version")
.append_header(("Authorization", USER_USER_PAT))
.to_request();
let resp = test_env.call(req).await;
let resp = api.call(req).await;
assert_status(&resp, StatusCode::OK);
let versions: Vec<Version> = test::read_body_json(resp).await;
let versions: Vec<CommonVersion> = test::read_body_json(resp).await;
let version = versions.into_iter().next().unwrap();
(project, version)
}
pub async fn get_organization_zeta(test_env: &TestEnvironment) -> Organization {
pub async fn get_organization_zeta(api: &ApiV3) -> Organization {
// Get organization
let req = TestRequest::get()
.uri("/v3/organization/zeta")
.append_header(("Authorization", USER_USER_PAT))
.to_request();
let resp = test_env.call(req).await;
let resp = api.call(req).await;
let organization: Organization = test::read_body_json(resp).await;
organization
}
pub async fn get_oauth_client_alpha(test_env: &TestEnvironment) -> OAuthClient {
let oauth_clients = test_env
.v3
pub async fn get_oauth_client_alpha(api: &ApiV3) -> OAuthClient {
let oauth_clients = api
.get_user_oauth_clients(USER_USER_ID, USER_USER_PAT)
.await;
oauth_clients.into_iter().next().unwrap()

View File

@@ -1,8 +1,7 @@
#![allow(dead_code)]
use std::{rc::Rc, sync::Arc};
use super::{
api_common::{generic::GenericApi, Api, ApiBuildable},
api_v2::ApiV2,
api_v3::ApiV3,
asserts::assert_status,
@@ -11,76 +10,103 @@ use super::{
};
use crate::common::setup;
use actix_http::StatusCode;
use actix_web::{dev::ServiceResponse, test, App};
use actix_web::dev::ServiceResponse;
use futures::Future;
pub async fn with_test_environment<Fut>(f: impl FnOnce(TestEnvironment) -> Fut)
where
pub async fn with_test_environment<Fut, A>(
max_connections: Option<u32>,
f: impl FnOnce(TestEnvironment<A>) -> Fut,
) where
Fut: Future<Output = ()>,
A: ApiBuildable + 'static,
{
let test_env = TestEnvironment::build(None).await;
let test_env: TestEnvironment<A> = TestEnvironment::build(max_connections).await;
let db = test_env.db.clone();
f(test_env).await;
db.cleanup().await;
}
// TODO: This needs to be slightly redesigned in order to do both V2 and v3 tests.
// TODO: Most tests, since they use API functions, can be applied to both. The ones that weren't are in v2/, but
// all tests that can be applied to both should use both v2 and v3 (extract api to a trait with all the API functions and call both).
pub async fn with_test_environment_all<Fut, F>(max_connections: Option<u32>, f: F)
where
Fut: Future<Output = ()>,
F: Fn(TestEnvironment<GenericApi>) -> Fut,
{
println!("Test environment: API v3");
let test_env_api_v3 = TestEnvironment::<ApiV3>::build(max_connections).await;
let test_env_api_v3 = TestEnvironment {
db: test_env_api_v3.db.clone(),
api: GenericApi::V3(test_env_api_v3.api),
setup_api: test_env_api_v3.setup_api,
dummy: test_env_api_v3.dummy,
};
let db = test_env_api_v3.db.clone();
f(test_env_api_v3).await;
db.cleanup().await;
println!("Test environment: API v2");
let test_env_api_v2 = TestEnvironment::<ApiV2>::build(max_connections).await;
let test_env_api_v2 = TestEnvironment {
db: test_env_api_v2.db.clone(),
api: GenericApi::V2(test_env_api_v2.api),
setup_api: test_env_api_v2.setup_api,
dummy: test_env_api_v2.dummy,
};
let db = test_env_api_v2.db.clone();
f(test_env_api_v2).await;
db.cleanup().await;
}
// A complete test environment, with a test actix app and a database.
// Must be called in an #[actix_rt::test] context. It also simulates a
// temporary sqlx db like #[sqlx::test] would.
// Use .call(req) on it directly to make a test call as if test::call_service(req) were being used.
#[derive(Clone)]
pub struct TestEnvironment {
test_app: Rc<dyn LocalService>, // Rc as it's not Send
pub struct TestEnvironment<A> {
// test_app: Rc<dyn LocalService>, // Rc as it's not Send
pub db: TemporaryDatabase,
pub v2: ApiV2,
pub v3: ApiV3,
pub dummy: Option<Arc<dummy_data::DummyData>>,
pub api: A,
pub setup_api: ApiV3, // Used for setting up tests only (ie: in ScopesTest)
pub dummy: Option<dummy_data::DummyData>,
}
impl TestEnvironment {
pub async fn build(max_connections: Option<u32>) -> Self {
impl<A: ApiBuildable> TestEnvironment<A> {
async fn build(max_connections: Option<u32>) -> Self {
let db = TemporaryDatabase::create(max_connections).await;
let mut test_env = Self::build_with_db(db).await;
let dummy = dummy_data::get_dummy_data(&test_env).await;
test_env.dummy = Some(Arc::new(dummy));
let dummy = dummy_data::get_dummy_data(&test_env.setup_api).await;
test_env.dummy = Some(dummy);
test_env
}
pub async fn build_with_db(db: TemporaryDatabase) -> Self {
let labrinth_config = setup(&db).await;
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 {
v2: ApiV2 {
test_app: test_app.clone(),
},
v3: ApiV3 {
test_app: test_app.clone(),
},
test_app,
db,
api: A::build(labrinth_config.clone()).await,
setup_api: ApiV3::build(labrinth_config.clone()).await,
dummy: None,
// test_app
}
}
}
impl<A: Api> TestEnvironment<A> {
pub async fn cleanup(self) {
self.db.cleanup().await;
}
pub async fn call(&self, req: actix_http::Request) -> ServiceResponse {
self.test_app.call(req).await.unwrap()
self.api.call(req).await
}
// Setup data, create a friend user notification
pub async fn generate_friend_user_notification(&self) {
let resp = self
.v3
.api
.add_user_to_team(
&self.dummy.as_ref().unwrap().project_alpha.team_id,
FRIEND_USER_ID,
@@ -92,23 +118,25 @@ impl TestEnvironment {
assert_status(&resp, StatusCode::NO_CONTENT);
}
// Setup data, assert that a user can read notifications
pub async fn assert_read_notifications_status(
&self,
user_id: &str,
pat: &str,
status_code: StatusCode,
) {
let resp = self.v3.get_user_notifications(user_id, pat).await;
let resp = self.api.get_user_notifications(user_id, pat).await;
assert_status(&resp, status_code);
}
// Setup data, assert that a user can read projects notifications
pub async fn assert_read_user_projects_status(
&self,
user_id: &str,
pat: &str,
status_code: StatusCode,
) {
let resp = self.v3.get_user_projects(user_id, pat).await;
let resp = self.api.get_user_projects(user_id, pat).await;
assert_status(&resp, status_code);
}
}

View File

@@ -2,6 +2,7 @@ use labrinth::{check_env_vars, clickhouse};
use labrinth::{file_hosting, queue, LabrinthConfig};
use std::sync::Arc;
pub mod api_common;
pub mod api_v2;
pub mod api_v3;
pub mod asserts;

View File

@@ -5,10 +5,14 @@ use itertools::Itertools;
use labrinth::models::teams::{OrganizationPermissions, ProjectPermissions};
use serde_json::json;
use crate::common::database::{generate_random_name, ADMIN_USER_PAT};
use crate::common::{
api_common::ApiTeams,
database::{generate_random_name, ADMIN_USER_PAT},
};
use super::{
api_v3::request_data,
api_common::{Api, ApiProject},
api_v3::ApiV3,
database::{ENEMY_USER_PAT, USER_USER_ID, USER_USER_PAT},
environment::TestEnvironment,
};
@@ -18,8 +22,9 @@ use super::{
// - returns a 200-299 if the scope is present
// - returns failure and success JSON bodies for requests that are 200 (for performing non-simple follow-up tests on)
// This uses a builder format, so you can chain methods to set the parameters to non-defaults (most will probably be not need to be set).
pub struct PermissionsTest<'a> {
test_env: &'a TestEnvironment,
type JsonCheck = Box<dyn Fn(&serde_json::Value) + Send>;
pub struct PermissionsTest<'a, A: Api> {
test_env: &'a TestEnvironment<A>,
// Permissions expected to fail on this test. By default, this is all permissions except the success permissions.
// (To ensure we have isolated the permissions we are testing)
failure_project_permissions: Option<ProjectPermissions>,
@@ -50,12 +55,12 @@ pub struct PermissionsTest<'a> {
// Closures that check the JSON body of the response for failure and success cases.
// These are used to perform more complex tests than just checking the status code.
// (eg: checking that the response contains the correct data)
failure_json_check: Option<Box<dyn Fn(&serde_json::Value) + Send>>,
success_json_check: Option<Box<dyn Fn(&serde_json::Value) + Send>>,
failure_json_check: Option<JsonCheck>,
success_json_check: Option<JsonCheck>,
}
pub struct PermissionsTestContext<'a> {
pub test_env: &'a TestEnvironment,
// pub test_env: &'a TestEnvironment<A>,
pub user_id: &'a str,
pub user_pat: &'a str,
pub project_id: Option<&'a str>,
@@ -64,8 +69,8 @@ pub struct PermissionsTestContext<'a> {
pub organization_team_id: Option<&'a str>,
}
impl<'a> PermissionsTest<'a> {
pub fn new(test_env: &'a TestEnvironment) -> Self {
impl<'a, A: Api> PermissionsTest<'a, A> {
pub fn new(test_env: &'a TestEnvironment<A>) -> Self {
Self {
test_env,
failure_project_permissions: None,
@@ -157,7 +162,6 @@ impl<'a> PermissionsTest<'a> {
.failure_project_permissions
.unwrap_or(ProjectPermissions::all() ^ success_permissions);
let test_context = PermissionsTestContext {
test_env,
user_id: self.user_id,
user_pat: self.user_pat,
project_id: None,
@@ -172,7 +176,7 @@ impl<'a> PermissionsTest<'a> {
self.project_team_id.clone().unwrap(),
)
} else {
create_dummy_project(test_env).await
create_dummy_project(&test_env.setup_api).await
};
add_user_to_team(
@@ -181,7 +185,7 @@ impl<'a> PermissionsTest<'a> {
&team_id,
Some(failure_project_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -268,7 +272,7 @@ impl<'a> PermissionsTest<'a> {
&team_id,
Some(success_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -297,7 +301,7 @@ impl<'a> PermissionsTest<'a> {
// If the remove_user flag is set, remove the user from the project
// Relevant for existing projects/users
if self.remove_user {
remove_user_from_team(self.user_id, &team_id, test_env).await;
remove_user_from_team(self.user_id, &team_id, &test_env.setup_api).await;
}
Ok(())
}
@@ -315,7 +319,6 @@ impl<'a> PermissionsTest<'a> {
.failure_organization_permissions
.unwrap_or(OrganizationPermissions::all() ^ success_permissions);
let test_context = PermissionsTestContext {
test_env,
user_id: self.user_id,
user_pat: self.user_pat,
project_id: None,
@@ -331,7 +334,7 @@ impl<'a> PermissionsTest<'a> {
self.organization_team_id.clone().unwrap(),
)
} else {
create_dummy_org(test_env).await
create_dummy_org(&test_env.setup_api).await
};
add_user_to_team(
@@ -340,7 +343,7 @@ impl<'a> PermissionsTest<'a> {
&team_id,
None,
Some(failure_organization_permissions),
test_env,
&test_env.setup_api,
)
.await;
@@ -371,7 +374,7 @@ impl<'a> PermissionsTest<'a> {
&team_id,
None,
Some(success_permissions),
test_env,
&test_env.setup_api,
)
.await;
@@ -395,7 +398,7 @@ impl<'a> PermissionsTest<'a> {
// If the remove_user flag is set, remove the user from the organization
// Relevant for existing projects/users
if self.remove_user {
remove_user_from_team(self.user_id, &team_id, test_env).await;
remove_user_from_team(self.user_id, &team_id, &test_env.setup_api).await;
}
Ok(())
}
@@ -413,7 +416,6 @@ impl<'a> PermissionsTest<'a> {
.failure_project_permissions
.unwrap_or(ProjectPermissions::all() ^ success_permissions);
let test_context = PermissionsTestContext {
test_env,
user_id: self.user_id,
user_pat: self.user_pat,
project_id: None,
@@ -426,7 +428,7 @@ impl<'a> PermissionsTest<'a> {
// This should always fail, regardless of permissions
// (As we are testing permissions-based failures)
let test_1 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
let request = req_gen(&PermissionsTestContext {
project_id: Some(&project_id),
@@ -447,8 +449,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != ProjectPermissions::empty() {
return Err(format!(
"Test 1 failed. Expected no permissions, got {:?}",
@@ -462,7 +469,7 @@ impl<'a> PermissionsTest<'a> {
// TEST 2: Failure
// Random user, unaffiliated with the project, with no permissions
let test_2 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
let request = req_gen(&PermissionsTestContext {
project_id: Some(&project_id),
@@ -483,8 +490,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != ProjectPermissions::empty() {
return Err(format!(
"Test 2 failed. Expected no permissions, got {:?}",
@@ -498,14 +510,14 @@ impl<'a> PermissionsTest<'a> {
// TEST 3: Failure
// User affiliated with the project, with failure permissions
let test_3 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
add_user_to_team(
self.user_id,
self.user_pat,
&team_id,
Some(failure_project_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -529,8 +541,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != failure_project_permissions {
return Err(format!(
"Test 3 failed. Expected {:?}, got {:?}",
@@ -544,14 +561,14 @@ impl<'a> PermissionsTest<'a> {
// TEST 4: Success
// User affiliated with the project, with the given permissions
let test_4 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
add_user_to_team(
self.user_id,
self.user_pat,
&team_id,
Some(success_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -571,8 +588,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != success_permissions {
return Err(format!(
"Test 4 failed. Expected {:?}, got {:?}",
@@ -587,16 +609,17 @@ impl<'a> PermissionsTest<'a> {
// Project has an organization
// User affiliated with the project's org, with default failure permissions
let test_5 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
add_project_to_org(test_env, &project_id, &organization_id).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
add_project_to_org(&test_env.setup_api, &project_id, &organization_id).await;
add_user_to_team(
self.user_id,
self.user_pat,
&organization_team_id,
Some(failure_project_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -620,8 +643,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != failure_project_permissions {
return Err(format!(
"Test 5 failed. Expected {:?}, got {:?}",
@@ -636,16 +664,17 @@ impl<'a> PermissionsTest<'a> {
// Project has an organization
// User affiliated with the project's org, with the default success
let test_6 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
add_project_to_org(test_env, &project_id, &organization_id).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
add_project_to_org(&test_env.setup_api, &project_id, &organization_id).await;
add_user_to_team(
self.user_id,
self.user_pat,
&organization_team_id,
Some(success_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -665,8 +694,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != success_permissions {
return Err(format!(
"Test 6 failed. Expected {:?}, got {:?}",
@@ -682,16 +716,17 @@ impl<'a> PermissionsTest<'a> {
// User affiliated with the project's org (even can have successful permissions!)
// User overwritten on the project team with failure permissions
let test_7 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
add_project_to_org(test_env, &project_id, &organization_id).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
add_project_to_org(&test_env.setup_api, &project_id, &organization_id).await;
add_user_to_team(
self.user_id,
self.user_pat,
&organization_team_id,
Some(success_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
add_user_to_team(
@@ -700,7 +735,7 @@ impl<'a> PermissionsTest<'a> {
&team_id,
Some(failure_project_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -724,8 +759,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != failure_project_permissions {
return Err(format!(
"Test 7 failed. Expected {:?}, got {:?}",
@@ -741,16 +781,17 @@ impl<'a> PermissionsTest<'a> {
// User affiliated with the project's org with default failure permissions
// User overwritten to the project with the success permissions
let test_8 = async {
let (project_id, team_id) = create_dummy_project(test_env).await;
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
add_project_to_org(test_env, &project_id, &organization_id).await;
let (project_id, team_id) = create_dummy_project(&test_env.setup_api).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
add_project_to_org(&test_env.setup_api, &project_id, &organization_id).await;
add_user_to_team(
self.user_id,
self.user_pat,
&organization_team_id,
Some(failure_project_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
add_user_to_team(
@@ -759,7 +800,7 @@ impl<'a> PermissionsTest<'a> {
&team_id,
Some(success_permissions),
None,
test_env,
&test_env.setup_api,
)
.await;
@@ -780,8 +821,13 @@ impl<'a> PermissionsTest<'a> {
));
}
let p =
get_project_permissions(self.user_id, self.user_pat, &project_id, test_env).await;
let p = get_project_permissions(
self.user_id,
self.user_pat,
&project_id,
&test_env.setup_api,
)
.await;
if p != success_permissions {
return Err(format!(
"Test 8 failed. Expected {:?}, got {:?}",
@@ -811,7 +857,6 @@ impl<'a> PermissionsTest<'a> {
.failure_organization_permissions
.unwrap_or(OrganizationPermissions::all() ^ success_permissions);
let test_context = PermissionsTestContext {
test_env,
user_id: self.user_id,
user_pat: self.user_pat,
project_id: None, // Will be overwritten on each test
@@ -823,7 +868,8 @@ impl<'a> PermissionsTest<'a> {
// TEST 1: Failure
// Random user, entirely unaffliaited with the organization
let test_1 = async {
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
let request = req_gen(&PermissionsTestContext {
organization_id: Some(&organization_id),
@@ -848,7 +894,7 @@ impl<'a> PermissionsTest<'a> {
self.user_id,
self.user_pat,
&organization_id,
test_env,
&test_env.setup_api,
)
.await;
if p != OrganizationPermissions::empty() {
@@ -863,14 +909,15 @@ impl<'a> PermissionsTest<'a> {
// TEST 2: Failure
// User affiliated with the organization, with failure permissions
let test_2 = async {
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
add_user_to_team(
self.user_id,
self.user_pat,
&organization_team_id,
None,
Some(failure_organization_permissions),
test_env,
&test_env.setup_api,
)
.await;
@@ -898,7 +945,7 @@ impl<'a> PermissionsTest<'a> {
self.user_id,
self.user_pat,
&organization_id,
test_env,
&test_env.setup_api,
)
.await;
if p != failure_organization_permissions {
@@ -913,14 +960,15 @@ impl<'a> PermissionsTest<'a> {
// TEST 3: Success
// User affiliated with the organization, with the given permissions
let test_3 = async {
let (organization_id, organization_team_id) = create_dummy_org(test_env).await;
let (organization_id, organization_team_id) =
create_dummy_org(&test_env.setup_api).await;
add_user_to_team(
self.user_id,
self.user_pat,
&organization_team_id,
None,
Some(success_permissions),
test_env,
&test_env.setup_api,
)
.await;
@@ -944,7 +992,7 @@ impl<'a> PermissionsTest<'a> {
self.user_id,
self.user_pat,
&organization_id,
test_env,
&test_env.setup_api,
)
.await;
if p != success_permissions {
@@ -962,31 +1010,29 @@ impl<'a> PermissionsTest<'a> {
}
}
async fn create_dummy_project(test_env: &TestEnvironment) -> (String, String) {
let api = &test_env.v3;
async fn create_dummy_project(setup_api: &ApiV3) -> (String, String) {
// Create a very simple project
let slug = generate_random_name("test_project");
let creation_data = request_data::get_public_project_creation_data(&slug, None);
let (project, _) = api.add_public_project(creation_data, ADMIN_USER_PAT).await;
let (project, _) = setup_api
.add_public_project(&slug, None, None, ADMIN_USER_PAT)
.await;
let project_id = project.id.to_string();
let team_id = project.team.to_string();
(project_id, team_id)
}
async fn create_dummy_org(test_env: &TestEnvironment) -> (String, String) {
async fn create_dummy_org(setup_api: &ApiV3) -> (String, String) {
// Create a very simple organization
let name = generate_random_name("test_org");
let api = &test_env.v3;
let resp = api
let resp = setup_api
.create_organization(&name, "Example description.", ADMIN_USER_PAT)
.await;
assert!(resp.status().is_success());
let organization = api
let organization = setup_api
.get_organization_deserialized(&name, ADMIN_USER_PAT)
.await;
let organizaion_id = organization.id.to_string();
@@ -995,9 +1041,8 @@ async fn create_dummy_org(test_env: &TestEnvironment) -> (String, String) {
(organizaion_id, team_id)
}
async fn add_project_to_org(test_env: &TestEnvironment, project_id: &str, organization_id: &str) {
let api = &test_env.v3;
let resp = api
async fn add_project_to_org(setup_api: &ApiV3, project_id: &str, organization_id: &str) {
let resp = setup_api
.organization_add_project(organization_id, project_id, ADMIN_USER_PAT)
.await;
assert!(resp.status().is_success());
@@ -1009,12 +1054,10 @@ async fn add_user_to_team(
team_id: &str,
project_permissions: Option<ProjectPermissions>,
organization_permissions: Option<OrganizationPermissions>,
test_env: &TestEnvironment,
setup_api: &ApiV3,
) {
let api = &test_env.v3;
// Invite user
let resp = api
let resp = setup_api
.add_user_to_team(
team_id,
user_id,
@@ -1026,7 +1069,7 @@ async fn add_user_to_team(
assert!(resp.status().is_success());
// Accept invitation
let resp = api.join_team(team_id, user_pat).await;
let resp = setup_api.join_team(team_id, user_pat).await;
assert!(resp.status().is_success());
}
@@ -1035,12 +1078,10 @@ async fn modify_user_team_permissions(
team_id: &str,
permissions: Option<ProjectPermissions>,
organization_permissions: Option<OrganizationPermissions>,
test_env: &TestEnvironment,
setup_api: &ApiV3,
) {
let api = &test_env.v3;
// Send invitation to user
let resp = api
let resp = setup_api
.edit_team_member(
team_id,
user_id,
@@ -1054,10 +1095,11 @@ async fn modify_user_team_permissions(
assert!(resp.status().is_success());
}
async fn remove_user_from_team(user_id: &str, team_id: &str, test_env: &TestEnvironment) {
async fn remove_user_from_team(user_id: &str, team_id: &str, setup_api: &ApiV3) {
// Send invitation to user
let api = &test_env.v3;
let resp = api.remove_from_team(team_id, user_id, ADMIN_USER_PAT).await;
let resp = setup_api
.remove_from_team(team_id, user_id, ADMIN_USER_PAT)
.await;
assert!(resp.status().is_success());
}
@@ -1065,9 +1107,9 @@ async fn get_project_permissions(
user_id: &str,
user_pat: &str,
project_id: &str,
test_env: &TestEnvironment,
setup_api: &ApiV3,
) -> ProjectPermissions {
let resp = test_env.v3.get_project_members(project_id, user_pat).await;
let resp = setup_api.get_project_members(project_id, user_pat).await;
let permissions = if resp.status().as_u16() == 200 {
let value: serde_json::Value = test::read_body_json(resp).await;
value
@@ -1088,10 +1130,9 @@ async fn get_organization_permissions(
user_id: &str,
user_pat: &str,
organization_id: &str,
test_env: &TestEnvironment,
setup_api: &ApiV3,
) -> OrganizationPermissions {
let api = &test_env.v3;
let resp = api
let resp = setup_api
.get_organization_members(organization_id, user_pat)
.await;
let permissions = if resp.status().as_u16() == 200 {

View File

@@ -2,15 +2,18 @@
use actix_web::test::{self, TestRequest};
use labrinth::models::pats::Scopes;
use super::{database::USER_USER_ID_PARSED, environment::TestEnvironment, pats::create_test_pat};
use super::{
api_common::Api, database::USER_USER_ID_PARSED, environment::TestEnvironment,
pats::create_test_pat,
};
// A reusable test type that works for any scope test testing an endpoint that:
// - returns a known 'expected_failure_code' if the scope is not present (defaults to 401)
// - returns a 200-299 if the scope is present
// - returns failure and success JSON bodies for requests that are 200 (for performing non-simple follow-up tests on)
// This uses a builder format, so you can chain methods to set the parameters to non-defaults (most will probably be not need to be set).
pub struct ScopeTest<'a> {
test_env: &'a TestEnvironment,
pub struct ScopeTest<'a, A> {
test_env: &'a TestEnvironment<A>,
// Scopes expected to fail on this test. By default, this is all scopes except the success scopes.
// (To ensure we have isolated the scope we are testing)
failure_scopes: Option<Scopes>,
@@ -20,8 +23,8 @@ pub struct ScopeTest<'a> {
expected_failure_code: u16,
}
impl<'a> ScopeTest<'a> {
pub fn new(test_env: &'a TestEnvironment) -> Self {
impl<'a, A: Api> ScopeTest<'a, A> {
pub fn new(test_env: &'a TestEnvironment<A>) -> Self {
Self {
test_env,
failure_scopes: None,