Recrear la DDBB con cada ejecución de los tests
[isfdt166-ansi-edi2-2024-server.git] / openapi / test-api.sh
blob7ec34f06611c5834bb5505f70f38b6deb56c3c9d
1 #!/bin/bash
3 # @see https://stackoverflow.com/a/4774063
4 SCRIPTPATH="$( cd -- "$(dirname "$0")" > /dev/null 2>&1; pwd -P )"
6 # Move to script's upper directory
7 cd "${SCRIPTPATH}/.."
9 # --------------------------------------
10 # Check `curl` availability
11 # --------------------------------------
13 which curl &> /dev/null
15 if (($? != 0)); then
16 echo "> curl not found"
17 exit 1
20 # --------------------------------------
21 # Check `php` availability
22 # --------------------------------------
24 which php &> /dev/null
26 if (($? != 0)); then
27 echo "> php not found"
28 exit 1
31 # --------------------------------------
32 # Get values from bash command-line parameters
33 # --------------------------------------
35 HOST="${1:-localhost}"
36 PORT="${2:-8000}"
38 # Colors:
39 # @see https://stackoverflow.com/a/5947802
41 # NO COLOR 0
42 # Black 0;30 Dark Gray 1;30
43 # Red 0;31 Light Red 1;31
44 # Green 0;32 Light Green 1;32
45 # Brown/Orange 0;33 Yellow 1;33
46 # Blue 0;34 Light Blue 1;34
47 # Purple 0;35 Light Purple 1;35
48 # Cyan 0;36 Light Cyan 1;36
49 # Light Gray 0;37 White 1;37
51 # .---------- constant part!
52 # vvvv vvvv-- the code from above
53 # RED='\033[0;31m'
54 # NC='\033[0m' # No Color
55 # printf "I ${RED}love${NC} Stack Overflow\n"
57 # --------------------------------------
58 # Display message
60 # Flags:
61 # - 'f': Failure message
62 # - 's': Success message
63 # - (empty): Normal message
65 # @param string $1 Message
66 # @param string $2 Flag
67 # --------------------------------------
68 function msg {
69 local rd='\033[0;31m'
70 local gr='\033[0;32m'
71 local nc='\033[0m'
73 local message="${1}"
74 local flag="${2}"
76 if [[ 's' == "${flag}" ]]; then
77 echo -e "${gr}[✅ SUCCESS] ${message}${nc}"
78 elif [[ 'f' == "${flag}" ]]; then
79 echo -e "${rd}[❌ FAILURE] ${message}${nc}"
80 if [[ "true" == "${STOP_ON_FAILURE}" ]]; then
81 exit 1
83 else
84 echo ">>>>>>>>>>>> ${message}"
88 # --------------------------------------
89 # Call cURL command
91 # Use following global variables to return/export values:
93 # - CURL_EXIT_CODE
94 # - CURL_RESPONSE_HEADER
95 # - CURL_RESPONSE_DATA
97 # @param string $1 Path
98 # @param string $2 Method
99 # @param string $3 Data
100 # --------------------------------------
101 function callRestApi {
102 CURL_EXIT_CODE=1
103 CURL_RESPONSE_HEADER=''
104 CURL_RESPONSE_DATA=''
106 local path="${1}"
107 local method="${2:-GET}"
108 local data="${3}"
110 if [[ ! -z "${data}" ]]; then
111 data="--data ${data}"
114 curl "${HOST}:${PORT}${path}" \
115 --request "${method}" \
116 --header "Content-Type: application/json" \
117 --header "Accept: application/json" \
118 --dump-header curl_response_header.txt \
119 --output curl_response_data.txt \
120 $data &> /dev/null
122 CURL_EXIT_CODE=$?
124 if [ -f curl_response_header.txt ]; then
125 CURL_RESPONSE_HEADER=$(cat curl_response_header.txt)
126 rm curl_response_header.txt
129 if [ -f curl_response_data.txt ]; then
130 CURL_RESPONSE_DATA=$(cat curl_response_data.txt)
131 rm curl_response_data.txt
135 # --------------------------------------
136 # Get the value from a response header
138 # @param string $1 Headers list
139 # @param string $2 Header name
140 # --------------------------------------
141 function getValueFromHeader {
142 local list="${1}"
143 local key="${2}"
144 if [[ "code" == "${key}" ]]; then
145 echo $(echo "${list}" | grep '^HTTP/' | cut -d' ' -f2 | xargs)
146 else
147 echo $(echo "${list}" | grep "^${key}:" | cut -d':' -f2 | xargs)
151 # --------------------------------------
152 # Count items in JSON list
154 # @param string $1 JSON
155 # --------------------------------------
156 function countItemsInJsonList {
157 local json="${1}"
158 local php=$(cat << PHP
159 \$list = json_decode('${json}', true);
160 echo count(\$list);
163 echo $(php -r "${php}")
166 # --------------------------------------
167 # Find an item in a JSON list
169 # @param string $1 JSON
170 # @param string $2 KEY
171 # @param string $3 VALUE
172 # --------------------------------------
173 function searchByKeyValue {
174 local json="${1}"
175 local key="${2}"
176 local value="${3}"
177 local php=$(cat << PHP
178 \$list = json_decode('${json}', true);
179 \$value = null;
180 foreach (\$list as \$item) {
181 if ('${value}' == \$item['${key}']) {
182 \$value = json_encode(\$item);
183 break;
186 echo \$value;
189 echo $(php -r "${php}")
192 # --------------------------------------
193 # Get a value from a JSON string
195 # @param string $1 JSON
196 # @param string $2 KEY
197 # --------------------------------------
198 function getValueFromJson {
199 local json="${1}"
200 local key="${2}"
201 local php=$(cat << PHP
202 \$list = json_decode('${json}', true);
203 echo \$list['${key}'];
206 echo $(php -r "${php}")
209 # ====================================================================
211 # --------------------------------------
212 # Helper to interact with an element
214 # @param string $1 HTTP Verb
215 # @param string $2 URL Path
216 # @param string $3 JSON
217 # --------------------------------------
218 function elementAction {
219 local verb="${1}"
220 local path="${2}"
221 local json="${3}"
223 msg "Call REST API (${verb}) '${path}'"
225 callRestApi "${path}" "${verb}" "${json}"
227 if (( 0 != "${CURL_EXIT_CODE}" )); then
228 msg 'Failed curl call' f
229 else
230 local code="$(getValueFromHeader "${CURL_RESPONSE_HEADER}" "code")"
232 if (( 200 != $code )); then
233 msg "(${verb}) '${path}'" f
238 # --------------------------------------
239 # Helper to get an element (or a list)
241 # @param string $1 URL Path
242 # --------------------------------------
243 function elementGet {
244 local path="${1}"
246 elementAction 'GET' "${path}"
249 # --------------------------------------
250 # Helper to create an element
252 # @param string $1 URL Path
253 # @param string $2 JSON
254 # --------------------------------------
255 function elementCreate {
256 local path="${1}"
257 local json="${2}"
259 elementAction 'POST' "${path}" "${json}"
262 # --------------------------------------
263 # Helper to update an element
265 # @param string $1 URL Path
266 # @param string $2 JSON
267 # --------------------------------------
268 function elementUpdate {
269 local path="${1}"
270 local json="${2}"
272 elementAction 'PUT' "${path}" "${json}"
275 # --------------------------------------
276 # Helper to delete an element
278 # @param string $1 URL Path
279 # --------------------------------------
280 function elementDelete {
281 local path="${1}"
283 elementAction 'DELETE' "${path}"
286 # ====================================================================
288 # --------------------------------------
289 # Test the creation of a species
291 # @param string $1 Species name (to create)
292 # --------------------------------------
293 function testCreateSpecies () {
294 local name="${1}"
295 local flag=''
297 echo '========================================'
298 msg 'Test species creation'
300 elementCreate '/especie' '{"nombre":"'$name'"}'
302 local remote_name=$(getValueFromJson "${CURL_RESPONSE_DATA}" 'nombre')
303 flag=$([[ "${remote_name}" == "${name}" ]] && echo "s" || echo "f")
304 msg "[new] Species name (${name}, ${remote_name})" "${flag}"
306 NEW_ID="$(getValueFromJson "${CURL_RESPONSE_DATA}" "id")"
309 # --------------------------------------
310 # Test the list of species
312 # @param string $1 Expected amount of species (in the list)
313 # @param string $2 Expected species id (used if given)
314 # @param string $3 Expected species name (used if given)
315 # --------------------------------------
316 function testListSpecies () {
317 local amount="${1}"
318 local id="${2}"
319 local name="${3}"
321 echo '========================================'
322 msg 'Test species listing'
324 elementGet '/especie'
326 local remote_amount=$(countItemsInJsonList "${CURL_RESPONSE_DATA}")
327 flag=$( (($remote_amount == $amount)) && echo "s" || echo "f" )
328 msg "[list] Amount of species (${amount}, ${remote_amount})" "${flag}"
330 if [[ "${id}" ]]; then
331 local json=$(searchByKeyValue "${CURL_RESPONSE_DATA}" 'id' "${id}")
333 if [[ "${json}" ]]; then
334 msg "[list] Species found (ID ${id})" "s"
336 if [[ "${name}" ]]; then
337 local remote_name=$(getValueFromJson "${json}" 'nombre')
338 flag=$([[ "${remote_name}" == "${name}" ]] && echo "s" || echo "f")
339 msg "[list] Species name (${name}, ${remote_name})" "${flag}"
341 else
342 msg "[list] Species not found (ID ${id})" "f"
347 # --------------------------------------
348 # Test the edition of a species
350 # @param string $1 Species ID (to edit)
351 # @param string $2 New species name
352 # --------------------------------------
353 function testEditSpecies () {
354 local id="${1}"
355 local name="${2}"
357 echo '========================================'
358 msg 'Test species edition'
360 elementUpdate "/especie/${id}" '{"nombre":"'$name'"}'
362 local remote_id=$(getValueFromJson "${CURL_RESPONSE_DATA}" 'id')
363 flag=$([[ "${remote_id}" == "${id}" ]] && echo "s" || echo "f")
364 msg "[edit] Species id (${id}, ${remote_id})" "${flag}"
366 local remote_name=$(getValueFromJson "${CURL_RESPONSE_DATA}" 'nombre')
367 flag=$([[ "${remote_name}" == "${name}" ]] && echo "s" || echo "f")
368 msg "[edit] Species name (${name}, ${remote_name})" "${flag}"
371 # --------------------------------------
372 # Test the deletion of a species
374 # @param string $1 Species ID (to edit)
375 # @param string $2 Species name (used if given)
376 # --------------------------------------
377 function testDeleteSpecies () {
378 local id="${1}"
379 local name="${2}"
381 echo '========================================'
382 msg 'Test species deletion'
384 elementDelete "/especie/${id}"
386 local remote_id=$(getValueFromJson "${CURL_RESPONSE_DATA}" 'id')
387 flag=$([[ "${remote_id}" == "${id}" ]] && echo "s" || echo "f")
388 msg "[delete] Species id (${id}, ${remote_id})" "${flag}"
390 if [[ "${name}" ]]; then
391 local remote_name=$(getValueFromJson "${CURL_RESPONSE_DATA}" 'nombre')
392 flag=$([[ "${remote_name}" == "${name}" ]] && echo "s" || echo "f")
393 msg "[delete] Species name (${name}, ${remote_name})" "${flag}"
397 # ====================================================================
399 # Remove and create DDBB
400 # ----------------------
402 rm -f database.sqlite
403 sqlite3 database.sqlite < esquema-ddbb.sql
405 # ====================================================================
407 # Species battery of tests
408 # ------------------------
410 testListSpecies 0
412 SPECIES_DOG_NAME='perroxxxx'
413 testCreateSpecies "${SPECIES_DOG_NAME}"
414 SPECIES_DOG_ID="${NEW_ID}"
415 testListSpecies 1 "${SPECIES_DOG_ID}" "${SPECIES_DOG_NAME}"
416 SPECIES_DOG_NAME='perro'
417 testEditSpecies "${SPECIES_DOG_ID}" "${SPECIES_DOG_NAME}"
418 testListSpecies 1 "${SPECIES_DOG_ID}" "${SPECIES_DOG_NAME}"
420 SPECIES_CAT_NAME='gatoxxxx'
421 testCreateSpecies "${SPECIES_CAT_NAME}"
422 SPECIES_CAT_ID="${NEW_ID}"
423 testListSpecies 2 "${SPECIES_CAT_ID}" "${SPECIES_CAT_NAME}"
424 SPECIES_CAT_NAME='gato'
425 testEditSpecies "${SPECIES_CAT_ID}" "${SPECIES_CAT_NAME}"
426 testListSpecies 2 "${SPECIES_CAT_ID}" "${SPECIES_CAT_NAME}"
428 SPECIES_TMP_NAME='conejoxxxx'
429 testCreateSpecies "${SPECIES_TMP_NAME}"
430 SPECIES_TMP_ID="${NEW_ID}"
431 testListSpecies 3 "${SPECIES_TMP_ID}" "${SPECIES_TMP_NAME}"
432 SPECIES_TMP_NAME='conejo'
433 testEditSpecies "${SPECIES_TMP_ID}" "${SPECIES_TMP_NAME}"
434 testListSpecies 3 "${SPECIES_TMP_ID}" "${SPECIES_TMP_NAME}"
436 testDeleteSpecies "${SPECIES_TMP_ID}" "${SPECIES_TMP_NAME}"
437 testListSpecies 2 "${SPECIES_DOG_ID}" "${SPECIES_DOG_NAME}"
438 testListSpecies 2 "${SPECIES_CAT_ID}" "${SPECIES_CAT_NAME}"
440 # ====================================================================