Merge pull request #3 from alevinval/master
(formatter) cleanup with greater test coverage.
Vladimir Bauer authored 9 years ago
GitHub committed 9 years ago
| 0 | 0 |
package mpb
|
| 1 | 1 |
|
| 2 | |
import (
|
| 3 | |
"fmt"
|
| 4 | |
"strings"
|
| 5 | |
)
|
|
2 |
import "fmt"
|
| 6 | 3 |
|
| 7 | 4 |
const (
|
| 8 | 5 |
_ = iota
|
|
| 15 | 12 |
type Units uint
|
| 16 | 13 |
|
| 17 | 14 |
const (
|
| 18 | |
UnitNone Units = iota
|
|
15 |
_ = iota
|
| 19 | 16 |
UnitBytes
|
| 20 | 17 |
)
|
| 21 | 18 |
|
|
| 50 | 47 |
|
| 51 | 48 |
func formatBytes(i int64) (result string) {
|
| 52 | 49 |
switch {
|
| 53 | |
case i > bytesInTiB:
|
|
50 |
case i >= bytesInTiB:
|
| 54 | 51 |
result = fmt.Sprintf("%.1fTiB", float64(i)/bytesInTiB)
|
| 55 | |
case i > bytesInGiB:
|
|
52 |
case i >= bytesInGiB:
|
| 56 | 53 |
result = fmt.Sprintf("%.1fGiB", float64(i)/bytesInGiB)
|
| 57 | |
case i > bytesInMiB:
|
|
54 |
case i >= bytesInMiB:
|
| 58 | 55 |
result = fmt.Sprintf("%.1fMiB", float64(i)/bytesInMiB)
|
| 59 | |
case i > bytesInKiB:
|
|
56 |
case i >= bytesInKiB:
|
| 60 | 57 |
result = fmt.Sprintf("%.1fKiB", float64(i)/bytesInKiB)
|
| 61 | 58 |
default:
|
| 62 | 59 |
result = fmt.Sprintf("%db", i)
|
| 63 | 60 |
}
|
| 64 | |
result = strings.Trim(result, " ")
|
| 65 | 61 |
return
|
| 66 | 62 |
}
|
|
0 |
package mpb_test
|
|
1 |
|
|
2 |
import (
|
|
3 |
"testing"
|
|
4 |
|
|
5 |
"github.com/vbauerster/mpb"
|
|
6 |
)
|
|
7 |
|
|
8 |
const (
|
|
9 |
_ = iota
|
|
10 |
KiB = 1 << (iota * 10)
|
|
11 |
MiB
|
|
12 |
GiB
|
|
13 |
TiB
|
|
14 |
)
|
|
15 |
|
|
16 |
func TestFormatNoUnits(t *testing.T) {
|
|
17 |
actual := mpb.Format(1234567).String()
|
|
18 |
expected := "1234567"
|
|
19 |
if actual != expected {
|
|
20 |
t.Errorf("Expected %q but found %q", expected, actual)
|
|
21 |
}
|
|
22 |
}
|
|
23 |
|
|
24 |
func TestFormatWidth(t *testing.T) {
|
|
25 |
actual := mpb.Format(1234567).Width(10).String()
|
|
26 |
expected := " 1234567"
|
|
27 |
if actual != expected {
|
|
28 |
t.Errorf("Expected %q but found %q", expected, actual)
|
|
29 |
}
|
|
30 |
}
|
|
31 |
|
|
32 |
func TestFormatToBytes(t *testing.T) {
|
|
33 |
inputs := []struct {
|
|
34 |
v int64
|
|
35 |
e string
|
|
36 |
}{
|
|
37 |
{v: 1000, e: "1000b"},
|
|
38 |
{v: 1024, e: "1.0KiB"},
|
|
39 |
{v: 3*MiB + 140*KiB, e: "3.1MiB"},
|
|
40 |
{v: 2 * GiB, e: "2.0GiB"},
|
|
41 |
{v: 4 * TiB, e: "4.0TiB"},
|
|
42 |
}
|
|
43 |
|
|
44 |
for _, input := range inputs {
|
|
45 |
actual := mpb.Format(input.v).To(mpb.UnitBytes).String()
|
|
46 |
if actual != input.e {
|
|
47 |
t.Errorf("Expected %q but found %q", input.e, actual)
|
|
48 |
}
|
|
49 |
}
|
|
50 |
}
|