From e03aed00026cc2e59c09ca41f69a247e1a85cc89 Mon Sep 17 00:00:00 2001 From: Jan Lehnardt Date: Sun, 18 Dec 2022 10:40:06 +0100 Subject: [PATCH] Detect server start/stop more reliably. This is useful, especially in testing, since your test hosts might not reliabliy start the server within two seconds, so we do a definite check before progressing. By the same token, after `kill $server_pid` wait for the pid to be gone from the process list. Since now the script can end prematurely, I also added a cleanup function to make sure the temporary certs are removed in any case. n.b. this could also be done with the use of `trap 'fn' ERR` but that felt like a bit too much magic for this short a script. --- tests/test_datasette_https_server.sh | 39 +++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/tests/test_datasette_https_server.sh b/tests/test_datasette_https_server.sh index a701ad4c..aee262cc 100755 --- a/tests/test_datasette_https_server.sh +++ b/tests/test_datasette_https_server.sh @@ -4,6 +4,10 @@ python -m trustme # This creates server.pem, server.key, client.pem +cleanup () { + rm server.pem server.key client.pem +} + # Start the server in the background datasette --memory \ --ssl-keyfile=server.key \ @@ -13,21 +17,48 @@ datasette --memory \ # Store the background process ID in a variable server_pid=$! +test_url='https://localhost:8152/_memory.json' + # Wait for the server to start -sleep 2 + +# h/t https://github.com/pouchdb/pouchdb/blob/25db22fb0ff025b8d2c698da30c6c409066baa0c/bin/run-test.sh#L102-L113 +waiting=0 +until $(curl --output /dev/null --silent --insecure --head --fail --max-time 2 $test_url); do + if [ $waiting -eq 4 ]; then + echo "$test_url can not be reached, server failed to start" + cleanup + exit 1 + fi + let waiting=waiting+1 + sleep 1 +done # Make a test request using curl -curl -f --cacert client.pem 'https://localhost:8152/_memory.json' +curl -f --cacert client.pem $test_url # Save curl's exit code (-f option causes it to return one on HTTP errors) curl_exit_code=$? # Shut down the server kill $server_pid -sleep 1 +waiting=0 +# show all pids +# | find just the $server_pid +# | | don’t match on the previous grep +# | | | we don’t need the output +# | | | | +until ( ! ps ax | grep $server_pid | grep -v grep > /dev/null ); do + if [ $waiting -eq 4 ]; then + echo "$server_pid does still exist, server failed to stop" + cleanup + exit 1 + fi + let waiting=waiting+1 + sleep 1 +done # Clean up the certificates -rm server.pem server.key client.pem +cleanup echo $curl_exit_code exit $curl_exit_code