State testing
This commit is contained in:
parent
07b40105c2
commit
efcb7a305b
1 changed files with 20 additions and 33 deletions
|
@ -55,9 +55,12 @@ impl ServerState {
|
|||
None => error!("Failed to create default user..."),
|
||||
}
|
||||
|
||||
// We want dummy posts
|
||||
lipsum_setup(&pool).await.unwrap();
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
debug_setup(&pool).await.unwrap();
|
||||
lipsum_setup(&pool).await.unwrap();
|
||||
|
||||
Self { pool }
|
||||
}
|
||||
}
|
||||
|
@ -66,48 +69,18 @@ impl ServerState {
|
|||
// Mostly useful for debugging new posts, as we need to satisfy foreign key constraints.
|
||||
#[cfg(debug_assertions)]
|
||||
async fn debug_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
||||
use lipsum::lipsum;
|
||||
use rand::prelude::*;
|
||||
use sqlx::query;
|
||||
|
||||
use crate::db::db_new_user;
|
||||
|
||||
db_new_user("user".to_string(), "pass".to_string(), pool).await;
|
||||
|
||||
// Check if the demo post already exists
|
||||
let no_posts = query!("SELECT * FROM posts WHERE id = 1",)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.ok()
|
||||
.is_none();
|
||||
|
||||
// If the demo user already has a post, don't insert another one
|
||||
if no_posts {
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
// This requires that the user with id 1 exists in the user table
|
||||
for _ in 0..100 {
|
||||
query!(
|
||||
"INSERT INTO posts (user_id, content) VALUES (1, $1)",
|
||||
lipsum(rng.gen_range(10..100))
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
query!("INSERT INTO posts (user_id, content) VALUES (1, 'Hello world! The demo username is user and the password is pass.')",)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Inserts a bunch of dummy posts into the database
|
||||
async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
||||
use lipsum::lipsum;
|
||||
use rand::prelude::*;
|
||||
use sqlx::query;
|
||||
|
||||
// Fetch any user
|
||||
let user_exist = query!("SELECT * FROM users",)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
|
@ -117,6 +90,7 @@ async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
|||
if user_exist {
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
// Insert a 100 dummy posts.
|
||||
// This requires that the user with id 1 exists in the user table
|
||||
for _ in 0..100 {
|
||||
query!(
|
||||
|
@ -130,3 +104,16 @@ async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_server_state() {
|
||||
let state = CaptchaState::new();
|
||||
assert!(state.capthca_db.lock().unwrap().is_empty());
|
||||
state.capthca_db.lock().unwrap().insert("test".to_string());
|
||||
assert!(!state.capthca_db.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue