From 352cf6dc775937d39f48bce8babef555351577a3 Mon Sep 17 00:00:00 2001 From: Michael Lange Date: Tue, 17 Oct 2017 10:17:07 -0700 Subject: [PATCH] Tests (and bug fixes!) for the format-bytes helper --- ui/app/helpers/format-bytes.js | 4 ++-- ui/tests/unit/helpers/format-bytes-test.js | 28 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 ui/tests/unit/helpers/format-bytes-test.js diff --git a/ui/app/helpers/format-bytes.js b/ui/app/helpers/format-bytes.js index 11d3c8e4e..53071fb18 100644 --- a/ui/app/helpers/format-bytes.js +++ b/ui/app/helpers/format-bytes.js @@ -14,12 +14,12 @@ const UNITS = ['Bytes', 'KiB', 'MiB']; */ export function formatBytes([bytes]) { let unitIndex = 0; - while (bytes >= 1024 && unitIndex < UNITS.length) { + while (bytes >= 1024 && unitIndex < UNITS.length - 1) { bytes /= 1024; unitIndex++; } - return `${Math.ceil(bytes)} ${UNITS[unitIndex]}`; + return `${Math.floor(bytes)} ${UNITS[unitIndex]}`; } export default Helper.helper(formatBytes); diff --git a/ui/tests/unit/helpers/format-bytes-test.js b/ui/tests/unit/helpers/format-bytes-test.js new file mode 100644 index 000000000..ba4f31083 --- /dev/null +++ b/ui/tests/unit/helpers/format-bytes-test.js @@ -0,0 +1,28 @@ +import { module, test } from 'ember-qunit'; +import { formatBytes } from 'nomad-ui/helpers/format-bytes'; + +module('format-bytes', 'Unit | Helper | format-bytes'); + +test('formats x < 1024 as bytes', function(assert) { + assert.equal(formatBytes([0]), '0 Bytes'); + assert.equal(formatBytes([100]), '100 Bytes'); + assert.equal(formatBytes([1023]), '1023 Bytes'); +}); + +test('formats 1024 <= x < 1024 * 1024 as KiB', function(assert) { + assert.equal(formatBytes([1024]), '1 KiB'); + assert.equal(formatBytes([125952]), '123 KiB'); + assert.equal(formatBytes([1024 * 1024 - 1]), '1023 KiB'); +}); + +test('formats 1024 * 1024 <= x < 1024 * 1024 * 1024 as MiB', function(assert) { + assert.equal(formatBytes([1024 * 1024]), '1 MiB'); + assert.equal(formatBytes([128974848]), '123 MiB'); +}); + +test('formats x > 1024 * 1024 * 1024 as MiB, since it is the highest allowed unit', function( + assert +) { + assert.equal(formatBytes([1024 * 1024 * 1024]), '1024 MiB'); + assert.equal(formatBytes([1024 * 1024 * 1024 * 4]), '4096 MiB'); +});