76 أسطر
2.1 KiB
Bash
76 أسطر
2.1 KiB
Bash
|
||
#!/usr/bin/env bash
|
||
# test_api.sh íÌÑøÈ ÇáÜ API æíÏæøä ÇáäÊÇÆÌ Ýí test_results.log
|
||
BASE_URL=${BASE_URL:-http://localhost:5000}
|
||
LOGFILE="./test_results.log"
|
||
|
||
timestamp(){ date +"%Y-%m-%d %H:%M:%S"; }
|
||
|
||
echo "=== TEST RUN $(timestamp) ===" >> "$LOGFILE"
|
||
|
||
run(){
|
||
method=$1; url=$2; data=$3
|
||
if [ -n "$data" ]; then
|
||
resp=$(curl -s -w "\n%{http_code}" -X "$method" -H "Content-Type: application/json" -d "$data" "$url")
|
||
else
|
||
resp=$(curl -s -w "\n%{http_code}" -X "$method" "$url")
|
||
fi
|
||
body=$(echo "$resp" | sed '$d')
|
||
code=$(echo "$resp" | tail -n1)
|
||
echo "[$(timestamp)] $method $url -> $code" >> "$LOGFILE"
|
||
echo "$body" >> "$LOGFILE"
|
||
echo "----" >> "$LOGFILE"
|
||
}
|
||
|
||
# 1. health
|
||
run GET "$BASE_URL/health"
|
||
|
||
# 2. list books (should be empty)
|
||
run GET "$BASE_URL/books"
|
||
|
||
# 3. add books
|
||
b1='{"id":1,"title":"Clean Code","author":"Robert C. Martin","year":2008,"copies":1}'
|
||
b2='{"id":2,"title":"The Pragmatic Programmer","author":"Andrew Hunt","year":1999,"copies":2}'
|
||
run POST "$BASE_URL/books" "$b1"
|
||
run POST "$BASE_URL/books" "$b2"
|
||
|
||
# 4. add users
|
||
u1='{"id":10,"name":"Mustafa","email":"m@example.com"}'
|
||
u2='{"id":11,"name":"Sara","email":"s@example.com"}'
|
||
run POST "$BASE_URL/users" "$u1"
|
||
run POST "$BASE_URL/users" "$u2"
|
||
|
||
# 5. borrow book id=1 by user 10 (should succeed)
|
||
loan1='{"user_id":10,"book_id":1}'
|
||
run POST "$BASE_URL/loans" "$loan1"
|
||
|
||
# 6. borrow same book id=1 again -> copies=1 so should fail (409)
|
||
run POST "$BASE_URL/loans" "$loan1"
|
||
|
||
# 7. borrow book id=2 twice (copies=2) by two users -> both succeed
|
||
loan2='{"user_id":11,"book_id":2}'
|
||
run POST "$BASE_URL/loans" "$loan2"
|
||
run POST "$BASE_URL/loans" '{"user_id":10,"book_id":2}'
|
||
|
||
# 8. list active loans
|
||
run GET "$BASE_URL/loans?active=true"
|
||
|
||
# 9. return loan id 1
|
||
run PUT "$BASE_URL/loans/1/return"
|
||
|
||
# 10. try returning again (should get 400)
|
||
run PUT "$BASE_URL/loans/1/return"
|
||
|
||
# 11. delete book 999 (not exist -> 404)
|
||
run DELETE "$BASE_URL/books/999"
|
||
|
||
# 12. update book 2
|
||
run PUT "$BASE_URL/books/2" '{"copies":1,"year":2000}'
|
||
|
||
# 13. list books & loans
|
||
run GET "$BASE_URL/books"
|
||
run GET "$BASE_URL/loans"
|
||
|
||
echo "=== END TEST RUN $(timestamp) ===" >> "$LOGFILE"
|
||
echo "" >> "$LOGFILE"
|