summaryrefslogtreecommitdiffstats
path: root/third_party/rust/tokio-0.1.22/tests/timer.rs
blob: 54c3b9d31df7debdfca5fceecbba52cbe59a0beb (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
extern crate env_logger;
extern crate futures;
extern crate tokio;
extern crate tokio_io;

use tokio::prelude::*;
use tokio::timer::*;

use std::sync::mpsc;
use std::time::{Duration, Instant};

#[test]
fn timer_with_runtime() {
    let _ = env_logger::try_init();

    let when = Instant::now() + Duration::from_millis(100);
    let (tx, rx) = mpsc::channel();

    tokio::run({
        Delay::new(when)
            .map_err(|e| panic!("unexpected error; err={:?}", e))
            .and_then(move |_| {
                assert!(Instant::now() >= when);
                tx.send(()).unwrap();
                Ok(())
            })
    });

    rx.recv().unwrap();
}

#[test]
fn starving() {
    use futures::{task, Async, Poll};

    let _ = env_logger::try_init();

    struct Starve(Delay, u64);

    impl Future for Starve {
        type Item = u64;
        type Error = ();

        fn poll(&mut self) -> Poll<Self::Item, ()> {
            if self.0.poll().unwrap().is_ready() {
                return Ok(self.1.into());
            }

            self.1 += 1;

            task::current().notify();

            Ok(Async::NotReady)
        }
    }

    let when = Instant::now() + Duration::from_millis(20);
    let starve = Starve(Delay::new(when), 0);

    let (tx, rx) = mpsc::channel();

    tokio::run({
        starve.and_then(move |_ticks| {
            assert!(Instant::now() >= when);
            tx.send(()).unwrap();
            Ok(())
        })
    });

    rx.recv().unwrap();
}

#[test]
fn deadline() {
    use futures::future;

    let _ = env_logger::try_init();

    let when = Instant::now() + Duration::from_millis(20);
    let (tx, rx) = mpsc::channel();

    #[allow(deprecated)]
    tokio::run({
        future::empty::<(), ()>().deadline(when).then(move |res| {
            assert!(res.is_err());
            tx.send(()).unwrap();
            Ok(())
        })
    });

    rx.recv().unwrap();
}

#[test]
fn timeout() {
    use futures::future;

    let _ = env_logger::try_init();

    let (tx, rx) = mpsc::channel();

    tokio::run({
        future::empty::<(), ()>()
            .timeout(Duration::from_millis(20))
            .then(move |res| {
                assert!(res.is_err());
                tx.send(()).unwrap();
                Ok(())
            })
    });

    rx.recv().unwrap();
}