switchgear_testing/credentials/
db.rs1use crate::credentials::download_credentials;
2use crate::services::IntegrationTestServices;
3use anyhow::{anyhow, Context};
4use std::fs;
5use std::path::PathBuf;
6use tempfile::TempDir;
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub struct TestDatabase {
10 pub address: String,
11 pub ca_cert_path: PathBuf,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq, Hash)]
15pub struct TestDatabases {
16 pub postgres: TestDatabase,
17 pub mysql: TestDatabase,
18}
19
20pub struct DbCredentials {
21 credentials_dir: TempDir,
22 postgres: String,
23 mysql: String,
24}
25
26impl DbCredentials {
27 pub fn create() -> anyhow::Result<Self> {
28 let services = IntegrationTestServices::new();
29
30 let credentials_dir = TempDir::new()?;
31 download_credentials(credentials_dir.path(), services.credentials())?;
32 Ok(Self {
33 credentials_dir,
34 postgres: services.postgres().to_string(),
35 mysql: services.mysql().to_string(),
36 })
37 }
38
39 pub fn get_databases(&self) -> anyhow::Result<TestDatabases> {
40 let credentials = self.credentials_dir.path().join("credentials");
41 let base_path = credentials.as_path();
42
43 let entries = fs::read_dir(base_path)
44 .with_context(|| format!("reading directory {}", base_path.display()))?;
45
46 let mut postgres = None;
47 let mut mysql = None;
48 for entry in entries {
49 let entry = entry
50 .with_context(|| format!("reading directory entry in {}", base_path.display(),))?;
51
52 let path = entry.path();
53
54 if !path.is_dir() {
55 continue;
56 }
57
58 let dir_name = match path.file_name() {
59 Some(name) => match name.to_str() {
60 Some(s) => s,
61 None => continue,
62 },
63 None => continue,
64 };
65
66 if dir_name == "postgres" {
67 postgres = Some(TestDatabase {
68 address: self.postgres.to_string(),
69 ca_cert_path: path.join("server.pem"),
70 });
71 }
72
73 if dir_name == "mysql" {
74 mysql = Some(TestDatabase {
75 address: self.mysql.to_string(),
76 ca_cert_path: path.join("server.pem"),
77 });
78 }
79
80 if postgres.is_some() && mysql.is_some() {
81 break;
82 }
83 }
84
85 Ok(TestDatabases {
86 postgres: postgres.ok_or_else(|| {
87 anyhow!(
88 "postgres credentials not found in {}",
89 self.credentials_dir.path().to_string_lossy()
90 )
91 })?,
92 mysql: mysql.ok_or_else(|| {
93 anyhow!(
94 "mysql credentials not found in {}",
95 self.credentials_dir.path().to_string_lossy()
96 )
97 })?,
98 })
99 }
100}