From 6714ed268b26ac22ccbc15e7961f26bc10d6be5f Mon Sep 17 00:00:00 2001
From: Jorrit Schaap <schaap@astron.nl>
Date: Tue, 2 Oct 2018 14:26:33 +0000
Subject: [PATCH] SW-415: gracefully exit during tests

---
 SAS/LSMR/src/manage.py                        | 19 +++++++++++++++++++
 .../test/t_lsmrapp_scheduling_functional.run  |  1 +
 .../t_lsmrapp_specification_functional.run    |  1 +
 3 files changed, 21 insertions(+)

diff --git a/SAS/LSMR/src/manage.py b/SAS/LSMR/src/manage.py
index 5bc33ce0e8c..aef23caff02 100755
--- a/SAS/LSMR/src/manage.py
+++ b/SAS/LSMR/src/manage.py
@@ -1,9 +1,28 @@
 #!/usr/bin/env python3
 import os
 import sys
+import signal
+
+def subscribe_to_signals():
+    # raise SignalException when a signal is caught so django will exit gracefully
+    class SignalException(Exception):
+        pass
+
+    def signal_handler(_s, _f):
+        raise SignalException("signal %s received..." % (_s,))
+
+    for s in [signal.SIGHUP, signal.SIGINT]:
+        signal.signal(s, signal_handler)
+
 
 if __name__ == "__main__":
+    # do subscribe to more signals than django does for proper exits during testing
+    if os.environ.get('LSMR_RAISE_ON_SIGNALS', "False").lower() in ["true", "1", "on"]:
+        subscribe_to_signals()
+
+    # normal django startup. Specify the DJANGO_SETTINGS_MODULE, and run it.
     os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lsmr.settings")
+
     try:
         from django.core.management import execute_from_command_line
     except ImportError as exc:
diff --git a/SAS/LSMR/test/t_lsmrapp_scheduling_functional.run b/SAS/LSMR/test/t_lsmrapp_scheduling_functional.run
index 8777ac110a3..fe3d426967a 100755
--- a/SAS/LSMR/test/t_lsmrapp_scheduling_functional.run
+++ b/SAS/LSMR/test/t_lsmrapp_scheduling_functional.run
@@ -56,6 +56,7 @@ sleep 5
 echo "Started Django test database server\n\n"
 
 # Run Django test instance
+export LSMR_RAISE_ON_SIGNALS="True"
 DJANGO_TEST_PORT=8777
 lsmr -p $DJANGO_TEST_PORT -C $DJANGO_TEST_DATABASE_NAME &
 PIDS="$! $PIDS"
diff --git a/SAS/LSMR/test/t_lsmrapp_specification_functional.run b/SAS/LSMR/test/t_lsmrapp_specification_functional.run
index a3895786e8a..9983333a5e1 100755
--- a/SAS/LSMR/test/t_lsmrapp_specification_functional.run
+++ b/SAS/LSMR/test/t_lsmrapp_specification_functional.run
@@ -56,6 +56,7 @@ sleep 5
 echo "Started Django test database server\n\n"
 
 # Run Django test instance
+export LSMR_RAISE_ON_SIGNALS="True"
 DJANGO_TEST_PORT=8777
 lsmr -p $DJANGO_TEST_PORT -C $DJANGO_TEST_DATABASE_NAME &
 PIDS="$! $PIDS"
-- 
GitLab