import XCTest @testable import CollectorCore final class WireTests: XCTestCase { /// The canonical hardware frame, shared **verbatim** with the Rust decode /// test (`crates/signal-schema/tests/hardware_wire.rs`). Both languages /// independently commit to these exact bytes — that shared literal *is* the /// cross-language wire contract, so no cross-process execution is needed to /// prove Swift and Rust agree. /// /// Signal: schema_version=3, ts=0, source=Hardware(3), name=CpuLoad(28), /// value=0.5, tag=none. func testCanonicalHardwareFrameMatchesRust() { let signal = Signal(ts: 0, source: .hardware, name: .cpuLoad, value: 0.5) let expected: [UInt8] = [ 0x15, 0x00, 0x00, 0x00, // body_len = 21 0x05, 0x00, // schema_version = 5 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ts = 0 0x03, // source = Hardware 0x0A, // name = CpuLoad (10) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x3F, // value = 0.5 (f64 LE) 0x00, // tag_present = 0 ] XCTAssertEqual(encode(signal), expected) } /// The schema version must equal the Rust `SCHEMA_VERSION`, or the daemon /// drops every frame this collector sends. func testSchemaVersionMatchesRust() { XCTAssertEqual(SCHEMA_VERSION, 5) } /// The tagged-frame layout matches Rust too (hardware signals are untagged, /// but the encoder must still agree on the audited-tag case). func testTaggedFrameLayout() { let signal = Signal(ts: 0, source: .macos, name: .batteryPct, value: 1.0, tag: "ab") let frame = encode(signal) // body = 2+8+1+1+8+1 + (2 + 2) = 25 ; frame = 4 + 25 = 29 XCTAssertEqual(frame.count, 29) XCTAssertEqual(Array(frame.prefix(4)), [0x19, 0x00, 0x00, 0x00]) // body_len = 25 XCTAssertEqual(frame[24], 0x01) // tag_present XCTAssertEqual([frame[25], frame[26]], [0x02, 0x00]) // tag_len = 2 XCTAssertEqual([frame[27], frame[28]], Array("ab".utf8)) } /// Hardware signals never carry a tag and never carry content — the payload /// is a single `Double`. This mirrors the Rust privacy invariant. func testHardwareSignalsAreUntaggedScalars() { for name in [SignalName.cpuLoad, .batteryPct, .charging, .batteryDrawW, .thermalState] { let s = Signal(ts: 1, source: .hardware, name: name, value: 0.0) XCTAssertNil(s.tag) } } /// The IOKit CPU read yields a plausible fraction in `[0, 1]` (or nil while /// unavailable) — a real read against real hardware. func testCPUSamplerInRange() { let sampler = CPUSampler() _ = sampler.sample() Thread.sleep(forTimeInterval: 0.1) if let load = sampler.sample() { XCTAssertGreaterThanOrEqual(load, 0.0) XCTAssertLessThanOrEqual(load, 1.0) } } }