working test passing
This commit is contained in:
@@ -4,6 +4,7 @@ use sqlx::{PgPool, Arguments, Postgres};
|
||||
use sqlx::postgres::PgArguments;
|
||||
use chrono::{DateTime, Utc};
|
||||
use common::proto::multieko2::tables_data::{PutTableDataRequest, PutTableDataResponse};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub async fn put_table_data(
|
||||
db_pool: &PgPool,
|
||||
@@ -12,9 +13,27 @@ pub async fn put_table_data(
|
||||
let profile_name = request.profile_name;
|
||||
let table_name = request.table_name;
|
||||
let record_id = request.id;
|
||||
let data = request.data;
|
||||
|
||||
// Preprocess and validate data
|
||||
let mut processed_data = HashMap::new();
|
||||
let mut null_fields = Vec::new();
|
||||
|
||||
for (key, value) in request.data {
|
||||
let trimmed = value.trim().to_string();
|
||||
|
||||
if key == "firma" && trimmed.is_empty() {
|
||||
return Err(Status::invalid_argument("Firma cannot be empty"));
|
||||
}
|
||||
|
||||
// Store fields that should be set to NULL
|
||||
if key != "firma" && trimmed.is_empty() {
|
||||
null_fields.push(key);
|
||||
} else {
|
||||
processed_data.insert(key, trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup profile (same as POST)
|
||||
// Lookup profile
|
||||
let profile = sqlx::query!(
|
||||
"SELECT id FROM profiles WHERE name = $1",
|
||||
profile_name
|
||||
@@ -25,7 +44,7 @@ pub async fn put_table_data(
|
||||
|
||||
let profile_id = profile.ok_or_else(|| Status::not_found("Profile not found"))?.id;
|
||||
|
||||
// Lookup table_definition (same as POST)
|
||||
// Lookup table_definition
|
||||
let table_def = sqlx::query!(
|
||||
r#"SELECT id, columns FROM table_definitions
|
||||
WHERE profile_id = $1 AND table_name = $2"#,
|
||||
@@ -38,7 +57,7 @@ pub async fn put_table_data(
|
||||
|
||||
let table_def = table_def.ok_or_else(|| Status::not_found("Table not found"))?;
|
||||
|
||||
// Parse columns from JSON (same as POST)
|
||||
// Parse columns from JSON
|
||||
let columns_json: Vec<String> = serde_json::from_value(table_def.columns.clone())
|
||||
.map_err(|e| Status::internal(format!("Column parsing error: {}", e)))?;
|
||||
|
||||
@@ -58,7 +77,7 @@ pub async fn put_table_data(
|
||||
let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect();
|
||||
|
||||
// Validate input columns
|
||||
for key in data.keys() {
|
||||
for key in processed_data.keys() {
|
||||
if !system_columns.contains(&key.as_str()) && !user_columns.contains(&key) {
|
||||
return Err(Status::invalid_argument(format!("Invalid column: {}", key)));
|
||||
}
|
||||
@@ -69,8 +88,8 @@ pub async fn put_table_data(
|
||||
let mut set_clauses = Vec::new();
|
||||
let mut param_idx = 1;
|
||||
|
||||
// Add data parameters
|
||||
for (col, value) in &data {
|
||||
// Add data parameters for non-empty fields
|
||||
for (col, value) in &processed_data {
|
||||
let sql_type = if system_columns.contains(&col.as_str()) {
|
||||
match col.as_str() {
|
||||
"firma" => "TEXT",
|
||||
@@ -91,7 +110,7 @@ pub async fn put_table_data(
|
||||
.and_then(|s| s.parse::<usize>().ok())
|
||||
{
|
||||
if value.len() > max_len {
|
||||
return Err(Status::invalid_argument(format!("Value too long for {}", col)));
|
||||
return Err(Status::internal(format!("Value too long for {}", col)));
|
||||
}
|
||||
}
|
||||
params.add(value)
|
||||
@@ -116,6 +135,20 @@ pub async fn put_table_data(
|
||||
param_idx += 1;
|
||||
}
|
||||
|
||||
// Add NULL clauses for empty fields
|
||||
for field in null_fields {
|
||||
// Make sure the field is valid
|
||||
if !system_columns.contains(&field.as_str()) && !user_columns.contains(&&field) {
|
||||
return Err(Status::invalid_argument(format!("Invalid column to set NULL: {}", field)));
|
||||
}
|
||||
set_clauses.push(format!("\"{}\" = NULL", field));
|
||||
}
|
||||
|
||||
// Ensure we have at least one field to update
|
||||
if set_clauses.is_empty() {
|
||||
return Err(Status::invalid_argument("No valid fields to update"));
|
||||
}
|
||||
|
||||
// Add ID parameter at the end
|
||||
params.add(record_id)
|
||||
.map_err(|e| Status::internal(format!("Failed to add record_id parameter: {}", e)))?;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// tests/tables_data/mod.rs
|
||||
pub mod post_table_data_test;
|
||||
pub mod put_table_data_test;
|
||||
|
||||
|
||||
314
server/tests/tables_data/handlers/put_table_data_test.rs
Normal file
314
server/tests/tables_data/handlers/put_table_data_test.rs
Normal file
@@ -0,0 +1,314 @@
|
||||
// tests/tables_data/handlers/put_table_data_test.rs
|
||||
use rstest::{fixture, rstest};
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use common::proto::multieko2::tables_data::{PutTableDataRequest, PutTableDataResponse};
|
||||
use server::tables_data::handlers::put_table_data;
|
||||
use crate::common::setup_test_db;
|
||||
use tonic;
|
||||
use chrono::Utc;
|
||||
|
||||
// Fixtures
|
||||
#[fixture]
|
||||
async fn pool() -> PgPool {
|
||||
setup_test_db().await
|
||||
}
|
||||
|
||||
#[fixture]
|
||||
async fn closed_pool(#[future] pool: PgPool) -> PgPool {
|
||||
let pool = pool.await;
|
||||
pool.close().await;
|
||||
pool
|
||||
}
|
||||
|
||||
#[fixture]
|
||||
async fn existing_record(#[future] pool: PgPool) -> (PgPool, i64) {
|
||||
let pool = pool.await;
|
||||
|
||||
// Create a test record in the database
|
||||
let record = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO "2025_adresar" (
|
||||
firma, kz, drc, ulica, psc, mesto, stat, banka, ucet,
|
||||
skladm, ico, kontakt, telefon, skladu, fax, deleted
|
||||
)
|
||||
VALUES (
|
||||
'Original Company', 'Original KZ', 'Original DRC', 'Original Street',
|
||||
'12345', 'Original City', 'Original Country', 'Original Bank',
|
||||
'Original Account', 'Original SkladM', 'Original ICO',
|
||||
'Original Contact', '+421123456789', 'Original SkladU', 'Original Fax',
|
||||
false
|
||||
)
|
||||
RETURNING id
|
||||
"#
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
(pool, record.id)
|
||||
}
|
||||
|
||||
#[fixture]
|
||||
fn valid_request_template() -> HashMap<String, String> {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("firma".into(), "Updated Company".into());
|
||||
map.insert("kz".into(), "Updated KZ".into());
|
||||
map.insert("drc".into(), "Updated DRC".into());
|
||||
map.insert("ulica".into(), "Updated Street".into());
|
||||
map.insert("psc".into(), "67890".into());
|
||||
map.insert("mesto".into(), "Updated City".into());
|
||||
map.insert("stat".into(), "Updated Country".into());
|
||||
map.insert("banka".into(), "Updated Bank".into());
|
||||
map.insert("ucet".into(), "987654321".into());
|
||||
map.insert("skladm".into(), "Updated SkladM".into());
|
||||
map.insert("ico".into(), "87654321".into());
|
||||
map.insert("kontakt".into(), "Jane Doe".into());
|
||||
map.insert("telefon".into(), "+421987654321".into());
|
||||
map.insert("skladu".into(), "Updated SkladU".into());
|
||||
map.insert("fax".into(), "+421987654300".into());
|
||||
map
|
||||
}
|
||||
|
||||
// Helper to check database state
|
||||
async fn assert_response_matches(pool: &PgPool, id: i64, response: &PutTableDataResponse) {
|
||||
let db_record = sqlx::query!(r#"SELECT * FROM "2025_adresar" WHERE id = $1"#, id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(db_record.firma, "Updated Company");
|
||||
assert_eq!(db_record.kz.unwrap_or_default(), "Updated KZ");
|
||||
assert_eq!(db_record.drc.unwrap_or_default(), "Updated DRC");
|
||||
assert_eq!(db_record.ulica.unwrap_or_default(), "Updated Street");
|
||||
assert_eq!(db_record.psc.unwrap_or_default(), "67890");
|
||||
assert_eq!(db_record.mesto.unwrap_or_default(), "Updated City");
|
||||
assert_eq!(db_record.stat.unwrap_or_default(), "Updated Country");
|
||||
assert_eq!(db_record.banka.unwrap_or_default(), "Updated Bank");
|
||||
assert_eq!(db_record.ucet.unwrap_or_default(), "987654321");
|
||||
assert_eq!(db_record.skladm.unwrap_or_default(), "Updated SkladM");
|
||||
assert_eq!(db_record.ico.unwrap_or_default(), "87654321");
|
||||
assert_eq!(db_record.kontakt.unwrap_or_default(), "Jane Doe");
|
||||
assert_eq!(db_record.telefon.unwrap_or_default(), "+421987654321");
|
||||
assert_eq!(db_record.skladu.unwrap_or_default(), "Updated SkladU");
|
||||
assert_eq!(db_record.fax.unwrap_or_default(), "+421987654300");
|
||||
assert!(!db_record.deleted, "Record should not be deleted");
|
||||
}
|
||||
|
||||
// Tests
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_success(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data: valid_request_template,
|
||||
};
|
||||
|
||||
let response = put_table_data(&pool, request).await.unwrap();
|
||||
|
||||
assert!(response.success);
|
||||
assert_eq!(response.message, "Data updated successfully");
|
||||
assert_eq!(response.updated_id, id);
|
||||
assert_response_matches(&pool, id, &response).await;
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_whitespace_trimming(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
let mut data = valid_request_template;
|
||||
data.insert("firma".into(), " Updated Company ".into());
|
||||
data.insert("telefon".into(), " +421987654321 ".into());
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data,
|
||||
};
|
||||
|
||||
let response = put_table_data(&pool, request).await.unwrap();
|
||||
|
||||
// Verify trimmed values in response
|
||||
assert_eq!(response.message, "Data updated successfully");
|
||||
|
||||
// Verify raw values in database
|
||||
let db_record = sqlx::query!(r#"SELECT firma, telefon FROM "2025_adresar" WHERE id = $1"#, id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(db_record.firma, "Updated Company"); // Trimmed
|
||||
assert_eq!(db_record.telefon.unwrap(), "+421987654321"); // Trimmed
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_empty_required_field(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
let mut data = valid_request_template;
|
||||
data.insert("firma".into(), "".into());
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data,
|
||||
};
|
||||
|
||||
let result = put_table_data(&pool, request).await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(result.unwrap_err().code(), tonic::Code::InvalidArgument);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_nonexistent_id(
|
||||
#[future] pool: PgPool,
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let pool = pool.await;
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id: 9999, // Non-existent ID
|
||||
data: valid_request_template,
|
||||
};
|
||||
|
||||
let result = put_table_data(&pool, request).await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_deleted_record(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
// Mark the record as deleted
|
||||
sqlx::query!(r#"UPDATE "2025_adresar" SET deleted = true WHERE id = $1"#, id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data: valid_request_template,
|
||||
};
|
||||
|
||||
let result = put_table_data(&pool, request).await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_clear_optional_fields(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
let mut data = valid_request_template;
|
||||
data.insert("telefon".into(), String::new());
|
||||
data.insert("ulica".into(), String::new());
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data,
|
||||
};
|
||||
|
||||
let response = put_table_data(&pool, request).await.unwrap();
|
||||
|
||||
// Check database contains NULL for cleared fields
|
||||
let db_record = sqlx::query!(r#"SELECT telefon, ulica FROM "2025_adresar" WHERE id = $1"#, id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(db_record.telefon.is_none());
|
||||
assert!(db_record.ulica.is_none());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_max_length_fields(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
let mut data = valid_request_template;
|
||||
data.insert("firma".into(), "a".repeat(255));
|
||||
data.insert("telefon".into(), "1".repeat(20));
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data,
|
||||
};
|
||||
|
||||
let _response = put_table_data(&pool, request).await.unwrap();
|
||||
|
||||
let db_record = sqlx::query!(r#"SELECT firma, telefon FROM "2025_adresar" WHERE id = $1"#, id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(db_record.firma.len(), 255);
|
||||
assert_eq!(db_record.telefon.unwrap().len(), 20);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_update_table_data_special_characters(
|
||||
#[future] existing_record: (PgPool, i64),
|
||||
valid_request_template: HashMap<String, String>,
|
||||
) {
|
||||
let (pool, id) = existing_record.await;
|
||||
|
||||
let mut data = valid_request_template;
|
||||
data.insert("ulica".into(), "Náměstí 28. října".into());
|
||||
data.insert("telefon".into(), "+420 123-456.789".into());
|
||||
|
||||
let request = PutTableDataRequest {
|
||||
profile_name: "default".into(),
|
||||
table_name: "2025_adresar".into(),
|
||||
id,
|
||||
data,
|
||||
};
|
||||
|
||||
let _response = put_table_data(&pool, request).await.unwrap();
|
||||
|
||||
let db_record = sqlx::query!(r#"SELECT ulica, telefon FROM "2025_adresar" WHERE id = $1"#, id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(db_record.ulica.unwrap(), "Náměstí 28. října");
|
||||
assert_eq!(db_record.telefon.unwrap(), "+420 123-456.789");
|
||||
}
|
||||
Reference in New Issue
Block a user