Debian Codegraph @

server/pse/pse_test.go

raw
1 // Copyright 2015-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package pse
15
16 import (
17 "fmt"
18 "os"
19 "os/exec"
20 "runtime"
21 "runtime/debug"
22 "testing"
23 )
24
25 func TestPSEmulationCPU(t *testing.T) {
26 if runtime.GOOS == "windows" {
27 t.Skipf("Skipping this test on Windows")
28 }
29 var rss, vss int64
30 var pcpu, psPcpu float64
31
32 debug.FreeOSMemory()
33
34 // PS version first
35 pidStr := fmt.Sprintf("%d", os.Getpid())
36 out, err := exec.Command("ps", "o", "pcpu=", "-p", pidStr).Output()
37 if err != nil {
38 t.Fatalf("Failed to execute ps command: %v\n", err)
39 }
40
41 // Our internal version
42 ProcUsage(&pcpu, &rss, &vss)
43
44 fmt.Sscanf(string(out), "%f", &psPcpu)
45
46 if pcpu != psPcpu {
47 delta := int64(pcpu - psPcpu)
48 if delta < 0 {
49 delta = -delta
50 }
51 if delta > 30 { // 30%?
52 t.Fatalf("CPUs did not match close enough: %f vs %f", pcpu, psPcpu)
53 }
54 }
55 }
56
57 func TestPSEmulationMem(t *testing.T) {
58 if runtime.GOOS == "windows" {
59 t.Skipf("Skipping this test on Windows")
60 }
61 var rss, vss, psRss, psVss int64
62 var pcpu float64
63
64 debug.FreeOSMemory()
65
66 // PS version first
67 pidStr := fmt.Sprintf("%d", os.Getpid())
68 out, err := exec.Command("ps", "o", "rss=,vsz=", "-p", pidStr).Output()
69 if err != nil {
70 t.Fatalf("Failed to execute ps command: %v\n", err)
71 }
72
73 fmt.Sscanf(string(out), "%d %d", &psRss, &psVss)
74 psRss *= 1024 // 1k blocks, want bytes.
75 psVss *= 1024 // 1k blocks, want bytes.
76
77 debug.FreeOSMemory()
78
79 // Our internal version
80 ProcUsage(&pcpu, &rss, &vss)
81
82 if rss != psRss {
83 delta := rss - psRss
84 if delta < 0 {
85 delta = -delta
86 }
87 if delta > 1024*1024 { // 1MB
88 t.Fatalf("RSSs did not match close enough: %d vs %d", rss, psRss)
89 }
90 }
91 }