From 3b4f4a15dc1ce69b65dc2c09d8743f7ed30662e4 Mon Sep 17 00:00:00 2001
From: Simon Ruderich <simon@ruderich.org>
Date: Mon, 29 Jul 2013 12:58:17 +0200
Subject: [PATCH] tests: Call stop_servers when the shell terminates.

For example when set -e terminates the shell due to a failed process or
the user sends SIGINT.
---
 tests/common.sh            | 14 ++++++++++++--
 tests/tests-normal.sh      |  2 +-
 tests/tests-passthrough.sh |  2 +-
 3 files changed, 14 insertions(+), 4 deletions(-)

diff --git a/tests/common.sh b/tests/common.sh
index 37c691b..36dda8e 100644
--- a/tests/common.sh
+++ b/tests/common.sh
@@ -19,6 +19,12 @@
 set -e
 
 
+# Terminate all running servers when the script terminates.
+trap 'stop_servers' 0
+# Same when the user presses Ctrl-C.
+trap 'abort SIGINT' INT
+
+
 cleanup() {
     rm -f \
         tmp tlsproxy-log \
@@ -26,8 +32,12 @@ cleanup() {
         proxy-ca-key.pem proxy-ca.pem proxy-invalid.pem proxy-key.pem
 }
 stop_servers() {
-    kill $pid_server || echo 'failed to kill gnutls-serv'
-    kill $pid_tlsproxy || echo 'failed to kill tlsproxy'
+    if test -n "$pid_server"; then
+        kill $pid_server || echo 'failed to kill gnutls-serv'
+    fi
+    if test -n "$pid_tlsproxy"; then
+        kill $pid_tlsproxy || echo 'failed to kill tlsproxy'
+    fi
 }
 abort() {
     echo "abort: $*"
diff --git a/tests/tests-normal.sh b/tests/tests-normal.sh
index 83b63f4..57ce39a 100755
--- a/tests/tests-normal.sh
+++ b/tests/tests-normal.sh
@@ -109,7 +109,7 @@ test_proxy_successful
 test_invalid_certificate
 
 
-stop_servers
+# stop_servers in trap-handler
 cleanup
 
 exit 0
diff --git a/tests/tests-passthrough.sh b/tests/tests-passthrough.sh
index 500fb1b..f96e782 100755
--- a/tests/tests-passthrough.sh
+++ b/tests/tests-passthrough.sh
@@ -113,7 +113,7 @@ test_proxy_successful
 test_invalid_certificate
 
 
-stop_servers
+# stop_servers in trap-handler
 cleanup
 
 exit 0
-- 
2.49.0