Skip to content

Unit Test

Andrei edited this page Feb 25, 2025 · 1 revision

Why we do them

Unit test serve to validate that logic complies with specifications, they are also useful when a bug is found to quickly replicate it. Unit test are super important in managing regression, and increase confidence in doing refactor work.

Examples

Checking postgres enum vs rust enum

Derive strum on the enum

#[cfg_attr(test, derive(strum::EnumIter))]
enum MyEnum {

In test

#[actix_rt::test]
async fn test_enum() {
    let (_, connection, _, _) =
        setup_all("test_enum", MockDataInserts::none()).await;

    let repo = Repository::new(&connection);
    // Try upsert all variants, confirm that diesel enums match postgres
    for variant in MyEnum::iter() {
        let id = format!("{variant:?}");
        let result = repo.upsert_one(&Row {
            id: id.clone(),
            enum: variant.clone(),
            ..Default::default()
        });
        assert_matches!(result, Ok(_));

        assert_eq!(
            repo.find_one_by_id(&id),
            Ok(Some(Row {
                id,
                enum: variant.clone(),
                ..Default::default()
            }))
        );
    }
}

// TODO more examples and base test snippets