morethantext-web/src/morethantext/databases.rs

82 lines
2.1 KiB
Rust

use std::collections::HashMap;
#[derive(Clone)]
pub struct Databases {
db_map: HashMap<String, String>,
}
impl Databases {
pub fn new() -> Self {
Self {
db_map: HashMap::new(),
}
}
fn add_database(&mut self, name: &str, id: &str) -> Option<String> {
if self.db_map.contains_key(name) {
None
} else {
self.db_map.insert(name.to_string(), id.to_string());
Some(id.to_string())
}
}
fn get_database(&self, name: &str) -> Option<String> {
self.db_map.get(name).cloned()
}
fn show(&self) -> Vec<String> {
let mut names: Vec<String> = self.db_map.clone().into_keys().collect();
names.sort();
names
}
}
#[cfg(test)]
mod functions {
use super::*;
#[test]
fn add_entry() {
let name = "fred";
let id = "123456";
let mut dbs = Databases::new();
let output = dbs.add_database(name, id);
assert_eq!(output, Some(id.to_string()));
let output = dbs.get_database(name);
assert_eq!(output, Some(id.to_string()));
}
#[test]
fn entry_cannot_be_over_written() {
let name = "barney";
let id = "abcde";
let mut dbs = Databases::new();
dbs.add_database(name, id);
let output = dbs.add_database(name, "09876");
assert_eq!(output, None);
let output = dbs.get_database(name);
assert_eq!(output, Some(id.to_string()));
}
#[test]
fn get_bad_database() {
let dbs = Databases::new();
let output = dbs.get_database("missing");
assert_eq!(output, None);
}
#[test]
fn list_databases() {
let mut dbs = Databases::new();
dbs.add_database("zebra", "a");
dbs.add_database("alpha", "a");
dbs.add_database("charlie", "a");
dbs.add_database("wilma", "a");
dbs.add_database("frank", "a");
let expected = ["alpha", "charlie", "frank", "wilma", "zebra"];
let output = dbs.show();
assert_eq!(output, expected);
}
}