A while ago I was looking for a simple way to e2e test my REST API, written in Flask. Since I was only interested in make HTTP requests and parse the JSON response I didn't see any point of using any assertion library or test framework. To improve my bash skills i decided to write it with cURL and bash functions.
Readable output
Testing is to give us control and possibility to with ease find troubles. Therefore I made some colors and an icon to make it easy to parse the results for a human eye.
Green='\033[0;32m'
Red='\033[0;31m'
Color_Off='\033[0m'
Check_Mark='\xE2\x9C\x94'
Assertions
To keep the tests simple I tested everything with "assert equals", which was ran by this function.
assert_equals () {
if [ "$1" = "$2" ]; then
echo -e "$Green $Check_Mark Success $Color_Off"
else
echo -e "$Red Failed $Color_Off"
echo -e "$Red Expected $1 to equal $2 $Color_Off"
Errors=$((Errors + 1))
fi
}
Parsing the JSON
To parse the JSON I used jq, and created a helper function. The first argument is the JSON string and the second is the path, for example ".[0].title".
get_json_value () {
echo $1 | jq -r $2
}
The tests
So finally came the tests that I run. They looked like this:
echo "### START /api/v2/shelters"
shelters_url="localhost:5000/api/v2/shelters/"
echo "When retrieving a shelter accurate properties should be given"
response=$(curl -s "${shelters_url}142784-8")
assert_equals "$(get_json_value "$response" ".shelterId")" "142784-8"
assert_equals "$(get_json_value "$response" ".address")" "Sockerbruksgatan 3"
assert_equals "$(get_json_value "$response" ".slots")" "80"
Am I happier?
Yes. I guess it'd been easier to write it with Python, but this was more fun. I also think that we developers may tend to use bloated frameworks that moves us away from the core and the control. This was a good lesson for me to think outside of my small box, which I think is necessary to keep learning.
Top comments (0)