1 use crate::{ |
|
2 server::{actions::Action, core::HWServer}, |
|
3 protocol::messages::{ |
|
4 HWProtocolMessage::{self, Rnd}, HWServerMessage::{self, ChatMsg}, |
|
5 } |
|
6 }; |
|
7 use rand::{self, Rng, thread_rng}; |
|
8 |
|
9 pub fn rnd_reply(options: &[String]) -> HWServerMessage { |
|
10 let mut rng = thread_rng(); |
|
11 let reply = if options.is_empty() { |
|
12 (*rng.choose(&["heads", "tails"]).unwrap()).to_owned() |
|
13 } else { |
|
14 rng.choose(&options).unwrap().clone() |
|
15 }; |
|
16 |
|
17 ChatMsg { |
|
18 nick: "[random]".to_owned(), |
|
19 msg: reply.clone(), |
|
20 } |
|
21 } |
|
22 |
|
23 #[cfg(test)] |
|
24 mod tests { |
|
25 use super::*; |
|
26 use crate::protocol::messages::HWServerMessage::ChatMsg; |
|
27 use crate::server::actions::{ |
|
28 Action::{self, Send}, PendingMessage, |
|
29 }; |
|
30 |
|
31 fn reply2string(r: HWServerMessage) -> String { |
|
32 match r { |
|
33 ChatMsg { msg: p, .. } => String::from(p), |
|
34 _ => panic!("expected a ChatMsg"), |
|
35 } |
|
36 } |
|
37 |
|
38 fn run_handle_test(opts: Vec<String>) { |
|
39 let opts2 = opts.clone(); |
|
40 for opt in opts { |
|
41 while reply2string(rnd_reply(&opts2)) != opt {} |
|
42 } |
|
43 } |
|
44 |
|
45 /// This test terminates almost surely. |
|
46 #[test] |
|
47 fn test_handle_rnd_empty() { |
|
48 run_handle_test(vec![]) |
|
49 } |
|
50 |
|
51 /// This test terminates almost surely. |
|
52 #[test] |
|
53 fn test_handle_rnd_nonempty() { |
|
54 run_handle_test(vec!["A".to_owned(), "B".to_owned(), "C".to_owned()]) |
|
55 } |
|
56 |
|
57 /// This test terminates almost surely (strong law of large numbers) |
|
58 #[test] |
|
59 fn test_distribution() { |
|
60 let eps = 0.000001; |
|
61 let lim = 0.5; |
|
62 let opts = vec![0.to_string(), 1.to_string()]; |
|
63 let mut ones = 0; |
|
64 let mut tries = 0; |
|
65 |
|
66 while tries < 1000 || ((ones as f64 / tries as f64) - lim).abs() >= eps { |
|
67 tries += 1; |
|
68 if reply2string(rnd_reply(&opts)) == 1.to_string() { |
|
69 ones += 1; |
|
70 } |
|
71 } |
|
72 } |
|
73 } |
|