SPB Git

Repository Public

parsers_test.go 7.5 KB 179 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/agent/collect/parsers_test.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142package collect4344import (45	"math"46	"testing"47)4849func mib(v float64) uint64 { return uint64(v*float64(1<<20) + 0.5) }5051func TestParseSwapUsage(t *testing.T) {52	cases := []struct {53		in          string54		total, used uint6455	}{56		{"total = 8192,00M  used = 7238,19M  free = 953,81M  (encrypted)", 8192 << 20, mib(7238.19)},57		{"total = 1024.00M  used = 223.19M  free = 800.81M  (encrypted)", 1024 << 20, mib(223.19)},58		{"vm.swapusage: total = 0,00M  used = 0,00M  free = 0,00M  (encrypted)", 0, 0},59		{"total = 2.00G  used = 1.50G  free = 0.50G", 2 << 30, 3 << 29},60	}61	for _, c := range cases {62		total, used, err := ParseSwapUsage(c.in)63		if err != nil || total != c.total || used != c.used {64			t.Errorf("%q: total=%d used=%d err=%v, want %d %d", c.in, total, used, err, c.total, c.used)65		}66	}67	if _, _, err := ParseSwapUsage("garbage"); err == nil {68		t.Error("garbage accepted")69	}70}7172const ioregSample = `+-o AGXAcceleratorG17X  <class AGXAcceleratorG17X, id 0x100000a2b, registered, matched, active, busy 0 (0 ms), retain 100>73    {74      "PerformanceStatistics" = {"In use system memory (driver)"=0,"Alloc system memory"=9160196096,"Tiler Utilization %"=56,"recoveryCount"=0,"lastRecoveryTime"=0,"Renderer Utilization %"=67,"TiledSceneBytes"=1572864,"Device Utilization %"=67,"SplitSceneCount"=0,"Allocated PB Size"=256901120,"In use system memory"=1798455296}75      "model" = "Apple M5 Max"76      "gpu-core-count" = 4077      "IOClass" = "AGXAcceleratorG17X"78    }79`8081func TestParseIORegGPU(t *testing.T) {82	g, err := ParseIORegGPU(ioregSample)83	if err != nil || !g.HasUtilization || g.UtilizationPct != 67 || !g.HasMem || g.MemUsed != 1798455296 || g.Model != "Apple M5 Max" || g.Cores != 40 {84		t.Fatalf("%+v %v", g, err)85	}86	if _, err := ParseIORegGPU(`"model" = "X"`); err != ErrNoGPUStats {87		t.Fatalf("missing statistics must be an error, got %v", err)88	}89	// Statistics block without the utilization key: memory only, never a made-up 0 %.90	g, err = ParseIORegGPU(`"PerformanceStatistics" = {"In use system memory"=5}`)91	if err != nil || g.HasUtilization || !g.HasMem {92		t.Fatalf("%+v %v", g, err)93	}94}9596func TestParsePing(t *testing.T) {97	mac := "PING 192.168.2.1 (192.168.2.1): 56 data bytes\n\n--- 192.168.2.1 ping statistics ---\n3 packets transmitted, 3 packets received, 0.0% packet loss\nround-trip min/avg/max/stddev = 1.234/2.345/3.456/0.500 ms\n"98	r, err := ParsePing(mac)99	if err != nil || r.LossPct != 0 || !r.HasRTT || r.AvgMS != 2.345 {100		t.Fatalf("%+v %v", r, err)101	}102	linux := "--- 10.0.0.1 ping statistics ---\n3 packets transmitted, 2 received, 33.3333% packet loss, time 2003ms\nrtt min/avg/max/mdev = 0.045/0.052/0.060/0.006 ms\n"103	r, err = ParsePing(linux)104	if err != nil || math.Abs(r.LossPct-33.333) > 0.01 || !r.HasRTT || r.AvgMS != 0.052 {105		t.Fatalf("%+v %v", r, err)106	}107	lost := "--- 192.168.2.173 ping statistics ---\n3 packets transmitted, 0 packets received, 100.0% packet loss\n"108	r, err = ParsePing(lost)109	if err != nil || r.LossPct != 100 || r.HasRTT {110		t.Fatalf("100%% loss must have no latency: %+v %v", r, err)111	}112	comma := "3 packets transmitted, 3 packets received, 0,0% packet loss\nround-trip min/avg/max/stddev = 1,2/2,5/3,4/0,5 ms\n"113	if r, err = ParsePing(comma); err != nil || r.AvgMS != 2.5 {114		t.Fatalf("%+v %v", r, err)115	}116	if _, err := ParsePing("ping: cannot resolve nowhere: Unknown host"); err == nil {117		t.Fatal("no summary must be an error")118	}119}120121func TestParsePSAndCPUTime(t *testing.T) {122	out := "    1 root              25504  12:42.68 /sbin/launchd\n  740 someone          102400   1:02:03 /Applications/My App.app/Contents/MacOS/My App\n 9 bob 10 2-01:00:00 sshd\nbad line\n"123	rows := ParsePS(out)124	if len(rows) != 3 {125		t.Fatalf("%d rows: %+v", len(rows), rows)126	}127	if rows[0].Name != "launchd" || rows[0].RSS != 25504*1024 || math.Abs(rows[0].CPUTime-762.68) > 1e-6 || rows[0].User != "root" {128		t.Errorf("%+v", rows[0])129	}130	if rows[1].Name != "My App" || rows[1].CPUTime != 3723 {131		t.Errorf("%+v", rows[1])132	}133	if rows[2].CPUTime != 2*86400+3600 {134		t.Errorf("%+v", rows[2])135	}136}137138func TestMisc(t *testing.T) {139	if p, ok := ParsePmsetBatt("Now drawing from 'Battery Power'\n -InternalBattery-0 (id=7733347)\t24%; discharging; 1:02 remaining present: true\n"); !ok || p != 24 {140		t.Errorf("battery %v %v", p, ok)141	}142	if _, ok := ParsePmsetBatt("Now drawing from 'AC Power'\n"); ok {143		t.Error("desktop must have no battery")144	}145	gw, ifc := ParseRouteGet("   route to: default\n    gateway: 192.168.2.1\n  interface: en0\n")146	if gw != "192.168.2.1" || ifc != "en0" {147		t.Errorf("%q %q", gw, ifc)148	}149	gw, ifc = ParseProcNetRoute("Iface\tDestination\tGateway\tFlags\nens3\t00000000\t0102A8C0\t0003\t0\t0\t0\t00000000\n")150	if gw != "192.168.2.1" || ifc != "ens3" {151		t.Errorf("%q %q", gw, ifc)152	}153	for in, want := range map[string]string{154		"//user:pass@192.168.2.173/clustr": "//192.168.2.173/clustr",155		"//guest@nas.local/share":          "//nas.local/share",156		"//192.168.2.175/clustr":           "//192.168.2.175/clustr",157		"host:/export/data":                "host:/export/data",158		"smb://u:p@h/s":                    "smb://h/s",159	} {160		if got := StripRemoteCredentials(in); got != want {161			t.Errorf("%q -> %q, want %q", in, got, want)162		}163	}164	if RemoteHost("//192.168.2.173/clustr") != "192.168.2.173" {165		t.Error("remote host")166	}167	if ParseIOPlatformUUID(`    "IOPlatformUUID" = "f5608413-BFE8-58F1-8758-E299CCBE5B24"`) != "F5608413-BFE8-58F1-8758-E299CCBE5B24" {168		t.Error("uuid")169	}170	ports := ParseHardwarePorts("Hardware Port: Wi-Fi\nDevice: en0\nEthernet Address: aa\n\nHardware Port: Ethernet\nDevice: en1\n")171	if InterfaceKind("en0", ports["en0"], false) != "wifi" || InterfaceKind("en1", ports["en1"], false) != "ethernet" || InterfaceKind("utun3", "", false) != "tunnel" {172		t.Errorf("%v", ports)173	}174	smart, internal, known := ParseDiskutilInfo("   SMART Status:              Verified\n   Device Location:           Internal\n")175	if smart != "verified" || !internal || !known {176		t.Error("diskutil")177	}178}179
Files main
Menu

Theme