From fcc702041bb8558bdc80f89fe7adb1d45fb6195c Mon Sep 17 00:00:00 2001 From: Pavel Boldyrev <627562+bpg@users.noreply.github.com> Date: Sat, 13 May 2023 21:53:40 -0400 Subject: [PATCH] fix(vm): Regression: cannot create disks larger than 99G --- proxmox/types/disk_size.go | 12 +++++++---- proxmox/types/disk_size_test.go | 38 +++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/proxmox/types/disk_size.go b/proxmox/types/disk_size.go index d80d0869e..6efa50622 100644 --- a/proxmox/types/disk_size.go +++ b/proxmox/types/disk_size.go @@ -97,17 +97,21 @@ func formatDiskSize(size int64) string { return fmt.Sprintf("%d", size) } + round := func(f float64) string { + return strconv.FormatFloat(math.Ceil(f*100)/100, 'f', -1, 64) + } + if size < 1024*1024 { - return fmt.Sprintf("%.2gK", float64(size)/1024) + return round(float64(size)/1024) + "K" } if size < 1024*1024*1024 { - return fmt.Sprintf("%.2gM", float64(size)/1024/1024) + return round(float64(size)/1024/1024) + "M" } if size < 1024*1024*1024*1024 { - return fmt.Sprintf("%.2gG", float64(size)/1024/1024/1024) + return round(float64(size)/1024/1024/1024) + "G" } - return fmt.Sprintf("%.2gT", float64(size)/1024/1024/1024/1024) + return round(float64(size)/1024/1024/1024/1024) + "T" } diff --git a/proxmox/types/disk_size_test.go b/proxmox/types/disk_size_test.go index 5a982c89b..eb7b7dce7 100644 --- a/proxmox/types/disk_size_test.go +++ b/proxmox/types/disk_size_test.go @@ -6,7 +6,11 @@ package types -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestParseDiskSize(t *testing.T) { t.Parallel() @@ -60,7 +64,7 @@ func TestFormatDiskSize(t *testing.T) { }{ {"handle 0 size", 0, "0"}, {"handle bytes", 1001, "1001"}, - {"handle kilobytes", 1234, "1.2K"}, + {"handle kilobytes", 1234, "1.21K"}, {"handle megabytes", 2097152, "2M"}, {"handle gigabytes", 2147483648, "2G"}, {"handle terabytes", 2199023255552, "2T"}, @@ -75,3 +79,33 @@ func TestFormatDiskSize(t *testing.T) { }) } } + +func TestToFromGigabytes(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + size int + want string + }{ + {"handle 0 size", 0, "0"}, + {"handle 99 GB", 99, "99G"}, + {"handle 100 GB", 100, "100G"}, + {"handle 101 GB", 101, "101G"}, + {"handle 1023 GB", 1023, "1023G"}, + {"handle 1024 GB", 1024, "1T"}, + {"handle 1025 GB", 1025, "1.01T"}, + } + for _, test := range tests { + tt := test + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ds := DiskSizeFromGigabytes(tt.size) + gb := ds.InGigabytes() + assert.Equal(t, tt.size, gb) + if got := ds.String(); got != tt.want { + t.Errorf("DiskSize.String() = %v, want %v", got, tt.want) + } + }) + } +}