comparison tests/comm.rs @ 1:ef8bf41097ac

Added integration tests
author Martin Habovstiak <martin.habovstiak@gmail.com>
date Fri, 27 Nov 2020 10:07:35 +0100
parents
children 372afb9a700f
comparison
equal deleted inserted replaced
0:a65053246c29 1:ef8bf41097ac
1 use std::process::Child;
2 use std::ffi::OsStr;
3 use std::io::{self, Read, Write};
4
5 pub trait Test {
6 const SOCKET_ADDR: &'static str;
7
8 fn spawn_slave(program_name: &OsStr) -> io::Result<Child>;
9 }
10
11 const REQUEST: &[u8] = b"orange coin";
12 const RESPONSE: &[u8] = b"good";
13
14 fn main_master(slave: io::Result<Child>) {
15 let mut slave = slave.expect("failed to run systemd-socket-activate");
16
17 // give slave some time to bind the socket just to be sure
18 std::thread::sleep(std::time::Duration::from_secs(1));
19
20 let mut client_socket = std::net::TcpStream::connect("127.0.0.1:4242").expect("Failed to connect to 127.0.0.1:4242");
21 client_socket.write_all(REQUEST).expect("failed to send data");
22 let mut buf = [0u8; RESPONSE.len()];
23 client_socket.read_exact(&mut buf).expect("failed to read response");
24 assert_eq!(buf, RESPONSE);
25
26 let status = slave.wait().expect("faild to wait for slave");
27 if !status.success() {
28 panic!("slave did not exit with succcess, status: {}", status);
29 }
30 }
31
32 fn main_slave(addr: &str) {
33 use systemd_socket::SocketAddr;
34
35 let socket = addr
36 .parse::<SocketAddr>()
37 .expect("failed to parse socket")
38 .bind()
39 .expect("failed to bind");
40
41 let (mut client_socket, _) = socket.accept().expect("failed to accept");
42 let mut buf = [0u8; REQUEST.len()];
43 client_socket.read_exact(&mut buf).expect("failed to read response");
44 assert_eq!(buf, REQUEST);
45 client_socket.write_all(RESPONSE).expect("failed to send data");
46 }
47
48 pub fn main<T: Test>() {
49 let mut args = std::env::args_os();
50 let program_name = args.next().expect("missing program name");
51
52 match std::env::var_os("SYSTEMD_SOCKET_INTEGRATION_TEST") {
53 None => main_master(T::spawn_slave(&program_name)),
54 Some(arg) if arg == "slave" => main_slave(T::SOCKET_ADDR),
55 Some(arg) => panic!("Unknown argument '{:?}'", arg),
56 }
57 }