summaryrefslogtreecommitdiff
path: root/rust/schist_models/tests/common/test_context.rs
blob: fb4112dbfa283f2d05d6775dc864a952a40d736a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use std::sync::atomic::{AtomicU64, Ordering};

use diesel::{Connection, SqliteConnection};
use diesel_migrations::MigrationHarness;
use schist_queries::clear::clear;
use schist_models::migrations::MIGRATIONS;

pub struct TestContext {
    pub db_url: String,
}

static ID_COUNTER: AtomicU64 = AtomicU64::new(0);

impl TestContext {
    pub fn new() -> Self {
        let db_url = Self::next_id() + ".sqlite";

        let connection = &mut SqliteConnection
            ::establish(&db_url)
            .expect("failed to connect to database");

        connection
            .run_pending_migrations(MIGRATIONS)
            .expect("failed to run migrations");

        clear(connection)
            .expect("failed to clear database");

        Self {
            db_url,
        }
    }

    fn next_id() -> String {
        ID_COUNTER.fetch_add(1, Ordering::Relaxed).to_string()
    }
}

impl Drop for TestContext {
    fn drop(&mut self) {
        std::fs::remove_file(&self.db_url)
            .expect(format!("failed to delete database {}", self.db_url).as_str());
    }
}