feat(backup-monitor): implement ByteFormatter with tests
This commit is contained in:
parent
0493b8a42d
commit
3cbd04fe72
|
|
@ -42,6 +42,17 @@ require 'json'
|
||||||
require 'optparse'
|
require 'optparse'
|
||||||
|
|
||||||
class ByteFormatter
|
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
|
end
|
||||||
|
|
||||||
class PayloadBuilder
|
class PayloadBuilder
|
||||||
|
|
|
||||||
|
|
@ -3,3 +3,29 @@
|
||||||
|
|
||||||
require 'minitest/autorun'
|
require 'minitest/autorun'
|
||||||
require_relative 'notify_backup'
|
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
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue