v / vlib / sync / channel_select_test.v
91 lines · 83 sloc · 1.87 KB · 99be39cbd15d4bbb5ab14d2f870199908c00bc8d
Raw
1module sync
2
3// vtest retry: 3
4
5// ATTENTION! Do not use this file as an example!
6// For that, please look at `channel_select_2_test.v` or `channel_select_3_test.v`
7// This test case uses the implementation in `sync/channels.v` directly
8// in order to test it independently from the support in the core language
9import os
10import time
11
12fn test_should_run_flaky_test() {
13 if os.getenv('VTEST_RUN_FLAKY') != '1' {
14 eprintln('> skipping running flaky test, set VTEST_RUN_FLAKY to 1, to run it')
15 exit(0)
16 }
17 assert true
18}
19
20fn do_rec_i64(mut ch Channel) {
21 mut sum := i64(0)
22 for _ in 0 .. 300 {
23 mut a := i64(0)
24 ch.pop(&a)
25 sum += a
26 }
27 assert sum == 300 * (300 - 1) / 2
28}
29
30fn do_send_int(mut ch Channel) {
31 for i in 0 .. 300 {
32 ch.push(&i)
33 }
34}
35
36fn do_send_u8(mut ch Channel) {
37 for i in 0 .. 300 {
38 ii := u8(i)
39 ch.push(&ii)
40 }
41}
42
43fn do_send_i64(mut ch Channel) {
44 for i in 0 .. 300 {
45 ii := i64(i)
46 ch.push(&ii)
47 }
48}
49
50fn test_select() {
51 mut chi := new_channel[int](0)
52 mut chl := new_channel[i64](1)
53 mut chb := new_channel[u8](10)
54 mut recch := new_channel[i64](0)
55 spawn do_rec_i64(mut recch)
56 spawn do_send_int(mut chi)
57 spawn do_send_u8(mut chb)
58 spawn do_send_i64(mut chl)
59 mut channels := [chi, recch, chl, chb]
60 directions := [Direction.pop, .push, .pop, .pop]
61 mut sum := i64(0)
62 mut rl := i64(0)
63 mut ri := int(0)
64 mut rb := u8(0)
65 mut sl := i64(0)
66 mut objs := [voidptr(&ri), &sl, &rl, &rb]
67 for _ in 0 .. 1200 {
68 idx := channel_select(mut channels, directions, mut objs, time.infinite)
69 match idx {
70 0 {
71 sum += ri
72 }
73 1 {
74 sl++
75 }
76 2 {
77 sum += rl
78 }
79 3 {
80 sum += rb
81 }
82 else {
83 println('got ${idx} (timeout)')
84 }
85 }
86 }
87 // Use Gauß' formula for the first 2 contributions
88 // the 3rd contribution is `byte` and must be seen modulo 256
89 expected_sum := 2 * (300 * (300 - 1) / 2) + 256 * (256 - 1) / 2 + 44 * (44 - 1) / 2
90 assert sum == expected_sum
91}
92