-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssertium.sh
More file actions
169 lines (148 loc) · 2.86 KB
/
Assertium.sh
File metadata and controls
169 lines (148 loc) · 2.86 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/bin/bash
assert()
{
assert_base "$@"
if [ $? == 0 ]
then
tput setaf 2; echo Pass: $@ ; tput sgr0
return 0
else
tput setaf 1; echo FAIL: $@ ; tput sgr0
return 1
fi
}
assert_base()
{
case "$2" in
is)
if [ "$3" == "not" ]
then
assert_is_not "$@"
else
assert_is "$@"
fi
;;
all)
assert_all "$@"
;;
any)
assert_any "$@"
;;
none)
assert_none "$@"
;;
piecewise)
assert_piecewise "$@"
;;
returns)
outputTrap=$(eval $1) # using a trap here to catch the output of the original assert
test "$?" == $3
;;
*)
test "$@"
;;
esac
return "$?"
}
###
### Type assertions
###
assert_is()
{
# for the regex we can not use the test command (which is just another way to write [ ... ]).
# We need to use double brackets. Even though they are used "standalone" here (you may be used to them embedded in if statements), they set their exit code ($?) as expected
case "$3" in
Number|number|numeric|Integer|integer)
[[ $1 =~ ^[0-9]*$ ]]
;;
String|string|Text|text)
[[ $1 =~ ^[0-9A-Za-z\ .,!]*$ ]]
;;
alphabetic)
[[ $1 =~ ^[A-Za-z]*$ ]]
;;
alphanumeric)
[[ $1 =~ ^[0-9a-zA-Z]*$ ]]
;;
*)
echo "Unknown assertion $3"
return 1
;;
esac
}
assert_is_not()
{
assert_is "$1" $2 $4
if [ $? == 0 ]
then
return 1
else
return 0
fi
}
###
### Array assertions
###
assert_all()
{
local mismatch=0
for i in "${!1}"
do
assert_base "$i" $3 "$4"
if [ $? != 0 ]
then
mismatch=1
break
fi
done
return $mismatch
}
assert_any()
{
local noElementFound=1
for i in "${!1}"
do
assert_base "$i" $3 "$4"
if [ $? == 0 ]
then
noElementFound=0
break
fi
done
return $noElementFound
}
assert_none()
{
local match=0
for i in "${!1}"
do
assert_base "$i" $3 $4
if [ $? == 0 ]
then
match=1
break
fi
done
return $match
}
assert_piecewise()
{
local mismatch=0
local array1=( ${!1} )
local array2=( ${!4} )
if [ ${#array1[@]} != ${#array2[@]} ]
then
return 1
else
for i in "${!array1[@]}"
do
assert_base "${array1[i]}" $3 "${array2[i]}"
if [ $? == 1 ]
then
mismatch=1
break
fi
done
return $mismatch
fi
}