Guidelines for running tests and writing test cases for pwr-bot
Testing is crucial for maintaining code quality in pwr-bot. This guide covers running tests, writing test cases, and working with the SQLX_OFFLINE mode.
# Run all testscargo test --all-features# Run specific testcargo test test_name# Run tests in a specific filecargo test --test file_name# Show test outputcargo test -- --nocapture
The tests/common.rs:17-37 file provides shared utilities:
/// Sets up a temporary test database.pub async fn setup_db() -> (Arc<Repository>, PathBuf) { let uuid = Uuid::new_v4(); let db_path = std::env::temp_dir().join(format!("pwr-bot-test-{}.db", uuid)); let db_url = format!("sqlite://{}", db_path.to_str().unwrap()); let db = Repository::new(&db_url, db_path.to_str().unwrap()) .await .expect("Failed to create database"); db.run_migrations().await.expect("Failed to run migrations"); (Arc::new(db), db_path)}
use pwr_bot::module::MyStruct;#[tokio::test]async fn test_my_feature() { // Arrange: Set up test data let value = MyStruct::new(); // Act: Execute the test let result = value.do_something().await; // Assert: Verify expectations assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_value);}
All async tests must use #[tokio::test] instead of #[test].
mod common;use common::{setup_db, teardown_db};#[tokio::test]async fn test_database_operation() { // Setup let (db, db_path) = setup_db().await; // Test your database operations let result = db.some_table.insert(data).await; assert!(result.is_ok()); // Cleanup teardown_db(db_path).await;}
Store API responses in tests/responses/ and load them:
tests/mock_platforms_test.rs:13-19
use std::path::PathBuf;/// Loads a test response file from the responses directory.fn get_response(filename: &str) -> String { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("tests/responses"); path.push(filename); std::fs::read_to_string(path).expect("Failed to read response file")}
#[tokio::test]async fn test_fetch_source_with_valid_id() { // Test happy path}#[tokio::test]async fn test_fetch_source_with_invalid_id() { // Test error handling}#[tokio::test]async fn test_fetch_source_when_not_found() { // Test edge case}
7
Clean up test resources
8
Always clean up temporary resources:
9
#[tokio::test]async fn test_with_cleanup() { let (db, db_path) = setup_db().await; // Your test code // Cleanup - always runs even if test panics teardown_db(db_path).await;}