v2 / vlib / v / tests / builtin_arrays / array_methods_test.v
89 lines · 73 sloc · 1.66 KB · 8e35f4d9848f7ad35d857a187dddbfd2eca5e19d
Raw
1struct Counter {
2mut:
3 val int
4}
5
6// if this is called more than once, the test'll fail
7fn (mut c Counter) new_arr(msg string) []int {
8 if c.val > 0 {
9 panic(msg)
10 }
11 c.val++
12 return [1, 3, 2]
13}
14
15fn test_array_eval_count() {
16 // `new_arr()` should only be evaluated once, not on every iteration
17 mut a1 := Counter{}
18 assert a1.new_arr('map() failed').map(it * 2) == [2, 6, 4]
19
20 mut a2 := Counter{}
21 assert a2.new_arr('filter() failed').filter(it < 3) == [1, 2]
22
23 mut a3 := Counter{}
24 assert a3.new_arr('any() failed').any(it == 2) == true
25 a3 = Counter{}
26 assert a3.new_arr('any() failed').any(it < 0) == false
27
28 mut a4 := Counter{}
29 assert a4.new_arr('all() failed').all(it > 0) == true
30 a4 = Counter{}
31 assert a4.new_arr('all() failed').all(it == 2) == false
32}
33
34fn opt_bool_fn() ?bool {
35 return true
36}
37
38fn test_any_called_with_opt_bool_fn() ? {
39 _ := [1, 2, 3].any(opt_bool_fn()?)
40 assert true
41}
42
43interface Args {}
44
45const some_strings = ['one', 'two', 'three']
46
47// For test `gen array contains method`
48fn test_array_contains_method_with_interface() {
49 arg := Args('one')
50 match arg {
51 string {
52 if arg in some_strings {
53 assert true
54 return
55 }
56 }
57 else {}
58 }
59
60 assert false
61}
62
63// For test `gen string_eq method`
64fn test_string_eq_method_with_interface() {
65 arg := Args('three')
66 match arg {
67 string {
68 if arg in ['one', 'two', 'three'] {
69 assert true
70 return
71 }
72 }
73 else {}
74 }
75
76 assert false
77}
78
79// test deref when alias as receiver of methods
80type Array = []int
81
82pub fn (mut arr Array) alias_as_receiver_deref() []int {
83 return arr.sorted(b < a)
84}
85
86fn test_alias_as_receiver_deref() {
87 mut arr := Array([1, 2, 3])
88 assert arr.alias_as_receiver_deref() == [3, 2, 1]
89}
90