From 0ae78f347f0de326c8d1247749e3a8e6cb3e0e7c Mon Sep 17 00:00:00 2001 From: Arturo Pie Date: Wed, 2 Oct 2019 22:07:19 -0400 Subject: [PATCH] Fix and add tests for the dehumanize function --- packer/linux/conf/bin/bk-check-disk-space.sh | 9 +---- packer/linux/conf/bin/dehumanize-test.sh | 39 ++++++++++++++++++++ packer/linux/conf/bin/dehumanize.sh | 10 +++++ 3 files changed, 50 insertions(+), 8 deletions(-) create mode 100755 packer/linux/conf/bin/dehumanize-test.sh create mode 100644 packer/linux/conf/bin/dehumanize.sh diff --git a/packer/linux/conf/bin/bk-check-disk-space.sh b/packer/linux/conf/bin/bk-check-disk-space.sh index 52a98129f..43d072324 100755 --- a/packer/linux/conf/bin/bk-check-disk-space.sh +++ b/packer/linux/conf/bin/bk-check-disk-space.sh @@ -7,14 +7,7 @@ set -euo pipefail # or 500M, or a percentage like 5% # min inodes must be a number, default to 250,000 -# Converts human-readable units like 1.43K and 120.3M to bytes -dehumanize() { - awk '/[0-9][bB]?$/ {printf "%u\n", $1*1024} - /[tT][bB]?$/ {printf "%u\n", $1*(1024*1024*1024)} - /[gG][bB]?$/ {printf "%u\n", $1*(1024*1024)} - /[mM][bB]?$/ {printf "%u\n", $1*(1024)} - /[kK][bB]?$/ {printf "%u\n", $1*1}' <<< "$1" -} +. "$(dirname "$0")"/dehumanize.sh min_available=${1:-5G} docker_dir="/var/lib/docker/" diff --git a/packer/linux/conf/bin/dehumanize-test.sh b/packer/linux/conf/bin/dehumanize-test.sh new file mode 100755 index 000000000..1e3d4c393 --- /dev/null +++ b/packer/linux/conf/bin/dehumanize-test.sh @@ -0,0 +1,39 @@ +#!/bin/bash +set -o pipefail + +. "$(dirname "$0")"/dehumanize.sh + +test_without_unit(){ + assertEquals 45 $(dehumanize 45) +} + +test_bytes(){ + assertEquals 45 $(dehumanize 45b) + assertEquals 45 $(dehumanize 45B) +} + +test_kilobytes(){ + assertEquals 46080 $(dehumanize 45kb) + assertEquals 46080 $(dehumanize 45KB) +} + +test_megabytes(){ + assertEquals 47185920 $(dehumanize 45mb) + assertEquals 47185920 $(dehumanize 45MB) +} + +test_gigabytes(){ + assertEquals 48318382080 $(dehumanize 45gb) + assertEquals 48318382080 $(dehumanize 45GB) +} + +test_terabytes(){ + assertEquals 49478023249920 $(dehumanize 45tb) + assertEquals 49478023249920 $(dehumanize 45TB) +} + +test_using_decimals(){ + assertEquals 1610612736 $(dehumanize 1.5gb) +} + +. shunit2 diff --git a/packer/linux/conf/bin/dehumanize.sh b/packer/linux/conf/bin/dehumanize.sh new file mode 100644 index 000000000..ca90e8897 --- /dev/null +++ b/packer/linux/conf/bin/dehumanize.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# Converts human-readable units like 1.43K and 120.3M to bytes +dehumanize() { + awk '/[0-9][bB]?$/ {printf "%u\n", $1*1} + /[tT][bB]?$/ {printf "%u\n", $1*(1024*1024*1024*1024)} + /[gG][bB]?$/ {printf "%u\n", $1*(1024*1024*1024)} + /[mM][bB]?$/ {printf "%u\n", $1*(1024*1024)} + /[kK][bB]?$/ {printf "%u\n", $1*1024}' <<< "$1" +}