Skip to content

Commit 8d109fc

Browse files
committed
Test fixes
1 parent 0016266 commit 8d109fc

File tree

16 files changed

+161
-78
lines changed

16 files changed

+161
-78
lines changed

cargo-hammerwork/tests/sql_query_tests.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use sqlx::{MySqlPool, PgPool, Row};
44
/// Tests for SQL query validation and correctness
55
/// These tests validate that our dynamic SQL queries are syntactically correct
66
/// and produce expected results
7-
87
#[cfg(test)]
98
mod postgres_tests {
109
use super::*;

examples/autoscaling_example.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,23 @@ async fn main() -> Result<()> {
2525
// Uncomment the appropriate line below based on your database setup
2626

2727
// For PostgreSQL:
28-
#[cfg(feature = "postgres")]
28+
#[cfg(all(feature = "postgres", not(feature = "mysql")))]
2929
let pool = sqlx::PgPool::connect("postgresql://localhost/hammerwork")
3030
.await
3131
.map_err(hammerwork::HammerworkError::Database)?;
3232

3333
// For MySQL:
34-
#[cfg(feature = "mysql")]
34+
#[cfg(all(feature = "mysql", not(feature = "postgres")))]
3535
let pool = sqlx::MySqlPool::connect("mysql://localhost/hammerwork")
3636
.await
3737
.map_err(hammerwork::HammerworkError::Database)?;
3838

39+
// Default to PostgreSQL when both features are enabled
40+
#[cfg(all(feature = "postgres", feature = "mysql"))]
41+
let pool = sqlx::PgPool::connect("postgresql://localhost/hammerwork")
42+
.await
43+
.map_err(hammerwork::HammerworkError::Database)?;
44+
3945
let queue = Arc::new(JobQueue::new(pool));
4046

4147
// Initialize database tables

examples/priority_example.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,14 +404,16 @@ async fn demonstrate_worker_pool_priorities(
404404
let mut pool = WorkerPool::new().with_stats_collector(stats_collector.clone());
405405

406406
// Add workers with different priority configurations
407-
let handler: Arc<
407+
type JobHandler = Arc<
408408
dyn Fn(
409409
Job,
410410
) -> std::pin::Pin<
411411
Box<dyn std::future::Future<Output = hammerwork::Result<()>> + Send>,
412412
> + Send
413413
+ Sync,
414-
> = Arc::new(|job: Job| {
414+
>;
415+
416+
let handler: JobHandler = Arc::new(|job: Job| {
415417
Box::pin(async move {
416418
info!(
417419
"🔄 Pool worker processing: {} (Priority: {:?})",

examples/retry_strategies.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
4747
let database_url = get_database_url();
4848
info!("🔗 Connecting to database: {}", database_url);
4949

50-
#[cfg(feature = "postgres")]
50+
#[cfg(all(feature = "postgres", not(feature = "mysql")))]
5151
let pool = sqlx::PgPool::connect(&database_url).await?;
5252

53-
#[cfg(feature = "mysql")]
53+
#[cfg(all(feature = "mysql", not(feature = "postgres")))]
5454
let pool = sqlx::MySqlPool::connect(&database_url).await?;
5555

56+
// Default to PostgreSQL when both features are enabled
57+
#[cfg(all(feature = "postgres", feature = "mysql"))]
58+
let pool = sqlx::PgPool::connect(&database_url).await?;
59+
5660
let queue = Arc::new(JobQueue::new(pool));
5761

5862
// Note: Database tables should be created using migrations

hammerwork-web/tests/integration_tests.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ mod test_helpers {
246246
use std::process::Command;
247247

248248
/// Check if PostgreSQL test database is available
249+
#[allow(dead_code)]
249250
pub fn postgres_available() -> bool {
250251
let output = Command::new("pg_isready")
251252
.arg("-h")
@@ -263,6 +264,7 @@ mod test_helpers {
263264
}
264265

265266
/// Check if MySQL test database is available
267+
#[allow(dead_code)]
266268
pub fn mysql_available() -> bool {
267269
let output = Command::new("mysql")
268270
.arg("--host=127.0.0.1")
@@ -279,6 +281,7 @@ mod test_helpers {
279281
}
280282

281283
/// Create a test configuration with minimal setup
284+
#[allow(dead_code)]
282285
pub fn create_test_config() -> DashboardConfig {
283286
let temp_dir = tempdir().expect("Failed to create temp directory");
284287

src/migrations/mysql.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ impl MigrationRunner<sqlx::MySql> for MySqlMigrationRunner {
128128

129129
#[cfg(test)]
130130
mod tests {
131-
use super::*;
131+
// Tests for MySQL migration functionality
132132

133133
#[test]
134134
fn test_sql_statement_splitting() {

src/migrations/postgres.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ impl MigrationRunner<sqlx::Postgres> for PostgresMigrationRunner {
130130

131131
#[cfg(test)]
132132
mod tests {
133-
use super::*;
133+
// Tests for PostgreSQL migration functionality
134134

135135
#[test]
136136
fn test_sql_statement_splitting() {

src/queue/mysql.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ impl DatabaseQueue for crate::queue::JobQueue<MySql> {
253253

254254
let row = sqlx::query_as::<_, JobRow>(
255255
r#"
256-
SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name
256+
SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context
257257
FROM hammerwork_jobs
258258
WHERE queue_name = ?
259259
AND status = ?
@@ -313,7 +313,7 @@ impl DatabaseQueue for crate::queue::JobQueue<MySql> {
313313
// Get available jobs by priority
314314
let available_jobs = sqlx::query_as::<_, JobRow>(
315315
r#"
316-
SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name
316+
SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context
317317
FROM hammerwork_jobs
318318
WHERE queue_name = ?
319319
AND status = ?

src/worker.rs

Lines changed: 53 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,10 +1082,11 @@ where
10821082
///
10831083
/// # Examples
10841084
///
1085-
/// ```rust
1085+
/// ```rust,no_run
10861086
/// # use hammerwork::{Worker, worker::{JobEventHooks, JobHookEvent}};
10871087
/// # use std::sync::Arc;
1088-
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await.unwrap()));
1088+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1089+
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await?));
10891090
/// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) }));
10901091
///
10911092
/// let hooks = JobEventHooks::new()
@@ -1105,6 +1106,8 @@ where
11051106
///
11061107
/// let worker = Worker::new(queue, "traced_queue".to_string(), handler)
11071108
/// .with_event_hooks(hooks);
1109+
/// # Ok(())
1110+
/// # }
11081111
/// ```
11091112
pub fn with_event_hooks(mut self, hooks: JobEventHooks) -> Self {
11101113
self.event_hooks = hooks;
@@ -1122,16 +1125,19 @@ where
11221125
///
11231126
/// # Examples
11241127
///
1125-
/// ```rust
1128+
/// ```rust,no_run
11261129
/// # use hammerwork::Worker;
11271130
/// # use std::sync::Arc;
1128-
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await.unwrap()));
1131+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1132+
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await?));
11291133
/// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) }));
11301134
///
11311135
/// let worker = Worker::new(queue, "queue".to_string(), handler)
11321136
/// .on_job_start(|event| {
11331137
/// println!("Starting job: {}", event.job.id);
11341138
/// });
1139+
/// # Ok(())
1140+
/// # }
11351141
/// ```
11361142
pub fn on_job_start<F>(mut self, handler: F) -> Self
11371143
where
@@ -1149,10 +1155,11 @@ where
11491155
///
11501156
/// # Examples
11511157
///
1152-
/// ```rust
1158+
/// ```rust,no_run
11531159
/// # use hammerwork::Worker;
11541160
/// # use std::sync::Arc;
1155-
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await.unwrap()));
1161+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1162+
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await?));
11561163
/// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) }));
11571164
///
11581165
/// let worker = Worker::new(queue, "queue".to_string(), handler)
@@ -1161,6 +1168,8 @@ where
11611168
/// println!("Job {} completed in {:?}", event.job.id, duration);
11621169
/// }
11631170
/// });
1171+
/// # Ok(())
1172+
/// # }
11641173
/// ```
11651174
pub fn on_job_complete<F>(mut self, handler: F) -> Self
11661175
where
@@ -1178,10 +1187,11 @@ where
11781187
///
11791188
/// # Examples
11801189
///
1181-
/// ```rust
1190+
/// ```rust,no_run
11821191
/// # use hammerwork::Worker;
11831192
/// # use std::sync::Arc;
1184-
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await.unwrap()));
1193+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1194+
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await?));
11851195
/// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) }));
11861196
///
11871197
/// let worker = Worker::new(queue, "queue".to_string(), handler)
@@ -1190,6 +1200,8 @@ where
11901200
/// eprintln!("Job {} failed: {}", event.job.id, error);
11911201
/// }
11921202
/// });
1203+
/// # Ok(())
1204+
/// # }
11931205
/// ```
11941206
pub fn on_job_fail<F>(mut self, handler: F) -> Self
11951207
where
@@ -1207,16 +1219,19 @@ where
12071219
///
12081220
/// # Examples
12091221
///
1210-
/// ```rust
1222+
/// ```rust,no_run
12111223
/// # use hammerwork::Worker;
12121224
/// # use std::sync::Arc;
1213-
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await.unwrap()));
1225+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1226+
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await?));
12141227
/// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) }));
12151228
///
12161229
/// let worker = Worker::new(queue, "queue".to_string(), handler)
12171230
/// .on_job_timeout(|event| {
12181231
/// println!("Job {} timed out after {:?}", event.job.id, event.duration);
12191232
/// });
1233+
/// # Ok(())
1234+
/// # }
12201235
/// ```
12211236
pub fn on_job_timeout<F>(mut self, handler: F) -> Self
12221237
where
@@ -1234,16 +1249,19 @@ where
12341249
///
12351250
/// # Examples
12361251
///
1237-
/// ```rust
1252+
/// ```rust,no_run
12381253
/// # use hammerwork::Worker;
12391254
/// # use std::sync::Arc;
1240-
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await.unwrap()));
1255+
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1256+
/// # let queue = Arc::new(hammerwork::JobQueue::new(sqlx::PgPool::connect("").await?));
12411257
/// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) }));
12421258
///
12431259
/// let worker = Worker::new(queue, "queue".to_string(), handler)
12441260
/// .on_job_retry(|event| {
12451261
/// println!("Retrying job {} due to: {:?}", event.job.id, event.error);
12461262
/// });
1263+
/// # Ok(())
1264+
/// # }
12471265
/// ```
12481266
pub fn on_job_retry<F>(mut self, handler: F) -> Self
12491267
where
@@ -1451,7 +1469,7 @@ where
14511469
span.record("error.type", "timeout");
14521470
span.record(
14531471
"error.message",
1454-
&format!("Job timed out after {:?}", timeout),
1472+
format!("Job timed out after {:?}", timeout),
14551473
);
14561474
}
14571475

@@ -2687,8 +2705,10 @@ mod tests {
26872705
#[test]
26882706
fn test_scaling_decision_logic() {
26892707
// This test simulates the scaling decision logic
2690-
let mut metrics = AutoscaleMetrics::default();
2691-
metrics.active_workers = 3;
2708+
let mut metrics = AutoscaleMetrics {
2709+
active_workers: 3,
2710+
..Default::default()
2711+
};
26922712

26932713
let config = AutoscaleConfig::default();
26942714

@@ -2735,14 +2755,13 @@ mod tests {
27352755
#[test]
27362756
fn test_queue_depth_averaging() {
27372757
let now = Utc::now();
2738-
let mut history = Vec::new();
2739-
2740-
// Add some history entries
2741-
history.push((now - chrono::Duration::seconds(25), 10));
2742-
history.push((now - chrono::Duration::seconds(20), 8));
2743-
history.push((now - chrono::Duration::seconds(15), 12));
2744-
history.push((now - chrono::Duration::seconds(10), 6));
2745-
history.push((now - chrono::Duration::seconds(5), 14));
2758+
let history = vec![
2759+
(now - chrono::Duration::seconds(25), 10),
2760+
(now - chrono::Duration::seconds(20), 8),
2761+
(now - chrono::Duration::seconds(15), 12),
2762+
(now - chrono::Duration::seconds(10), 6),
2763+
(now - chrono::Duration::seconds(5), 14),
2764+
];
27462765

27472766
// Calculate average
27482767
let avg =
@@ -2764,10 +2783,10 @@ mod tests {
27642783
#[test]
27652784
fn test_worker_count_boundaries() {
27662785
let config = AutoscaleConfig::default();
2767-
let mut metrics = AutoscaleMetrics::default();
2768-
2769-
// Test scaling up to max workers
2770-
metrics.active_workers = config.max_workers - 1;
2786+
let mut metrics = AutoscaleMetrics {
2787+
active_workers: config.max_workers - 1,
2788+
..Default::default()
2789+
};
27712790
let new_count = (metrics.active_workers + config.scale_step).min(config.max_workers);
27722791
assert_eq!(new_count, config.max_workers);
27732792

@@ -2813,14 +2832,13 @@ mod tests {
28132832
#[test]
28142833
fn test_history_cleanup() {
28152834
let now = Utc::now();
2816-
let mut history = Vec::new();
2817-
2818-
// Add entries with various ages
2819-
history.push((now - chrono::Duration::seconds(60), 10)); // Too old
2820-
history.push((now - chrono::Duration::seconds(45), 8)); // Too old
2821-
history.push((now - chrono::Duration::seconds(25), 12)); // Recent
2822-
history.push((now - chrono::Duration::seconds(15), 6)); // Recent
2823-
history.push((now - chrono::Duration::seconds(5), 14)); // Recent
2835+
let mut history = vec![
2836+
(now - chrono::Duration::seconds(60), 10), // Too old
2837+
(now - chrono::Duration::seconds(45), 8), // Too old
2838+
(now - chrono::Duration::seconds(25), 12), // Recent
2839+
(now - chrono::Duration::seconds(15), 6), // Recent
2840+
(now - chrono::Duration::seconds(5), 14), // Recent
2841+
];
28242842

28252843
// Filter based on 30-second window
28262844
let evaluation_window = Duration::from_secs(30);

tests/batch_tests.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
mod test_utils;
22

33
use hammerwork::{
4-
Job,
4+
BatchStatus, Job, JobStatus,
55
batch::{JobBatch, PartialFailureMode},
6+
queue::DatabaseQueue,
67
};
78
use serde_json::json;
89
// use std::sync::Arc;

0 commit comments

Comments
 (0)