diff --git a/scripts/notify_backup.rb b/scripts/notify_backup.rb index 6f703dd..8e14e61 100644 --- a/scripts/notify_backup.rb +++ b/scripts/notify_backup.rb @@ -42,6 +42,17 @@ require 'json' require 'optparse' class ByteFormatter + UNITS = [['GB', 1_073_741_824], ['MB', 1_048_576], ['KB', 1_024]].freeze + + def self.format(bytes) + return nil if bytes.nil? + + bytes = bytes.to_i + unit, divisor = UNITS.find { |_, d| bytes >= d } + return "#{bytes} B" unless unit + + '%.2f %s' % [bytes.to_f / divisor, unit] + end end class PayloadBuilder diff --git a/scripts/notify_backup_test.rb b/scripts/notify_backup_test.rb index 9bf08c2..1bf7a7b 100644 --- a/scripts/notify_backup_test.rb +++ b/scripts/notify_backup_test.rb @@ -3,3 +3,29 @@ require 'minitest/autorun' require_relative 'notify_backup' + +class ByteFormatterTest < Minitest::Test + def test_gigabytes + assert_equal '4.50 GB', ByteFormatter.format(4_831_838_208) + end + + def test_megabytes + assert_equal '823.00 MB', ByteFormatter.format(862_978_048) + end + + def test_kilobytes + assert_equal '12.00 KB', ByteFormatter.format(12_288) + end + + def test_bytes_below_one_kb + assert_equal '512 B', ByteFormatter.format(512) + end + + def test_nil_returns_nil + assert_nil ByteFormatter.format(nil) + end + + def test_string_integer_is_coerced + assert_equal '1.00 GB', ByteFormatter.format('1073741824') + end +end