Skip to content

Commit

Permalink
add integration test, and expose more as library
Browse files Browse the repository at this point in the history
  • Loading branch information
lovasoa committed Aug 27, 2023
1 parent b409e08 commit 62bd001
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 63 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rust-analyzer.linkedProjects": [
"./Cargo.toml"
]
}
3 changes: 2 additions & 1 deletion src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,10 @@ fn default_database_connection_acquire_timeout_seconds() -> f64 {
}

#[cfg(test)]
pub(crate) mod tests {
pub mod tests {
use super::AppConfig;

#[must_use]
pub fn test_config() -> AppConfig {
serde_json::from_str::<AppConfig>(
r#"{
Expand Down
7 changes: 7 additions & 0 deletions src/file_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,14 @@ pub struct FileCache<T: AsyncFromStrWithState> {
static_files: HashMap<PathBuf, Cached<T>>,
}

impl<T: AsyncFromStrWithState> Default for FileCache<T> {
fn default() -> Self {
Self::new()
}
}

impl<T: AsyncFromStrWithState> FileCache<T> {
#[must_use]
pub fn new() -> Self {
Self {
cache: Arc::default(),
Expand Down
63 changes: 63 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#![deny(clippy::pedantic)]
#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]

extern crate core;

pub mod app_config;
pub mod file_cache;
pub mod filesystem;
pub mod render;
pub mod templates;
pub mod utils;
pub mod webserver;

use crate::app_config::AppConfig;
use crate::filesystem::FileSystem;
use crate::webserver::database::{FileCache, ParsedSqlFile};
use std::env;
use std::net::SocketAddr;
use std::path::PathBuf;
use templates::AllTemplates;
use webserver::Database;

pub const TEMPLATES_DIR: &str = "sqlpage/templates";
pub const MIGRATIONS_DIR: &str = "sqlpage/migrations";

pub struct AppState {
pub db: Database,
all_templates: AllTemplates,
sql_file_cache: FileCache<ParsedSqlFile>,
file_system: FileSystem,
}

impl AppState {
pub async fn init(config: &AppConfig) -> anyhow::Result<Self> {
// Connect to the database
let db = Database::init(config).await?;
let all_templates = AllTemplates::init()?;
let web_root = get_web_root();
let mut sql_file_cache = FileCache::new();
let file_system = FileSystem::init(&web_root, &db).await;
sql_file_cache.add_static(
PathBuf::from("index.sql"),
ParsedSqlFile::new(&db, include_str!("../index.sql")).await,
);
Ok(AppState {
db,
all_templates,
sql_file_cache,
file_system,
})
}
}

pub fn get_web_root() -> PathBuf {
env::var("WEB_ROOT").map_or_else(
|_| PathBuf::from(&std::path::Component::CurDir),
PathBuf::from,
)
}

pub struct Config {
pub listen_on: SocketAddr,
}
62 changes: 1 addition & 61 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,64 +1,4 @@
#![deny(clippy::pedantic)]
extern crate core;

mod app_config;
mod file_cache;
mod filesystem;
mod render;
mod templates;
mod utils;
mod webserver;

use crate::app_config::AppConfig;
use crate::filesystem::FileSystem;
use crate::webserver::database::{FileCache, ParsedSqlFile};
use crate::webserver::Database;
use std::env;
use std::net::SocketAddr;
use std::path::PathBuf;
use templates::AllTemplates;

const TEMPLATES_DIR: &str = "sqlpage/templates";
const MIGRATIONS_DIR: &str = "sqlpage/migrations";

pub struct AppState {
db: Database,
all_templates: AllTemplates,
sql_file_cache: FileCache<ParsedSqlFile>,
file_system: FileSystem,
}

impl AppState {
async fn init(config: &AppConfig) -> anyhow::Result<Self> {
// Connect to the database
let db = Database::init(config).await?;
let all_templates = AllTemplates::init()?;
let web_root = get_web_root();
let mut sql_file_cache = FileCache::new();
let file_system = FileSystem::init(&web_root, &db).await;
sql_file_cache.add_static(
PathBuf::from("index.sql"),
ParsedSqlFile::new(&db, include_str!("../index.sql")).await,
);
Ok(AppState {
db,
all_templates,
sql_file_cache,
file_system,
})
}
}

fn get_web_root() -> PathBuf {
env::var("WEB_ROOT").map_or_else(
|_| PathBuf::from(&std::path::Component::CurDir),
PathBuf::from,
)
}

pub struct Config {
listen_on: SocketAddr,
}
use sqlpage::{app_config, webserver, AppState, Config};

#[actix_web::main]
async fn main() {
Expand Down
1 change: 1 addition & 0 deletions src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub struct SplitTemplate {
}

impl SplitTemplate {
#[must_use]
pub fn name(&self) -> Option<&str> {
self.before_list.name.as_deref()
}
Expand Down
1 change: 1 addition & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use serde_json::{Map, Value};

#[must_use]
pub fn add_value_to_map(
mut map: Map<String, Value>,
(key, value): (String, Value),
Expand Down
1 change: 1 addition & 0 deletions src/webserver/database/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ fn function_arg_expr(arg: &mut FunctionArg) -> Option<&mut Expr> {
}

#[inline]
#[must_use]
pub fn make_placeholder(db_kind: AnyKind, arg_number: usize) -> String {
if let Some((_, prefix)) = PLACEHOLDER_PREFIXES
.iter()
Expand Down
5 changes: 4 additions & 1 deletion src/webserver/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ impl SingleOrVec {
}
}

#[must_use]
pub fn as_json_str(&self) -> Cow<'_, str> {
match self {
SingleOrVec::Single(x) => Cow::Borrowed(x),
Expand Down Expand Up @@ -464,7 +465,9 @@ async fn serve_file(
})
}

async fn main_handler(mut service_request: ServiceRequest) -> actix_web::Result<ServiceResponse> {
pub async fn main_handler(
mut service_request: ServiceRequest,
) -> actix_web::Result<ServiceResponse> {
let path = req_path(&service_request);
let sql_file_path = path_to_sql_file(&path);
if let Some(sql_path) = sql_file_path {
Expand Down
34 changes: 34 additions & 0 deletions tests/index.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use actix_web::{
http::{self, header::ContentType},
test,
};
use sqlpage::{app_config::AppConfig, webserver::http::main_handler, AppState};

#[actix_web::test]
async fn test_index_ok() {
let config = test_config();
let state = AppState::init(&config).await.unwrap();
let data = actix_web::web::Data::new(state);
let req = test::TestRequest::default()
.app_data(data)
.insert_header(ContentType::plaintext())
.to_srv_request();
let resp = main_handler(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let body = test::read_body(resp).await;
assert!(body.starts_with(b"<!DOCTYPE html>"));
// the body should contain the strint "It works!" and should not contain the string "error"
let body = String::from_utf8(body.to_vec()).unwrap();
assert!(body.contains("It works !"));
assert!(!body.contains("error"));
}

pub fn test_config() -> AppConfig {
serde_json::from_str::<AppConfig>(
r#"{
"database_url": "sqlite::memory:",
"listen_on": "111.111.111.111:1"
}"#,
)
.unwrap()
}

0 comments on commit 62bd001

Please sign in to comment.