aboutsummaryrefslogtreecommitdiff
path: root/tests/expr.test
blob: 19db19eb3d874cce2163ffef23994b9b34168247 (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
#!/bin/bash

[ -f testing.sh ] && . testing.sh

testing "integer" "expr 5" "5\n" "" ""
testing "integer negative" "expr -5" "-5\n" "" ""
testing "string" "expr astring" "astring\n" "" ""
testing "addition" "expr 1 + 3" "4\n" "" ""
testing "5 + 6 * 3" "expr 5 + 6 \* 3" "23\n" "" ""
testing "( 5 + 6 ) * 3" "expr \( 5 + 6 \) \* 3" "33\n" "" ""
testing ">" "expr 3 \> 2" "1\n" "" ""
testing "* / same priority" "expr 4 \* 3 / 2"  "6\n" "" ""
testing "/ * same priority" "expr 3 / 2 \* 4" "4\n" "" ""
testing "& before |" "expr 0 \| 1 \& 0" "0\n" "" ""
testing "| after &" "expr 1 \| 0 \& 0" "1\n" "" ""
testing "| & same priority" "expr 0 \& 0 \| 1" "1\n" "" ""
testing "% * same priority" "expr 3 % 2 \* 4" "4\n" "" ""
testing "* % same priority" "expr 3 \* 2 % 4" "2\n" "" ""
testing "= > same priority" "expr 0 = 2 \> 3" "0\n" "" ""
testing "> = same priority" "expr 3 \> 2 = 1" "1\n" "" ""

testing "/ by zero" "expr 1 / 0; echo \$?" "2\n" "" ""
testing "% by zero" "expr 1 % 0; echo \$?" "2\n" "" ""

testing "regex position" "expr ab21xx : '[^0-9]*[0-9]*'" "4\n" "" ""
testing "regex extraction" "expr ab21xx : '[^0-9]*\([0-9]*\).*'" "21\n" "" ""
testing "regex no match" "expr ab21xx : x" "0\n" "" ""
testing "long str" "expr abcdefghijklmnopqrstuvwxyz : '\(.*\)' = a" "0\n" "" ""

# result of ':' regex match can subsequently be used for arithmetic
testing "string becomes integer" "expr ab21xx : '[^0-9]*\([0-9]*\)' + 3" \
	"24\n" "" ""

testing "integer comparison" "expr -3 \< -2" "1\n" "" ""
testing "string comparison" "expr -3 \< -2s" "0\n" "" ""
testing "integer expression comparison" "expr 2 - 5 \< -2" "1\n" "" ""
# result of arithmetic can subsequently be compared as a string
testing "string expr comparison" "expr 2 - 5 \< -2s" "0\n" "" ""

testing "parens around literal" "expr \( a \)" "a\n" "" ""

testing "exit code when true" "expr a; echo \$?" "a\n0\n" "" ""
testing "exit code when false" "expr 0; echo \$?" "0\n1\n" "" ""
testing "exit code with syntax error" "expr \(; echo \$?" "2\n" "" ""
testing "exit code when evaluating to 0" "expr -1 + 1; echo \$?" "0\n1\n" "" ""

# BUG: segfaults because '3' is coerced to integer and regexc gets NULL
testing "regex segfault" "expr 3 : '\(.\)'" "3\n" "" ""

# syntax errors
testing "no expression" "expr; echo \$?" "2\n" "" ""
testing "empty ()" "expr \( \); echo \$?" "2\n" "" ""
testing "missing )" "expr \( 1; echo \$?" "2\n" "" ""
testing "missing outer )" "expr \( 1 + \( 2 \* 3 \); echo \$?" "2\n" "" ""
testing "bad operator" "expr 1 @ 2; echo \$?" "2\n" "" ""
testing "adjacent literals" "expr 1 2; echo \$?" "2\n" "" ""
testing "non-integer argument" "expr 1 + a; echo \$?" "2\n" "" ""