Codebase list golang-github-vbauerster-mpb / 8efbd5f
Merge pull request #3 from alevinval/master (formatter) cleanup with greater test coverage. Vladimir Bauer authored 9 years ago GitHub committed 9 years ago
2 changed file(s) with 57 addition(s) and 10 deletion(s). Raw diff Collapse all Expand all
00 package mpb
11
2 import (
3 "fmt"
4 "strings"
5 )
2 import "fmt"
63
74 const (
85 _ = iota
1512 type Units uint
1613
1714 const (
18 UnitNone Units = iota
15 _ = iota
1916 UnitBytes
2017 )
2118
5047
5148 func formatBytes(i int64) (result string) {
5249 switch {
53 case i > bytesInTiB:
50 case i >= bytesInTiB:
5451 result = fmt.Sprintf("%.1fTiB", float64(i)/bytesInTiB)
55 case i > bytesInGiB:
52 case i >= bytesInGiB:
5653 result = fmt.Sprintf("%.1fGiB", float64(i)/bytesInGiB)
57 case i > bytesInMiB:
54 case i >= bytesInMiB:
5855 result = fmt.Sprintf("%.1fMiB", float64(i)/bytesInMiB)
59 case i > bytesInKiB:
56 case i >= bytesInKiB:
6057 result = fmt.Sprintf("%.1fKiB", float64(i)/bytesInKiB)
6158 default:
6259 result = fmt.Sprintf("%db", i)
6360 }
64 result = strings.Trim(result, " ")
6561 return
6662 }
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 }