get.pme.sh/pnats@v0.0.0-20240304004023-26bb5a137ed0/server/pse/pse_windows_test.go (about) 1 // Copyright 2015-2018 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 //go:build windows 15 // +build windows 16 17 package pse 18 19 import ( 20 "fmt" 21 "os/exec" 22 "runtime" 23 "strconv" 24 "strings" 25 "testing" 26 ) 27 28 func checkValues(t *testing.T, pcpu, tPcpu float64, rss, tRss int64) { 29 if pcpu != tPcpu { 30 delta := int64(pcpu - tPcpu) 31 if delta < 0 { 32 delta = -delta 33 } 34 if delta > 30 { // 30%? 35 t.Fatalf("CPUs did not match close enough: %f vs %f", pcpu, tPcpu) 36 } 37 } 38 if rss != tRss { 39 delta := rss - tRss 40 if delta < 0 { 41 delta = -delta 42 } 43 if delta > 1024*1024 { // 1MB 44 t.Fatalf("RSSs did not match close enough: %d vs %d", rss, tRss) 45 } 46 } 47 } 48 49 func TestPSEmulationWin(t *testing.T) { 50 var pcpu, tPcpu float64 51 var rss, vss, tRss int64 52 53 runtime.GC() 54 55 if err := ProcUsage(&pcpu, &rss, &vss); err != nil { 56 t.Fatalf("Error: %v", err) 57 } 58 59 runtime.GC() 60 61 imageName := getProcessImageName() 62 // query the counters using typeperf 63 out, err := exec.Command("typeperf.exe", 64 fmt.Sprintf("\\Process(%s)\\%% Processor Time", imageName), 65 fmt.Sprintf("\\Process(%s)\\Working Set - Private", imageName), 66 fmt.Sprintf("\\Process(%s)\\Virtual Bytes", imageName), 67 "-sc", "1").Output() 68 if err != nil { 69 t.Fatal("unable to run command", err) 70 } 71 72 // parse out results - refer to comments in procUsage for detail 73 results := strings.Split(string(out), "\r\n") 74 values := strings.Split(results[2], ",") 75 76 // parse pcpu 77 tPcpu, err = strconv.ParseFloat(strings.Trim(values[1], "\""), 64) 78 if err != nil { 79 t.Fatalf("Unable to parse percent cpu: %s", values[1]) 80 } 81 82 // parse private bytes (rss) 83 fval, err := strconv.ParseFloat(strings.Trim(values[2], "\""), 64) 84 if err != nil { 85 t.Fatalf("Unable to parse private bytes: %s", values[2]) 86 } 87 tRss = int64(fval) 88 89 checkValues(t, pcpu, tPcpu, rss, tRss) 90 91 runtime.GC() 92 93 // Again to test caching 94 if err = ProcUsage(&pcpu, &rss, &vss); err != nil { 95 t.Fatalf("Error: %v", err) 96 } 97 checkValues(t, pcpu, tPcpu, rss, tRss) 98 }