Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore: test cases for sea-orm-macros #504

Closed
tyt2y3 opened this issue Feb 5, 2022 · 6 comments
Closed

Chore: test cases for sea-orm-macros #504

tyt2y3 opened this issue Feb 5, 2022 · 6 comments
Labels
good first issue Good for newcomers

Comments

@tyt2y3
Copy link
Member

tyt2y3 commented Feb 5, 2022

thanks for the catch! @billy1624 I imagine we can also add some test cases using the MockInterface?

Originally posted by @tyt2y3 in #494 (comment)

@tyt2y3 tyt2y3 changed the title Whore: test cases for sea-orm-macros Chore: test cases for sea-orm-macros Feb 5, 2022
@tyt2y3 tyt2y3 added the good first issue Good for newcomers label Mar 15, 2022
@sbshah97
Copy link

Hey I'd love to try this out, i am new to the project but would love the learning.

@billy1624
Copy link
Member

Hey @sbshah97, happy new year! Sorry for the delay. Do you have anything implementation plan in mind that you want to share? We better have a clear and workable testing plan before coding.

@sbshah97
Copy link

sbshah97 commented Jan 3, 2023

I don't think I have any clear plan. I'd love to play with the code and get it up first. I plan to run through the code using the CONTRIBUTING guide and set the repo up on my local system. Do you have any additional pointers apart from the Getting Started guide?

Also any pointers on how I can call this particular code path ?

@JonasCir
Copy link

JonasCir commented Jan 3, 2023

Is this ticket about asserting that the generated code by a macro matches the expected value?

@billy1624
Copy link
Member

billy1624 commented Jan 4, 2023

This ticket want to test the expected behaviour of FromQueryResult::from_query_result() via mock test. From that we can assert the implementation of FromQueryResult derive macro is sounded.

An example mock test:

#[smol_potat::test]
async fn update_record_not_found_1() -> Result<(), DbErr> {
let db = MockDatabase::new(DbBackend::Postgres)
.append_query_results(vec![
vec![cake::Model {
id: 1,
name: "Cheese Cake".to_owned(),
}],
vec![],
vec![],
vec![],
])
.append_exec_results(vec![MockExecResult {
last_insert_id: 0,
rows_affected: 0,
}])
.into_connection();
let model = cake::Model {
id: 1,
name: "New York Cheese".to_owned(),
};
assert_eq!(
cake::ActiveModel {
name: Set("Cheese Cake".to_owned()),
..model.into_active_model()
}
.update(&db)
.await?,
cake::Model {
id: 1,
name: "Cheese Cake".to_owned(),
}
);
let model = cake::Model {
id: 2,
name: "New York Cheese".to_owned(),
};
assert_eq!(
cake::ActiveModel {
name: Set("Cheese Cake".to_owned()),
..model.clone().into_active_model()
}
.update(&db)
.await,
Err(DbErr::RecordNotFound(
"None of the database rows are affected".to_owned()
))
);
assert_eq!(
cake::Entity::update(cake::ActiveModel {
name: Set("Cheese Cake".to_owned()),
..model.clone().into_active_model()
})
.exec(&db)
.await,
Err(DbErr::RecordNotFound(
"None of the database rows are affected".to_owned()
))
);
assert_eq!(
Update::one(cake::ActiveModel {
name: Set("Cheese Cake".to_owned()),
..model.into_active_model()
})
.exec(&db)
.await,
Err(DbErr::RecordNotFound(
"None of the database rows are affected".to_owned()
))
);
assert_eq!(
Update::many(cake::Entity)
.col_expr(cake::Column::Name, Expr::value("Cheese Cake".to_owned()))
.filter(cake::Column::Id.eq(2))
.exec(&db)
.await,
Ok(UpdateResult { rows_affected: 0 })
);
assert_eq!(
db.into_transaction_log(),
vec![
Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"UPDATE "cake" SET "name" = $1 WHERE "cake"."id" = $2 RETURNING "id", "name""#,
vec!["Cheese Cake".into(), 1i32.into()]
),
Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"UPDATE "cake" SET "name" = $1 WHERE "cake"."id" = $2 RETURNING "id", "name""#,
vec!["Cheese Cake".into(), 2i32.into()]
),
Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"UPDATE "cake" SET "name" = $1 WHERE "cake"."id" = $2 RETURNING "id", "name""#,
vec!["Cheese Cake".into(), 2i32.into()]
),
Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"UPDATE "cake" SET "name" = $1 WHERE "cake"."id" = $2 RETURNING "id", "name""#,
vec!["Cheese Cake".into(), 2i32.into()]
),
Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"UPDATE "cake" SET "name" = $1 WHERE "cake"."id" = $2"#,
vec!["Cheese Cake".into(), 2i32.into()]
),
]
);
Ok(())
}

@sbshah97
Copy link

sbshah97 commented Jan 6, 2023

Sorry I have a rather trivial question here. Is this the method we are looking to test on?

/// Method to derive a [QueryResult](sea_orm::QueryResult)
pub fn expand_derive_from_query_result(ident: Ident, data: Data) -> syn::Result<TokenStream> {
    let fields = match data {
        Data::Struct(DataStruct {
            fields: Fields::Named(named),
            ..
        }) => named.named,
        _ => {
            return Ok(quote_spanned! {
                ident.span() => compile_error!("you can only derive FromQueryResult on structs");
            })
        }
    };

    let field: Vec<Ident> = fields
        .into_iter()
        .map(|Field { ident, .. }| format_ident!("{}", ident.unwrap().to_string()))
        .collect();

    let name: Vec<TokenStream> = field
        .iter()
        .map(|f| {
            let s = f.unraw().to_string();
            quote! { #s }
        })
        .collect();

    Ok(quote!(
        #[automatically_derived]
        impl sea_orm::FromQueryResult for #ident {
            fn from_query_result(row: &sea_orm::QueryResult, pre: &str) -> std::result::Result<Self, sea_orm::DbErr> {
                Ok(Self {
                    #(#field: row.try_get(pre, #name)?),*
                })
            }
        }
    ))
}

@tyt2y3 tyt2y3 closed this as completed Feb 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
Archived in project
Development

No branches or pull requests

4 participants