From 0ab06f62ca827bfbeaabc11b17d2d5e92014092b Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Sun, 19 Mar 2023 23:56:36 +0800 Subject: [PATCH] chore: add more tests (#3045) --- core/stat/metrics_test.go | 2 -- core/stat/usage_test.go | 64 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 core/stat/usage_test.go diff --git a/core/stat/metrics_test.go b/core/stat/metrics_test.go index 1f11a21b..7172994f 100644 --- a/core/stat/metrics_test.go +++ b/core/stat/metrics_test.go @@ -6,11 +6,9 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/zeromicro/go-zero/core/logx" ) func TestMetrics(t *testing.T) { - logx.Disable() DisableLog() defer logEnabled.Set(true) diff --git a/core/stat/usage_test.go b/core/stat/usage_test.go new file mode 100644 index 00000000..6cb5e19b --- /dev/null +++ b/core/stat/usage_test.go @@ -0,0 +1,64 @@ +package stat + +import ( + "bytes" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/zeromicro/go-zero/core/logx" +) + +func TestBToMb(t *testing.T) { + tests := []struct { + name string + bytes uint64 + expected float32 + }{ + { + name: "Test 1: Convert 0 bytes to MB", + bytes: 0, + expected: 0, + }, + { + name: "Test 2: Convert 1048576 bytes to MB", + bytes: 1048576, + expected: 1, + }, + { + name: "Test 3: Convert 2097152 bytes to MB", + bytes: 2097152, + expected: 2, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result := bToMb(test.bytes) + assert.Equal(t, test.expected, result) + }) + } +} + +func TestPrintUsage(t *testing.T) { + var buf bytes.Buffer + writer := logx.NewWriter(&buf) + old := logx.Reset() + logx.SetWriter(writer) + defer logx.SetWriter(old) + + printUsage() + + output := buf.String() + assert.Contains(t, output, "CPU:") + assert.Contains(t, output, "MEMORY:") + assert.Contains(t, output, "Alloc=") + assert.Contains(t, output, "TotalAlloc=") + assert.Contains(t, output, "Sys=") + assert.Contains(t, output, "NumGC=") + + lines := strings.Split(output, "\n") + assert.Len(t, lines, 2) + fields := strings.Split(lines[0], ", ") + assert.Len(t, fields, 5) +}