Skip to content

Commit ce4d808

Browse files
committed
add test
1 parent 759b04a commit ce4d808

1 file changed

Lines changed: 50 additions & 3 deletions

File tree

  • books/sqlx/examples/sqlx-sqlite-todo/src

books/sqlx/examples/sqlx-sqlite-todo/src/main.rs

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ enum Command {
2020

2121
#[tokio::main(flavor = "current_thread")]
2222
async fn main() -> anyhow::Result<()> {
23+
let args = Args::parse();
2324
let database_file = env::var("DATABASE_FILE")
2425
.context("DATABASE_FILE is not set. Set it to the SQLite database file path, for example: DATABASE_FILE=todos.db")?;
25-
run(database_file).await
26+
run(args, database_file).await
2627
}
2728

28-
async fn run(database_file: String) -> anyhow::Result<()> {
29-
let args = Args::parse();
29+
async fn run(args: Args, database_file: String) -> anyhow::Result<()> {
3030
let options = SqliteConnectOptions::new()
3131
.filename(database_file)
3232
.create_if_missing(true);
@@ -56,6 +56,53 @@ async fn run(database_file: String) -> anyhow::Result<()> {
5656
Ok(())
5757
}
5858

59+
#[cfg(test)]
60+
mod tests {
61+
use super::{Args, Command, run};
62+
use sqlx::{Row, sqlite::SqlitePool};
63+
use std::{
64+
env,
65+
path::PathBuf,
66+
time::{SystemTime, UNIX_EPOCH},
67+
};
68+
69+
#[tokio::test(flavor = "current_thread")]
70+
async fn run_adds_a_todo() {
71+
let database_file = unique_database_file("run-adds-a-todo");
72+
let args = Args {
73+
cmd: Some(Command::Add {
74+
description: "buy milk".to_string(),
75+
}),
76+
};
77+
78+
run(args, database_file.to_string_lossy().into_owned())
79+
.await
80+
.unwrap();
81+
82+
let pool = SqlitePool::connect(&format!("sqlite://{}", database_file.display()))
83+
.await
84+
.unwrap();
85+
let row = sqlx::query("SELECT description, done FROM todos WHERE id = 1")
86+
.fetch_one(&pool)
87+
.await
88+
.unwrap();
89+
90+
assert_eq!(row.try_get::<String, _>("description").unwrap(), "buy milk");
91+
assert!(!row.try_get::<bool, _>("done").unwrap());
92+
93+
std::fs::remove_file(database_file).unwrap();
94+
}
95+
96+
fn unique_database_file(prefix: &str) -> PathBuf {
97+
let unique_suffix = SystemTime::now()
98+
.duration_since(UNIX_EPOCH)
99+
.unwrap()
100+
.as_nanos();
101+
102+
env::temp_dir().join(format!("sqlx-sqlite-todo-{prefix}-{unique_suffix}.db"))
103+
}
104+
}
105+
59106
async fn initialize_database(pool: &SqlitePool) -> anyhow::Result<()> {
60107
sqlx::query(
61108
r#"

0 commit comments

Comments
 (0)