run.sh 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/bin/bash
  2. set -e
  3. image="$1"
  4. export POSTGRES_USER='my cool postgres user'
  5. export POSTGRES_PASSWORD='my cool postgres password'
  6. export POSTGRES_DB='my cool postgres database'
  7. cname="postgres-container-$RANDOM-$RANDOM"
  8. cid="$(docker run -d -e POSTGRES_USER -e POSTGRES_PASSWORD -e POSTGRES_DB --name "$cname" "$image")"
  9. trap "docker rm -vf $cid > /dev/null" EXIT
  10. psql() {
  11. docker run --rm -i \
  12. --link "$cname":postgres \
  13. --entrypoint psql \
  14. -e PGPASSWORD="$POSTGRES_PASSWORD" \
  15. "$image" \
  16. --host postgres \
  17. --username "$POSTGRES_USER" \
  18. --dbname "$POSTGRES_DB" \
  19. --quiet --no-align --tuples-only \
  20. "$@"
  21. }
  22. : ${POSTGRES_TEST_TRIES:=10}
  23. : ${POSTGRES_TEST_SLEEP:=2}
  24. tries="$POSTGRES_TEST_TRIES"
  25. while ! echo 'SELECT 1' | psql &> /dev/null; do
  26. (( tries-- ))
  27. if [ $tries -le 0 ]; then
  28. echo >&2 'postgres failed to accept connections in a reasonable amount of time!'
  29. ( set -x && docker logs "$cid" ) >&2 || true
  30. echo 'SELECT 1' | psql # to hopefully get a useful error message
  31. false
  32. fi
  33. echo >&2 -n .
  34. sleep "$POSTGRES_TEST_SLEEP"
  35. done
  36. echo 'CREATE TABLE test (a INT, b INT, c VARCHAR(255))' | psql
  37. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 0 ]
  38. psql <<'EOSQL'
  39. INSERT INTO test VALUES (1, 2, 'hello')
  40. EOSQL
  41. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 1 ]
  42. psql <<'EOSQL'
  43. INSERT INTO test VALUES (2, 3, 'goodbye!')
  44. EOSQL
  45. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 2 ]
  46. echo 'DELETE FROM test WHERE a = 1' | psql
  47. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 1 ]
  48. [ "$(echo 'SELECT c FROM test' | psql)" = 'goodbye!' ]
  49. echo 'DROP TABLE test' | psql