use crate::domain::repositories::geo_restriction_repository::{
GeoRestrictionRepository, GeoRestrictionRepositoryError,
};
use crate::domain::services::team_service::TeamGeoRestrictions;
use crate::infrastructure::database::entities::{geo_restriction_log, team};
use dbnexus::sea_orm::{ActiveModelTrait, EntityTrait, Set};
use dbnexus::DbPool;
use std::sync::Arc;
#[derive(Clone)]
pub struct DatabaseGeoRestrictionRepository {
pool: Arc<DbPool>,
}
impl DatabaseGeoRestrictionRepository {
pub fn new(pool: Arc<DbPool>) -> Self {
Self { pool }
}
}
#[async_trait::async_trait]
impl GeoRestrictionRepository for DatabaseGeoRestrictionRepository {
async fn get_team_restrictions(
&self,
team_id: crate::domain::id::Id,
) -> Result<TeamGeoRestrictions, GeoRestrictionRepositoryError> {
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
let conn = session
.connection()
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
let team_model = team::Entity::find_by_id(team_id)
.one(conn)
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?
.ok_or(GeoRestrictionRepositoryError::TeamNotFound(team_id))?;
let allowed_countries = team_model
.allowed_countries
.and_then(|json| serde_json::from_value(json).ok());
let blocked_countries = team_model
.blocked_countries
.and_then(|json| serde_json::from_value(json).ok());
let ip_whitelist = team_model
.ip_whitelist
.and_then(|json| serde_json::from_value(json).ok());
let domain_blacklist = team_model
.domain_blacklist
.and_then(|json| serde_json::from_value(json).ok());
Ok(TeamGeoRestrictions {
enable_geo_restrictions: team_model.enable_geo_restrictions,
allowed_countries,
blocked_countries,
ip_whitelist,
domain_blacklist,
})
}
async fn update_team_restrictions(
&self,
team_id: crate::domain::id::Id,
restrictions: &TeamGeoRestrictions,
) -> Result<(), GeoRestrictionRepositoryError> {
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
let conn = session
.connection()
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
let team_model = team::Entity::find_by_id(team_id)
.one(conn)
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?
.ok_or(GeoRestrictionRepositoryError::TeamNotFound(team_id))?;
let mut active_model: team::ActiveModel = team_model.into();
active_model.enable_geo_restrictions = Set(restrictions.enable_geo_restrictions);
active_model.allowed_countries =
Set(restrictions.allowed_countries.as_ref().map(|countries| {
serde_json::to_value(countries).expect(
"Failed to serialize allowed_countries: this should never fail for Vec<String>",
)
}));
active_model.blocked_countries =
Set(restrictions.blocked_countries.as_ref().map(|countries| {
serde_json::to_value(countries).expect(
"Failed to serialize blocked_countries: this should never fail for Vec<String>",
)
}));
active_model.ip_whitelist = Set(restrictions.ip_whitelist.as_ref().map(|whitelist| {
serde_json::to_value(whitelist)
.expect("Failed to serialize ip_whitelist: this should never fail for Vec<String>")
}));
active_model.domain_blacklist =
Set(restrictions.domain_blacklist.as_ref().map(|blacklist| {
serde_json::to_value(blacklist).expect(
"Failed to serialize domain_blacklist: this should never fail for Vec<String>",
)
}));
active_model
.update(conn)
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
Ok(())
}
async fn log_geo_restriction_action(
&self,
team_id: crate::domain::id::Id,
ip_address: &str,
country_code: &str,
action: &str,
reason: &str,
) -> Result<(), GeoRestrictionRepositoryError> {
let session = self
.pool
.get_session("admin")
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
let conn = session
.connection()
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
let log_entry = geo_restriction_log::ActiveModel {
id: Set(crate::domain::id::Id::generate().into()),
team_id: Set(team_id.into()),
ip_address: Set(ip_address.to_string()),
country_code: Set(Some(country_code.to_string())),
restriction_type: Set(action.to_string()),
url: Set(None), reason: Set(reason.to_string()),
created_at: Set(chrono::Utc::now().into()),
};
log_entry
.insert(conn)
.await
.map_err(|e| GeoRestrictionRepositoryError::Database(e.to_string()))?;
Ok(())
}
}
#[cfg(test)]
mod error_path_tests {
use super::*;
use crate::common::test_helpers::create_test_db_pool;
#[test]
fn test_new_creates_repository_instance() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let pool = create_test_db_pool();
let repo = DatabaseGeoRestrictionRepository::new(pool);
let _clone = repo.clone();
}
#[tokio::test]
async fn test_get_team_restrictions_returns_team_not_found_for_unknown() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.get_team_restrictions(crate::domain::id::Id::generate())
.await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_update_team_restrictions_returns_team_not_found_for_unknown() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions::default();
let result = repo
.update_team_restrictions(crate::domain::id::Id::generate(), &restrictions)
.await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_log_geo_restriction_action_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.log_geo_restriction_action(
crate::domain::id::Id::generate(),
"192.168.1.1",
"US",
"allowed",
"test reason",
)
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
#[test]
fn test_error_database_display() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let err = GeoRestrictionRepositoryError::Database("connection refused".to_string());
assert_eq!(format!("{}", err), "Database error: connection refused");
}
#[test]
fn test_error_team_not_found_display() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let id = crate::domain::id::Id::generate();
let err = GeoRestrictionRepositoryError::TeamNotFound(id);
assert_eq!(format!("{}", err), format!("Team not found: {}", id));
}
#[test]
fn test_error_other_display() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let err = GeoRestrictionRepositoryError::Other("something went wrong".to_string());
assert_eq!(format!("{}", err), "Other error: something went wrong");
}
#[test]
fn test_team_geo_restrictions_default() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions::default();
assert!(!restrictions.enable_geo_restrictions);
assert!(restrictions.allowed_countries.is_none());
assert!(restrictions.blocked_countries.is_none());
assert!(restrictions.ip_whitelist.is_none());
assert!(restrictions.domain_blacklist.is_none());
}
#[test]
fn test_team_geo_restrictions_with_all_fields_populated() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions {
enable_geo_restrictions: true,
allowed_countries: Some(vec!["US".to_string(), "CA".to_string()]),
blocked_countries: Some(vec!["CN".to_string(), "RU".to_string()]),
ip_whitelist: Some(vec!["192.168.1.1".to_string(), "10.0.0.1".to_string()]),
domain_blacklist: Some(vec!["spam.com".to_string(), "malware.org".to_string()]),
};
assert!(restrictions.enable_geo_restrictions);
assert_eq!(restrictions.allowed_countries.as_ref().unwrap().len(), 2);
assert_eq!(restrictions.blocked_countries.as_ref().unwrap().len(), 2);
assert_eq!(restrictions.ip_whitelist.as_ref().unwrap().len(), 2);
assert_eq!(restrictions.domain_blacklist.as_ref().unwrap().len(), 2);
}
#[test]
fn test_team_geo_restrictions_with_empty_vectors() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions {
enable_geo_restrictions: true,
allowed_countries: Some(Vec::new()),
blocked_countries: Some(Vec::new()),
ip_whitelist: Some(Vec::new()),
domain_blacklist: Some(Vec::new()),
};
assert!(restrictions.allowed_countries.as_ref().unwrap().is_empty());
assert!(restrictions.blocked_countries.as_ref().unwrap().is_empty());
assert!(restrictions.ip_whitelist.as_ref().unwrap().is_empty());
assert!(restrictions.domain_blacklist.as_ref().unwrap().is_empty());
}
#[test]
fn test_team_geo_restrictions_clone_preserves_values() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let original = crate::domain::services::team_service::TeamGeoRestrictions {
enable_geo_restrictions: true,
allowed_countries: Some(vec!["US".to_string()]),
blocked_countries: None,
ip_whitelist: Some(vec!["127.0.0.1".to_string()]),
domain_blacklist: None,
};
let cloned = original.clone();
assert_eq!(
cloned.enable_geo_restrictions,
original.enable_geo_restrictions
);
assert_eq!(cloned.allowed_countries, original.allowed_countries);
assert_eq!(cloned.blocked_countries, original.blocked_countries);
assert_eq!(cloned.ip_whitelist, original.ip_whitelist);
assert_eq!(cloned.domain_blacklist, original.domain_blacklist);
}
#[tokio::test]
async fn test_get_team_restrictions_with_nil_uuid_returns_team_not_found() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.get_team_restrictions(crate::domain::id::Id::nil())
.await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_update_team_restrictions_with_enabled_flag_returns_team_not_found() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions {
enable_geo_restrictions: true,
allowed_countries: Some(vec!["US".to_string(), "CA".to_string(), "MX".to_string()]),
blocked_countries: Some(vec!["CN".to_string()]),
ip_whitelist: None,
domain_blacklist: Some(vec!["bad.com".to_string()]),
};
let result = repo
.update_team_restrictions(crate::domain::id::Id::generate(), &restrictions)
.await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_update_team_restrictions_with_nil_uuid_returns_team_not_found() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions::default();
let result = repo
.update_team_restrictions(crate::domain::id::Id::nil(), &restrictions)
.await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_log_geo_restriction_action_with_empty_strings_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.log_geo_restriction_action(crate::domain::id::Id::generate(), "", "", "", "")
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
#[tokio::test]
async fn test_log_geo_restriction_action_with_unicode_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.log_geo_restriction_action(
crate::domain::id::Id::generate(),
"192.168.1.1",
"测试",
"阻止",
"地理限制-测试原因",
)
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
#[tokio::test]
async fn test_log_geo_restriction_action_with_special_characters_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.log_geo_restriction_action(
crate::domain::id::Id::generate(),
"10.0.0.1",
"US",
"allowed",
"reason with 'quotes' and \"double quotes\" and; semicolon",
)
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
#[tokio::test]
async fn test_log_geo_restriction_action_with_nil_uuid_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let result = repo
.log_geo_restriction_action(
crate::domain::id::Id::nil(),
"127.0.0.1",
"US",
"blocked",
"test",
)
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
#[test]
fn test_error_database_display_with_empty_message() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let err = GeoRestrictionRepositoryError::Database("".to_string());
assert_eq!(format!("{}", err), "Database error: ");
}
#[test]
fn test_error_database_display_with_long_message() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let long_msg = "x".repeat(1000);
let err = GeoRestrictionRepositoryError::Database(long_msg.clone());
let msg = format!("{}", err);
assert!(msg.contains(&long_msg));
}
#[test]
fn test_error_team_not_found_with_nil_uuid() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let err = GeoRestrictionRepositoryError::TeamNotFound(crate::domain::id::Id::nil());
assert_eq!(
format!("{}", err),
"Team not found: 00000000-0000-0000-0000-000000000000"
);
}
#[test]
fn test_error_other_with_empty_message() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let err = GeoRestrictionRepositoryError::Other("".to_string());
assert_eq!(format!("{}", err), "Other error: ");
}
#[test]
fn test_dberr_custom_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Custom("query failed".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("query failed"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_record_not_found_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::RecordNotFound("team missing".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("team missing"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_connection_acquire_timeout_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err =
dbnexus::sea_orm::DbErr::ConnectionAcquire(dbnexus::sea_orm::ConnAcquireErr::Timeout);
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(!msg.is_empty());
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_connection_acquire_closed_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::ConnectionAcquire(
dbnexus::sea_orm::ConnAcquireErr::ConnectionClosed,
);
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(!msg.is_empty());
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_record_not_inserted_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::RecordNotInserted;
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_record_not_updated_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::RecordNotUpdated;
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_query_runtime_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Query(dbnexus::sea_orm::RuntimeErr::Internal(
"syntax error".to_string(),
));
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("syntax error"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_conn_runtime_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Conn(dbnexus::sea_orm::RuntimeErr::Internal(
"conn lost".to_string(),
));
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("conn lost"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_exec_runtime_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Exec(dbnexus::sea_orm::RuntimeErr::Internal(
"exec failed".to_string(),
));
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("exec failed"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_type_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Type("invalid type".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("invalid type"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_json_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Json("parse error".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("parse error"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_attr_not_set_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::AttrNotSet("name".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("name"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_migration_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::Migration("schema mismatch".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("schema mismatch"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_rbac_error_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::RbacError("forbidden".to_string());
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("forbidden"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_access_denied_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::AccessDenied {
permission: "write".to_string(),
resource: "team".to_string(),
};
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
match repo_err {
GeoRestrictionRepositoryError::Database(msg) => {
assert!(msg.contains("write"));
assert!(msg.contains("team"));
}
other => panic!("expected Database variant, got {:?}", other),
}
}
#[test]
fn test_dberr_mutex_poison_error_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::MutexPoisonError;
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_backend_not_supported_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::BackendNotSupported {
db: "mysql",
ctx: "not configured",
};
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_unpack_insert_id_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::UnpackInsertId;
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_update_get_primary_key_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::UpdateGetPrimaryKey;
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_convert_from_u64_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::ConvertFromU64("String");
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_try_into_err_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let source_err: std::sync::Arc<dyn std::error::Error + Send + Sync> = std::sync::Arc::new(
std::io::Error::new(std::io::ErrorKind::InvalidData, "bad value"),
);
let db_err = dbnexus::sea_orm::DbErr::TryIntoErr {
from: "String",
into: "i32",
source: source_err,
};
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_key_arity_mismatch_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::KeyArityMismatch {
expected: 2,
received: 1,
};
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_dberr_primary_key_not_set_to_database_variant() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let db_err = dbnexus::sea_orm::DbErr::PrimaryKeyNotSet { ctx: "update" };
let repo_err = GeoRestrictionRepositoryError::Database(db_err.to_string());
assert!(matches!(
repo_err,
GeoRestrictionRepositoryError::Database(_)
));
}
#[test]
fn test_error_other_display_with_long_message() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let long_msg = "x".repeat(1000);
let err = GeoRestrictionRepositoryError::Other(long_msg.clone());
let msg = format!("{}", err);
assert!(msg.contains(&long_msg));
}
#[test]
fn test_error_database_display_with_special_characters() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let err = GeoRestrictionRepositoryError::Database(
"error with 'quotes' and \"double\" and; semicolon".to_string(),
);
let msg = format!("{}", err);
assert!(msg.contains("quotes"));
assert!(msg.contains("double"));
assert!(msg.contains("semicolon"));
}
#[test]
fn test_error_implements_debug_for_all_variants() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let variants: Vec<GeoRestrictionRepositoryError> = vec![
GeoRestrictionRepositoryError::Database("e".into()),
GeoRestrictionRepositoryError::TeamNotFound(crate::domain::id::Id::nil()),
GeoRestrictionRepositoryError::Other("o".into()),
];
for err in &variants {
let debug = format!("{:?}", err);
assert!(!debug.is_empty());
}
}
#[tokio::test]
async fn test_get_team_restrictions_with_max_uuid_returns_team_not_found() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let max_uuid = crate::domain::id::Id::from_u128(u128::MAX);
let result = repo.get_team_restrictions(max_uuid).await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_update_team_restrictions_with_empty_vectors_returns_team_not_found() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let restrictions = crate::domain::services::team_service::TeamGeoRestrictions {
enable_geo_restrictions: false,
allowed_countries: Some(Vec::new()),
blocked_countries: Some(Vec::new()),
ip_whitelist: Some(Vec::new()),
domain_blacklist: Some(Vec::new()),
};
let result = repo
.update_team_restrictions(crate::domain::id::Id::generate(), &restrictions)
.await;
match result {
Err(GeoRestrictionRepositoryError::TeamNotFound(_)) => {}
other => panic!("expected TeamNotFound error, got {:?}", other),
}
}
#[tokio::test]
async fn test_log_geo_restriction_action_with_long_reason_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let long_reason = "x".repeat(2000);
let result = repo
.log_geo_restriction_action(
crate::domain::id::Id::generate(),
"10.0.0.1",
"US",
"allowed",
&long_reason,
)
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
#[tokio::test]
async fn test_log_geo_restriction_action_with_max_uuid_succeeds() {
if crate::common::test_helpers::skip_if_no_test_db() {
return;
}
let repo = DatabaseGeoRestrictionRepository::new(create_test_db_pool());
let max_uuid = crate::domain::id::Id::from_u128(u128::MAX);
let result = repo
.log_geo_restriction_action(max_uuid, "127.0.0.1", "US", "blocked", "test")
.await;
assert!(
result.is_ok(),
"log_geo_restriction_action failed: {:?}",
result.err()
);
}
}