• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![cfg(feature = "full")]
2 
3 use std::sync::Arc;
4 use tokio::sync::Semaphore;
5 
6 #[test]
no_permits()7 fn no_permits() {
8     // this should not panic
9     Semaphore::new(0);
10 }
11 
12 #[test]
try_acquire()13 fn try_acquire() {
14     let sem = Semaphore::new(1);
15     {
16         let p1 = sem.try_acquire();
17         assert!(p1.is_ok());
18         let p2 = sem.try_acquire();
19         assert!(p2.is_err());
20     }
21     let p3 = sem.try_acquire();
22     assert!(p3.is_ok());
23 }
24 
25 #[tokio::test]
acquire()26 async fn acquire() {
27     let sem = Arc::new(Semaphore::new(1));
28     let p1 = sem.try_acquire().unwrap();
29     let sem_clone = sem.clone();
30     let j = tokio::spawn(async move {
31         let _p2 = sem_clone.acquire().await;
32     });
33     drop(p1);
34     j.await.unwrap();
35 }
36 
37 #[tokio::test]
add_permits()38 async fn add_permits() {
39     let sem = Arc::new(Semaphore::new(0));
40     let sem_clone = sem.clone();
41     let j = tokio::spawn(async move {
42         let _p2 = sem_clone.acquire().await;
43     });
44     sem.add_permits(1);
45     j.await.unwrap();
46 }
47 
48 #[test]
forget()49 fn forget() {
50     let sem = Arc::new(Semaphore::new(1));
51     {
52         let p = sem.try_acquire().unwrap();
53         assert_eq!(sem.available_permits(), 0);
54         p.forget();
55         assert_eq!(sem.available_permits(), 0);
56     }
57     assert_eq!(sem.available_permits(), 0);
58     assert!(sem.try_acquire().is_err());
59 }
60 
61 #[tokio::test]
stresstest()62 async fn stresstest() {
63     let sem = Arc::new(Semaphore::new(5));
64     let mut join_handles = Vec::new();
65     for _ in 0..1000 {
66         let sem_clone = sem.clone();
67         join_handles.push(tokio::spawn(async move {
68             let _p = sem_clone.acquire().await;
69         }));
70     }
71     for j in join_handles {
72         j.await.unwrap();
73     }
74     // there should be exactly 5 semaphores available now
75     let _p1 = sem.try_acquire().unwrap();
76     let _p2 = sem.try_acquire().unwrap();
77     let _p3 = sem.try_acquire().unwrap();
78     let _p4 = sem.try_acquire().unwrap();
79     let _p5 = sem.try_acquire().unwrap();
80     assert!(sem.try_acquire().is_err());
81 }
82 
83 #[test]
add_max_amount_permits()84 fn add_max_amount_permits() {
85     let s = tokio::sync::Semaphore::new(0);
86     s.add_permits(usize::MAX >> 3);
87     assert_eq!(s.available_permits(), usize::MAX >> 3);
88 }
89 
90 #[test]
91 #[should_panic]
add_more_than_max_amount_permits()92 fn add_more_than_max_amount_permits() {
93     let s = tokio::sync::Semaphore::new(1);
94     s.add_permits(usize::MAX >> 3);
95 }
96