1 #![cfg(unix)]
2 extern crate serialport;
3
4 use serialport::{SerialPort, TTYPort};
5 use std::io::{Read, Write};
6
7 // Test that cloning a port works as expected
8 #[test]
test_try_clone()9 fn test_try_clone() {
10 let (master, mut slave) = TTYPort::pair().expect("Unable to create ptty pair");
11
12 // Create the clone in an inner scope to test that dropping a clone doesn't close the original
13 // port
14 {
15 let mut clone = master.try_clone().expect("Failed to clone");
16 let bytes = [b'a', b'b', b'c', b'd', b'e', b'f'];
17 clone.write_all(&bytes).unwrap();
18 let mut buffer = [0; 6];
19 slave.read_exact(&mut buffer).unwrap();
20 assert_eq!(buffer, [b'a', b'b', b'c', b'd', b'e', b'f']);
21 }
22
23 // Second try to check that the serial device is not closed
24 {
25 let mut clone = master.try_clone().expect("Failed to clone");
26 let bytes = [b'g', b'h', b'i', b'j', b'k', b'l'];
27 clone.write_all(&bytes).unwrap();
28 let mut buffer = [0; 6];
29 slave.read_exact(&mut buffer).unwrap();
30 assert_eq!(buffer, [b'g', b'h', b'i', b'j', b'k', b'l']);
31 }
32 }
33
34 // Test moving a cloned port into a thread
35 #[test]
test_try_clone_move()36 fn test_try_clone_move() {
37 use std::thread;
38
39 let (master, mut slave) = TTYPort::pair().expect("Unable to create ptty pair");
40
41 let mut clone = master.try_clone().expect("Failed to clone the slave");
42 let loopback = thread::spawn(move || {
43 let bytes = [b'a', b'b', b'c', b'd', b'e', b'f'];
44 clone.write_all(&bytes).unwrap();
45 });
46
47 let mut buffer = [0; 6];
48 slave.read_exact(&mut buffer).unwrap();
49 assert_eq!(buffer, [b'a', b'b', b'c', b'd', b'e', b'f']);
50
51 // The thread should have already ended, but we'll make sure here anyways.
52 loopback.join().unwrap();
53 }
54