Skip to content

Commit

Permalink
Simplified DB init
Browse files Browse the repository at this point in the history
  • Loading branch information
joepio committed Feb 4, 2025
1 parent 02d76d3 commit 58cd95a
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 14 deletions.
2 changes: 1 addition & 1 deletion lib/benches/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn random_resource(atom: &Atom) -> Resource {
}

fn criterion_benchmark(c: &mut Criterion) {
let store = Db::init_temp("bench").unwrap();
let store = Db::init_temp().unwrap();

c.bench_function("add_resource", |b| {
b.iter(|| {
Expand Down
1 change: 1 addition & 0 deletions lib/src/client/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub fn fetch_body(
content_type: &str,
client_agent: Option<&Agent>,
) -> AtomicResult<String> {
println!("Fetching body from {}", url);
if !url.starts_with("http") {
return Err(format!("Could not fetch url '{}', must start with http.", url).into());
}
Expand Down
11 changes: 8 additions & 3 deletions lib/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,9 @@ impl Db {

/// Create a temporary Db in `.temp/db/{id}`. Useful for testing.
/// Populates the database, creates a default agent, and sets the server_url to "http://localhost/".
pub fn init_temp(id: &str) -> AtomicResult<Db> {
let tmp_dir_path = format!(".temp/db/{}", id);
let _try_remove_existing = std::fs::remove_dir_all(&tmp_dir_path);
pub fn init_temp() -> AtomicResult<Db> {
let random_id = crate::utils::random_string(10);
let tmp_dir_path = format!(".temp/db/{}", random_id);
let store = Db::init(std::path::Path::new(&tmp_dir_path), "https://localhost")?;
let agent = store.create_agent(None)?;
store.set_default_agent(agent);
Expand Down Expand Up @@ -557,6 +557,11 @@ impl Db {

impl Drop for Db {
fn drop(&mut self) {
// Remove if it's a temporary test database
if cfg!(test) && self.path.to_string_lossy().contains(".temp/db/") {
let _ = std::fs::remove_dir_all(&self.path);
return;
}
match self.db.flush() {
Ok(..) => (),
Err(e) => eprintln!("Failed to flush the database: {}", e),
Expand Down
2 changes: 1 addition & 1 deletion lib/src/db/query_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ pub mod test {
let instant = std::time::Instant::now();

{
let store = &Db::init_temp("should_update_or_not").unwrap();
let store = &Db::init_temp().unwrap();

let prop = urls::IS_A.to_string();
let class = urls::AGENT;
Expand Down
30 changes: 22 additions & 8 deletions lib/src/db/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use ntest::timeout;
use lazy_static::lazy_static; // 1.4.0
use std::sync::Mutex;
lazy_static! {
pub static ref DB: Mutex<Db> = Mutex::new(Db::init_temp("shared").unwrap());
pub static ref DB: Mutex<Db> = Mutex::new(Db::init_temp().unwrap());
}

#[test]
Expand Down Expand Up @@ -59,7 +59,7 @@ fn basic() {

#[test]
fn populate_collections() {
let store = Db::init_temp("populate_collections").unwrap();
let store = Db::init_temp().unwrap();
let subjects: Vec<String> = store
.all_resources(false)
.map(|r| r.get_subject().into())
Expand Down Expand Up @@ -89,7 +89,7 @@ fn populate_collections() {
/// Check if a resource is properly removed from the DB after a delete command.
/// Also counts commits.
fn destroy_resource_and_check_collection_and_commits() {
let store = Db::init_temp("counter").unwrap();
let store = Db::init_temp().unwrap();
let agents_url = store.get_server_url().set_route(Routes::Agents).to_string();
let for_agent = &ForAgent::Public;
let agents_collection_1 = store
Expand Down Expand Up @@ -198,7 +198,7 @@ fn destroy_resource_and_check_collection_and_commits() {

#[test]
fn get_extended_resource_pagination() {
let store = Db::init_temp("get_extended_resource_pagination").unwrap();
let store = Db::init_temp().unwrap();
let subject = format!(
"{}collections/commits?current_page=2&page_size=99999",
store.get_server_url()
Expand Down Expand Up @@ -231,7 +231,7 @@ fn get_extended_resource_pagination() {
fn queries() {
// Re-using the same instance can cause issues with testing concurrently.
// let store = &DB.lock().unwrap().clone();
let store = &Db::init_temp("queries").unwrap();
let store = &Db::init_temp().unwrap();

let demo_val = Value::Slug("myval".to_string());
let demo_reference = Value::AtomicUrl(urls::PARAGRAPH.into());
Expand Down Expand Up @@ -397,7 +397,7 @@ fn queries() {
/// Check if `include_external` is respected.
#[test]
fn query_include_external() {
let store = &Db::init_temp("query_include_external").unwrap();
let store = &Db::init_temp().unwrap();

let mut q = Query {
property: Some(urls::DESCRIPTION.into()),
Expand All @@ -423,9 +423,23 @@ fn query_include_external() {
);
}

#[test]
fn drop_speed() {
let start = std::time::Instant::now();
println!("Start: {:?}", start.elapsed());
assert!(
std::time::Duration::from_secs(1) > start.elapsed(),
"initializing DB too slow"
);
let store = Db::init_temp().unwrap();
println!("Init db: {:?}", start.elapsed());
drop(store);
println!("Drop db: {:?}", start.elapsed());
}

#[test]
fn test_db_resources_all() {
let store = &Db::init_temp("resources_all").unwrap();
let store = &Db::init_temp().unwrap();
let res_no_include = store.all_resources(false).count();
let res_include = store.all_resources(true).count();
assert!(
Expand All @@ -437,7 +451,7 @@ fn test_db_resources_all() {
#[test]
/// Changing these values actually correctly updates the index.
fn index_invalidate_cache() {
let store = &Db::init_temp("invalidate_cache").unwrap();
let store = &Db::init_temp().unwrap();

// Make sure to use Properties that are not in the default store

Expand Down
2 changes: 1 addition & 1 deletion server/src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ mod tests {
use super::resource_to_facet;
#[test]
fn facet_contains_subfacet() {
let store = atomic_lib::Db::init_temp("facet_contains").unwrap();
let store = atomic_lib::Db::init_temp().unwrap();
let mut prev_subject: Option<String> = None;
let mut resources = Vec::new();

Expand Down

0 comments on commit 58cd95a

Please sign in to comment.