forked from discord/rust-etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.rs
93 lines (77 loc) · 2.7 KB
/
test.rs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use std::fs::File;
use std::io::Read;
use std::ops::Deref;
use etcd::{kv, Client};
use hyper::client::connect::Connect;
use hyper::client::{Client as Hyper, HttpConnector};
use hyper_tls::HttpsConnector;
use native_tls::{Certificate, Identity, TlsConnector};
/// Wrapper around Client that automatically cleans up etcd after each test.
pub struct TestClient<C>
where
C: Clone + Connect + Sync + Send + 'static,
{
c: Client<C>,
run_destructor: bool,
}
impl TestClient<HttpConnector> {
/// Creates a new client for a test.
#[allow(dead_code)]
pub async fn new() -> TestClient<HttpConnector> {
let tc = TestClient {
c: Client::new(&["http://etcd:2379"], None).unwrap(),
run_destructor: true,
};
kv::delete(&tc.c, "/test", true).await.ok();
tc
}
/// Creates a new client for a test that will not clean up the key space afterwards.
#[allow(dead_code)]
pub fn no_destructor() -> TestClient<HttpConnector> {
TestClient {
c: Client::new(&["http://etcd:2379"], None).unwrap(),
run_destructor: false,
}
}
/// Creates a new HTTPS client for a test.
#[allow(dead_code)]
pub fn https(use_client_cert: bool) -> TestClient<HttpsConnector<HttpConnector>> {
let mut ca_cert_file = File::open("/source/tests/ssl/ca.der").unwrap();
let mut ca_cert_buffer = Vec::new();
ca_cert_file.read_to_end(&mut ca_cert_buffer).unwrap();
let mut builder = TlsConnector::builder();
builder.add_root_certificate(Certificate::from_der(&ca_cert_buffer).unwrap());
if use_client_cert {
let mut pkcs12_file = File::open("/source/tests/ssl/client.p12").unwrap();
let mut pkcs12_buffer = Vec::new();
pkcs12_file.read_to_end(&mut pkcs12_buffer).unwrap();
builder.identity(Identity::from_pkcs12(&pkcs12_buffer, "secret").unwrap());
}
let tls_connector = builder.build().unwrap();
let mut http_connector = HttpConnector::new();
http_connector.enforce_http(false);
let https_connector = HttpsConnector::from((http_connector, tls_connector.into()));
let hyper = Hyper::builder().build(https_connector);
TestClient {
c: Client::custom(hyper, &["https://etcdsecure:2379"], None).unwrap(),
run_destructor: true,
}
}
}
impl<C> Drop for TestClient<C>
where
C: Clone + Connect + Sync + Send + 'static,
{
fn drop(&mut self) {
if self.run_destructor {}
}
}
impl<C> Deref for TestClient<C>
where
C: Clone + Connect + Sync + Send + 'static,
{
type Target = Client<C>;
fn deref(&self) -> &Self::Target {
&self.c
}
}