Skip to content
Permalink
Browse files

Implement --check to test if cache is fresh

  • Loading branch information
semanticart committed Feb 2, 2020
1 parent 780d577 commit ae8b56f9fe855dd469d7dbadbba2be21f736f100
Showing with 39 additions and 1 deletion.
  1. +10 −1 cache
  2. +29 −0 test/cache.bats
11 cache
@@ -8,6 +8,7 @@ usage() {
echo "usage: cache [--ttl SECONDS] [--cache-status CACHEABLE-STATUSES] [--stale_while_revalidate SECONDS] [cache-key] [command] [args for command]"
echo " --ttl # Treat previously cached content as fresh if fewer than SECONDS seconds have passed"
echo " --cache-status # Quoted and space-delimited exit statuses for [command] that are acceptable to cache."
echo " --check # Returns 0 if the content is cached and 1 if content is uncached or the TTL/SWR conditions are unmet."
echo " --stale-while-revalidate # Serve stale content for SECONDS past TTL while updating in the background"
echo " --help # show this help documentation"
}
@@ -22,6 +23,10 @@ do
shift # drop the key
shift # drop the value
;;
--check)
check_only=0
shift; # drop the key
;;
--force-stale)
force_stale=1
shift # drop the key
@@ -62,7 +67,7 @@ if [ -z "$cache_key" ]; then
exit 64
fi

if [ -z "$1" ]; then
if [ -z "$1" ] && [ -z "$check_only" ]; then
echo "Error: You must provide a command"
exit 64
fi
@@ -106,10 +111,14 @@ fresh () {
}

if [ -z "$force_stale" ] && fresh; then
[ -n "$check_only" ] && exit 0

status=$(cat "$cache_file.cache-status")

cat "$cache_file"
else
[ -n "$check_only" ] && exit 1

"$@" | tee "$cache_file"
status=${PIPESTATUS[0]}

@@ -109,6 +109,7 @@ wait_for_second_to_pass() {
[ "$status" -eq 0 ]
echo "$output" | grep -- --ttl
echo "$output" | grep -- --cache-status
echo "$output" | grep -- --check
echo "$output" | grep -- --stale-while-revalidate
echo "$output" | grep -- --help
}
@@ -208,3 +209,31 @@ wait_for_second_to_pass() {
[ "$status" -eq 64 ]
[ "$output" = "Error: You must provide a command" ]
}

@test "--check returns 0 if the content exists and is inside the TTL/SWR" {
run ./cache $TEST_KEY echo 1
[ "$status" -eq 0 ]
[ "$output" = "1" ]

run ./cache --stale-while-revalidate 1 --ttl 1 --check $TEST_KEY
[ "$status" -eq 0 ]
[ "$output" = "" ]
}

@test "--check returns 1 if the content exists but is outside the TTL/SWR" {
run ./cache $TEST_KEY echo 1
[ "$status" -eq 0 ]
[ "$output" = "1" ]

wait_for_second_to_pass

run ./cache --stale-while-revalidate 1 --ttl 0 --check $TEST_KEY
[ "$status" -eq 1 ]
[ "$output" = "" ]
}

@test "--check returns 1 if the content is not yet cached" {
run ./cache --check $TEST_KEY
[ "$status" -eq 1 ]
[ "$output" = "" ]
}

0 comments on commit ae8b56f

Please sign in to comment.
You can’t perform that action at this time.