|
1 use protocol::messages::{ |
|
2 HWProtocolMessage::{self, Rnd}, HWServerMessage::ChatMsg, |
|
3 }; |
|
4 use rand::{self, Rng}; |
|
5 use server::{actions::Action, server::HWServer}; |
|
6 |
|
7 pub fn rnd_reply(options: Vec<String>) -> Vec<Action> { |
|
8 let options = if options.is_empty() { |
|
9 vec!["heads".to_owned(), "tails".to_owned()] |
|
10 } else { |
|
11 options |
|
12 }; |
|
13 let reply = rand::thread_rng().choose(&options).unwrap(); |
|
14 let msg = ChatMsg { |
|
15 nick: "[random]".to_owned(), |
|
16 msg: reply.clone(), |
|
17 }; |
|
18 let msg = msg.send_all().action(); |
|
19 vec![msg] |
|
20 } |
|
21 |
|
22 #[cfg(test)] |
|
23 mod tests { |
|
24 use super::*; |
|
25 use protocol::messages::HWServerMessage::ChatMsg; |
|
26 use server::actions::{ |
|
27 Action::{self, Send}, PendingMessage, |
|
28 }; |
|
29 |
|
30 fn reply2string(mut r: Vec<Action>) -> String { |
|
31 assert_eq!(r.len(), 1); |
|
32 match r.remove(0) { |
|
33 Send(PendingMessage { |
|
34 message: ChatMsg { msg: p, .. }, |
|
35 .. |
|
36 }) => String::from(p), |
|
37 _ => panic!("reply should be a string"), |
|
38 } |
|
39 } |
|
40 |
|
41 fn run_handle_test(opts: Vec<String>) { |
|
42 let opts2 = opts.clone(); |
|
43 for opt in opts { |
|
44 while reply2string(rnd_reply(opts2.clone())) != opt {} |
|
45 } |
|
46 } |
|
47 |
|
48 #[test] |
|
49 fn test_handle_rnd_empty() { |
|
50 run_handle_test(vec![]) |
|
51 } |
|
52 |
|
53 #[test] |
|
54 fn test_handle_rnd_nonempty() { |
|
55 run_handle_test(vec!["A".to_owned(), "B".to_owned(), "C".to_owned()]) |
|
56 } |
|
57 } |