v2 / vlib / v / tests / conditions / ifs / if_guard_test.v
161 lines · 146 sloc · 2.12 KB · 36710adccc8cf04c82a8e52ed8acabea826622d7
Raw
1fn f(n int) !f64 {
2 if n < 0 {
3 return error('negative')
4 }
5 return 1.5 * f64(n)
6}
7
8fn test_fn_return() {
9 mut res := []f64{cap: 2}
10 for m in [-3, 5] {
11 if x := f(m) {
12 res << x
13 } else {
14 res << 31.0
15 }
16 }
17 assert res == [31.0, 7.5]
18}
19
20fn test_fn_return_empty() {
21 if _ := f(-3) {
22 assert false
23 } else {
24 assert true
25 }
26}
27
28fn test_map_get() {
29 mut m := {
30 'xy': 5
31 'zu': 7
32 }
33 mut res := []int{cap: 2}
34 for k in ['jk', 'zu'] {
35 if x := m[k] {
36 res << x
37 } else {
38 res << -17
39 }
40 }
41 assert res == [-17, 7]
42}
43
44fn test_map_get_empty() {
45 mut m := {
46 'xy': 5
47 'zu': 7
48 }
49 if _ := m['jk'] {
50 assert false
51 } else {
52 assert true
53 }
54}
55
56fn test_array_get() {
57 mut a := [12.5, 6.5, -17.25]
58 mut res := []f64{cap: 2}
59 for i in [1, 4] {
60 if x := a[i] {
61 res << x
62 } else {
63 res << -23.0
64 }
65 }
66 assert res == [6.5, -23.0]
67}
68
69fn test_array_get_empty() {
70 mut a := [12.5, 6.5, -17.25]
71 if _ := a[7] {
72 assert false
73 } else {
74 assert true
75 }
76}
77
78fn maybe_text(ok bool) ?string {
79 if ok {
80 return 'hello'
81 }
82 return none
83}
84
85fn test_array_get_method() {
86 mut a := [12.5, 6.5, -17.25]
87 mut res := []f64{cap: 2}
88 for i in [1, 4] {
89 if x := a.get(i) {
90 res << x
91 } else {
92 res << -23.0
93 }
94 }
95 assert res == [6.5, -23.0]
96}
97
98fn test_array_get_method_with_option_elements() {
99 arr := [maybe_text(true)]
100 x := arr.get(0) or { 'fallback' }
101 y := arr.get(99) or { 'fallback' }
102 assert x == 'hello'
103 assert y == 'fallback'
104}
105
106fn test_chan_pop() {
107 mut res := []f64{cap: 3}
108 ch := chan f64{cap: 10}
109 ch <- 6.75
110 ch <- -3.25
111 ch.close()
112 for _ in 0 .. 3 {
113 if x := <-ch {
114 res << x
115 } else {
116 res << -37.5
117 }
118 }
119 assert res == [6.75, -3.25, -37.5]
120}
121
122fn test_chan_pop_empty() {
123 ch := chan f64{cap: 10}
124 ch <- 6.75
125 ch <- -3.25
126 ch.close()
127 for i in 0 .. 3 {
128 if _ := <-ch {
129 assert i < 2
130 } else {
131 assert i == 2
132 }
133 }
134}
135
136struct Thing {
137mut:
138 value int
139}
140
141fn maybe_a_thing() ?Thing {
142 return Thing{
143 value: 1
144 }
145}
146
147fn test_if_guard() {
148 if val := maybe_a_thing() {
149 assert val.value == 1
150 } else {
151 assert false
152 }
153
154 if mut val := maybe_a_thing() {
155 assert val.value == 1
156 val.value = 2
157 assert val.value == 2
158 } else {
159 assert false
160 }
161}
162