Modern Apps git

← Modern-Apps.git

auto-protocol: add tests for sensor snapshot, stream transport and services

Commit
98f1c91ac087181d1f0e2b9d72dc60b1ac0d6776
Author
Vayun Mathur <[email protected]>
When
2026-11-07 04:45 UTC (29 days ago)
Parents
8d7ed93
Adds SensorSnapshotAllTypesTest (one payload-carrying and one
payload-less event of every sensor type folded through
SensorSnapshot.withEvents, plus a fully populated SensorEvent
serialize/parse round-trip), StreamTransportAndCredentialTest
(stream read/write/flush/close semantics including close-failure
propagation, GAL credential asset names, expiry arithmetic and
malformed-key rejection), and GalServicesRoundTripTest (a discovery
response carrying every service payload type, a fully populated
discovery request, and empty-message defaults).

Handwritten (non-protobuf) INSTRUCTION coverage rises to 91.5%.
The module total only reaches ~45% because the merged report counts
379 generated protobuf-lite classes in gal/ (36751 of 46217
instructions): MERGED_COVERAGE_EXCLUDES only strips
*OuterClass* protobuf classes, and these protos use
java_multiple_files. See the lead-inbox note; 85% of the total is
unreachable without a build-logic exclusion or a dedicated
generated-code exercise task.

Verified: :auto:protocol:testDebugUnitTest passes and
:auto:protocol:createMergedCoverageReport succeeds.

(cherry picked from commit f73040a53d9af683298984d77c9f18a3de218c1a)

Diff

auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalServicesRoundTripTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalServicesRoundTripTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalServicesRoundTripTest.ktnew file mode 100644index 0000000000..8ebf961a7c--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalServicesRoundTripTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.auto.protocol++import com.google.protobuf.ByteString+import com.vayunmathur.auto.protocol.gal.AudioConfiguration+import com.vayunmathur.auto.protocol.gal.BluetoothService+import com.vayunmathur.auto.protocol.gal.InputSourceService+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.MediaSourceService+import com.vayunmathur.auto.protocol.gal.NavigationStatusService+import com.vayunmathur.auto.protocol.gal.Sensor+import com.vayunmathur.auto.protocol.gal.SensorSourceService+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryRequest+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryResponse+import com.vayunmathur.auto.protocol.gal.TouchConfig+import com.vayunmathur.auto.protocol.gal.VendorExtensionService+import com.vayunmathur.auto.protocol.gal.VideoConfiguration+import com.vayunmathur.auto.protocol.gal.VideoResolution+import com.vayunmathur.auto.protocol.gal.WifiProjectionService+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Builds one fully populated [Service] per service payload type inside a+ * discovery response, and pins that the whole structure survives a+ * serialize/parse round-trip field-for-field.+ */+class GalServicesRoundTripTest {++    private fun bytes(vararg values: Int): ByteString = ByteString.copyFrom(values.map { it.toByte() }.toByteArray())++    @Test+    fun `discovery response with every service type round-trips`() {+        val audio = AudioConfiguration.newBuilder().setSamplingRate(48_000).setNumberOfBits(16).setNumberOfChannels(2)+        val video = VideoConfiguration.newBuilder()+            .setCodecResolution(VideoResolution.VIDEO_1920x1080).setFrameRate(60)+            .setWidthMargin(4).setHeightMargin(2).setDensity(320)+            .setField6(6).setField8(8).setField9(9).setField10(-10).setField11(bytes(1, 2))+        val response = ServiceDiscoveryResponse.newBuilder()+            .setHeadUnitName("Pioneer").setCarModel("Model X").setCarYear("2026").setCarSerial("SN1")+            .setDriverPosition(1).setHeadunitMake("Make").setHeadunitModel("HU-1")+            .setHeadunitSoftwareBuild("b42").setHeadunitSoftwareVersion("1.2.3")+            .setCanPlayNativeMediaDuringVr(true).setField13(13).setField14("f14")+            .setHideClock(true).setField17(bytes(17))+            .addServices(+                Service.newBuilder().setId(7).setSensorSource(+                    SensorSourceService.newBuilder()+                        .addSensors(Sensor.newBuilder().setType(1))+                        .addSensors(Sensor.newBuilder().setType(3))+                        .setLocationCharacterization(2)+                        .addAllFuelTypes(listOf(1, 2)).addAllEvConnectorTypes(listOf(3)),+                ),+            )+            .addServices(+                Service.newBuilder().setId(3).setMediaSink(+                    MediaSinkService.newBuilder()+                        .setAvailableType(MediaCodecType.MEDIA_CODEC_VIDEO_H264_BP)+                        .setAudioType(1).addAudioConfigs(audio).addVideoConfigs(video)+                        .setAvailableWhileInCall(1).setField7(7).setField8(8).setField9(9),+                ),+            )+            .addServices(+                Service.newBuilder().setId(4).setInputSource(+                    InputSourceService.newBuilder()+                        .addAllKeycodesSupported(listOf(24, 25))+                        .addTouchscreen(TouchConfig.newBuilder().setWidth(1920).setHeight(720).setType(1))+                        .addTouchpad(TouchConfig.newBuilder().setWidth(200).setHeight(100))+                        .addAllFeedbackEventsSupported(listOf(1)).setField5(5),+                ),+            )+            .addServices(+                Service.newBuilder().setId(5).setMediaSource(+                    MediaSourceService.newBuilder().setAvailableType(MediaCodecType.MEDIA_CODEC_AUDIO_PCM).setAudioConfig(audio),+                ),+            )+            .addServices(+                Service.newBuilder().setId(6).setBluetooth(+                    BluetoothService.newBuilder().setCarAddress("AA:BB:CC:DD:EE:FF").addAllSupportedPairingMethods(listOf(1, 2)),+                ),+            )+            .addServices(+                Service.newBuilder().setId(8)+                    .setRadio(bytes(1))+                    .setNavigationStatus(+                        NavigationStatusService.newBuilder().setMinimumIntervalMs(500).setType(2).setImageOptions(bytes(3, 4)),+                    ),+            )+            .addServices(+                Service.newBuilder().setId(12)+                    .setMediaPlaybackStatus(bytes(9)).setPhoneStatus(bytes(10)).setMediaBrowser(bytes(11))+                    .setVendorExtension(+                        VendorExtensionService.newBuilder().setName("vendor")+                            .addPackageAllowlist("com.example.a").addPackageAllowlist("com.example.b")+                            .setData(bytes(5)),+                    )+                    .setNotification(bytes(13)),+            )+            .addServices(+                Service.newBuilder().setId(14)+                    .setWifiProjection(WifiProjectionService.newBuilder().setCarWifiBssid("00:11:22:33:44:55"))+                    .setField15(bytes(15)),+            )+            .build()++        val parsed = ServiceDiscoveryResponse.parseFrom(response.toByteArray())+        assertEquals(response, parsed)+        assertEquals(8, parsed.servicesCount)+        assertEquals("Pioneer", parsed.headUnitName)+        assertTrue(parsed.hideClock)+        val sensor = parsed.getServices(0)+        assertEquals(listOf(1, 3), sensor.sensorSource.sensorsList.map { it.type })+        val sink = parsed.getServices(1).mediaSink+        assertEquals(48_000, sink.getAudioConfigs(0).samplingRate)+        assertEquals(VideoResolution.VIDEO_1920x1080, sink.getVideoConfigs(0).codecResolution)+        assertEquals(-10, sink.getVideoConfigs(0).field10)+        val input = parsed.getServices(2).inputSource+        assertEquals(listOf(24, 25), input.keycodesSupportedList)+        assertEquals(1920, input.getTouchscreen(0).width)+        assertEquals("AA:BB:CC:DD:EE:FF", parsed.getServices(4).bluetooth.carAddress)+        assertEquals(500, parsed.getServices(5).navigationStatus.minimumIntervalMs)+        assertEquals(listOf("com.example.a", "com.example.b"), parsed.getServices(6).vendorExtension.packageAllowlistList)+        assertEquals("00:11:22:33:44:55", parsed.getServices(7).wifiProjection.carWifiBssid)+        // Rebuilding from the parsed message yields identical bytes.+        val rebuilt = ServiceDiscoveryResponse.newBuilder().mergeFrom(parsed).build()+        assertTrue(response.toByteArray().contentEquals(rebuilt.toByteArray()))+    }++    @Test+    fun `discovery request with all fields round-trips`() {+        val request = ServiceDiscoveryRequest.newBuilder()+            .setField1(bytes(1)).setField2(bytes(2)).setField3(bytes(3))+            .setDeviceName("Pixel").setDeviceBrand("Google").setField6(bytes(6))+            .build()+        val parsed = ServiceDiscoveryRequest.parseFrom(request.toByteArray())+        assertEquals(request, parsed)+        assertEquals("Pixel", parsed.deviceName)+        assertEquals("Google", parsed.deviceBrand)+        assertTrue(parsed.hasField1() && parsed.hasField6())+    }++    @Test+    fun `empty discovery response and defaults`() {+        val empty = ServiceDiscoveryResponse.getDefaultInstance()+        assertEquals(0, empty.servicesCount)+        assertEquals("", empty.headUnitName)+        val parsed = ServiceDiscoveryResponse.parseFrom(empty.toByteArray())+        assertEquals(empty, parsed)+        // A service carrying only its required id still builds and parses.+        val bare = Service.newBuilder().setId(99).build()+        assertEquals(99, Service.parseFrom(bare.toByteArray()).id)+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorSnapshotAllTypesTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorSnapshotAllTypesTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorSnapshotAllTypesTest.ktnew file mode 100644index 0000000000..58aa892abc--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorSnapshotAllTypesTest.kt@@ -0,0 +1,182 @@+package com.vayunmathur.auto.protocol++import com.google.protobuf.ByteString+import com.vayunmathur.auto.protocol.gal.AccelerometerReading+import com.vayunmathur.auto.protocol.gal.CompassReading+import com.vayunmathur.auto.protocol.gal.DeadReckoningReading+import com.vayunmathur.auto.protocol.gal.DoorReading+import com.vayunmathur.auto.protocol.gal.DrivingStatusReading+import com.vayunmathur.auto.protocol.gal.EnvironmentReading+import com.vayunmathur.auto.protocol.gal.FuelReading+import com.vayunmathur.auto.protocol.gal.GearReading+import com.vayunmathur.auto.protocol.gal.GpsSatelliteEntry+import com.vayunmathur.auto.protocol.gal.GpsSatelliteReading+import com.vayunmathur.auto.protocol.gal.GyroscopeReading+import com.vayunmathur.auto.protocol.gal.HvacReading+import com.vayunmathur.auto.protocol.gal.LightReading+import com.vayunmathur.auto.protocol.gal.LocationReading+import com.vayunmathur.auto.protocol.gal.NightReading+import com.vayunmathur.auto.protocol.gal.ObdiiReading+import com.vayunmathur.auto.protocol.gal.OdometerReading+import com.vayunmathur.auto.protocol.gal.ParkingBrakeReading+import com.vayunmathur.auto.protocol.gal.PassengerReading+import com.vayunmathur.auto.protocol.gal.RawEvTripReading+import com.vayunmathur.auto.protocol.gal.RawVehicleEnergyReading+import com.vayunmathur.auto.protocol.gal.RpmReading+import com.vayunmathur.auto.protocol.gal.SensorEvent+import com.vayunmathur.auto.protocol.gal.SpeedReading+import com.vayunmathur.auto.protocol.gal.SensorType+import com.vayunmathur.auto.protocol.gal.TirePressureReading+import com.vayunmathur.auto.protocol.gal.TollCardReading+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Folds one payload-carrying event of every sensor type through+ * [SensorSnapshot.withEvents], and pins that payload-less or payload-free+ * (MISSING) events never clobber last-known values.+ */+class SensorSnapshotAllTypesTest {++    private fun fullEvent(): SensorEvent = SensorEvent.newBuilder()+        .setSensorType(SensorType.LOCATION)+        .setLocation(LocationReading.newBuilder().setLatitudeE7(377_000_000L).setLongitudeE7(-1_220_000_000L).setAccuracyM(5).setTimestampMs(123_456L))+        .setCompass(CompassReading.newBuilder().setHeadingDeg(270))+        .setSpeed(SpeedReading.newBuilder().setSpeedMps(13.5))+        .setNight(NightReading.newBuilder().setIsNight(true))+        .setDrivingStatus(DrivingStatusReading.newBuilder().setParked(false))+        .setRpm(RpmReading.newBuilder().setField1(3_200))+        .setOdometer(OdometerReading.newBuilder().setField1(88_000).setField2(120))+        .setFuel(FuelReading.newBuilder().setField1(55).setField2(10).setField3(700))+        .setParkingBrake(ParkingBrakeReading.newBuilder().setField1(true))+        .setGear(GearReading.newBuilder().setField1(4))+        .setObdii(ObdiiReading.newBuilder().setField1(ByteString.copyFrom(byteArrayOf(1, 2, 3))))+        .setEnvironment(EnvironmentReading.newBuilder().setField1(21).setField2(40).setField3(101))+        .setHvac(HvacReading.newBuilder().setField1(22).setField2(3))+        .setDeadReckoning(DeadReckoningReading.newBuilder().setField1(7).addAllField2(listOf(1, 2)))+        .setPassenger(PassengerReading.newBuilder().setField1(true))+        .setDoor(DoorReading.newBuilder().setField1(true).setField2(false).addAllField3(listOf(true, false)))+        .setLight(LightReading.newBuilder().setField1(2).setField2(1).setField3(true))+        .setTirePressure(TirePressureReading.newBuilder().addAllField1(listOf(32, 33, 31, 34)))+        .setAccelerometer(AccelerometerReading.newBuilder().setField1(1).setField2(2).setField3(98))+        .setGyroscope(GyroscopeReading.newBuilder().setField1(4).setField2(5).setField3(6))+        .setGpsSatellite(+            GpsSatelliteReading.newBuilder().setField1(9).setField2(3)+                .addField3(GpsSatelliteEntry.newBuilder().setField1(1).setField2(2).setField3(true).setField4(4).setField5(5)),+        )+        .setTollCard(TollCardReading.newBuilder().setField1(true))+        .setRawVehicleEnergy(RawVehicleEnergyReading.newBuilder().setField1(ByteString.copyFrom(byteArrayOf(9, 8))))+        .setRawEvTrip(RawEvTripReading.newBuilder().setField1(ByteString.copyFrom(byteArrayOf(7))))+        .build()++    /** One event per type, each carrying only its own payload (as a batch would). */+    private fun perTypeEvents(full: SensorEvent): List<SensorEvent> = listOf(+        SensorEvent.newBuilder().setSensorType(SensorType.LOCATION).setLocation(full.location).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.COMPASS).setCompass(full.compass).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.SPEED).setSpeed(full.speed).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.NIGHT_MODE).setNight(full.night).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.DRIVING_STATUS_DATA).setDrivingStatus(full.drivingStatus).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.RPM).setRpm(full.rpm).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.ODOMETER).setOdometer(full.odometer).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.FUEL).setFuel(full.fuel).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.PARKING_BRAKE).setParkingBrake(full.parkingBrake).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.GEAR).setGear(full.gear).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.OBDII_DIAGNOSTIC_CODE).setObdii(full.obdii).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.ENVIRONMENT_DATA).setEnvironment(full.environment).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.HVAC_DATA).setHvac(full.hvac).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.DEAD_RECKONING_DATA).setDeadReckoning(full.deadReckoning).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.PASSENGER_DATA).setPassenger(full.passenger).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.DOOR_DATA).setDoor(full.door).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.LIGHT_DATA).setLight(full.light).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.TIRE_PRESSURE_DATA).setTirePressure(full.tirePressure).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.ACCELEROMETER_DATA).setAccelerometer(full.accelerometer).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.GYROSCOPE_DATA).setGyroscope(full.gyroscope).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.GPS_SATELLITE_DATA).setGpsSatellite(full.gpsSatellite).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.TOLL_CARD).setTollCard(full.tollCard).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.RAW_VEHICLE_ENERGY_MODEL).setRawVehicleEnergy(full.rawVehicleEnergy).build(),+        SensorEvent.newBuilder().setSensorType(SensorType.RAW_EV_TRIP_SETTINGS).setRawEvTrip(full.rawEvTrip).build(),+    )++    @Test+    fun `every payload type folds into the snapshot`() {+        val full = fullEvent()+        val snapshot = SensorSnapshot().withEvents(perTypeEvents(full))+        assertEquals(LocationFix(377_000_000L, -1_220_000_000L, 5, 123_456L), snapshot.location)+        assertEquals(270, snapshot.compassHeadingDeg)+        assertEquals(13.5, snapshot.speedMps)+        assertEquals(true, snapshot.isNight)+        assertFalse(snapshot.parked)+        assertEquals(full.rpm, snapshot.rpm)+        assertEquals(full.odometer, snapshot.odometer)+        assertEquals(full.fuel, snapshot.fuel)+        assertEquals(full.parkingBrake, snapshot.parkingBrake)+        assertEquals(full.gear, snapshot.gear)+        assertEquals(full.obdii, snapshot.obdii)+        assertEquals(full.environment, snapshot.environment)+        assertEquals(full.hvac, snapshot.hvac)+        assertEquals(full.deadReckoning, snapshot.deadReckoning)+        assertEquals(full.passenger, snapshot.passenger)+        assertEquals(full.door, snapshot.door)+        assertEquals(full.light, snapshot.light)+        assertEquals(full.tirePressure, snapshot.tirePressure)+        assertEquals(full.accelerometer, snapshot.accelerometer)+        assertEquals(full.gyroscope, snapshot.gyroscope)+        assertEquals(full.gpsSatellite, snapshot.gpsSatellite)+        assertEquals(full.tollCard, snapshot.tollCard)+        assertEquals(full.rawVehicleEnergy, snapshot.rawVehicleEnergy)+        assertEquals(full.rawEvTrip, snapshot.rawEvTrip)+        // Equality / hash over the populated snapshot is stable.+        assertEquals(snapshot, snapshot.copy())+        assertEquals(snapshot.hashCode(), snapshot.copy().hashCode())+        assertTrue(snapshot.toString().contains("speedMps=13.5"))+    }++    @Test+    fun `payload-less events of every type keep last known`() {+        val full = fullEvent()+        val populated = SensorSnapshot().withEvents(perTypeEvents(full))+        val bare = SensorType.entries+            .map { SensorEvent.newBuilder().setSensorType(it).build() }+        assertEquals(populated, populated.withEvents(bare))+        assertEquals(SensorSnapshot(), SensorSnapshot().withEvents(bare))+        assertEquals(SensorSnapshot(), SensorSnapshot().withEvents(emptyList()))+    }++    @Test+    fun `optional sub-fields fall back to null when absent`() {+        val event = SensorEvent.newBuilder().setSensorType(SensorType.LOCATION)+            .setLocation(LocationReading.newBuilder().setLatitudeE7(1L).setLongitudeE7(2L))+            .build()+        val snapshot = SensorSnapshot().withEvents(listOf(event))+        assertEquals(LocationFix(1L, 2L, null, null), snapshot.location)+        // Speed/night/driving/compass with a payload object but no leaf value change nothing.+        val leaves = listOf(+            SensorEvent.newBuilder().setSensorType(SensorType.SPEED).setSpeed(SpeedReading.getDefaultInstance()).build(),+            SensorEvent.newBuilder().setSensorType(SensorType.NIGHT_MODE).setNight(NightReading.getDefaultInstance()).build(),+            SensorEvent.newBuilder().setSensorType(SensorType.DRIVING_STATUS_DATA).setDrivingStatus(DrivingStatusReading.getDefaultInstance()).build(),+            SensorEvent.newBuilder().setSensorType(SensorType.COMPASS).setCompass(CompassReading.getDefaultInstance()).build(),+        )+        val after = snapshot.withEvents(leaves)+        assertEquals(0.0, after.speedMps)+        assertNull(after.isNight)+        assertTrue(after.parked)+        assertNull(after.compassHeadingDeg)+    }++    @Test+    fun `full sensor event serializes and parses back identically`() {+        val full = fullEvent()+        val parsed = SensorEvent.parseFrom(full.toByteArray())+        assertEquals(full, parsed)+        assertEquals(full.hashCode(), parsed.hashCode())+        assertTrue(parsed.hasLocation() && parsed.hasGpsSatellite() && parsed.hasRawEvTrip())+        assertNotNull(parsed.toString())+        // A fresh builder merged from the parsed message re-serializes identically.+        val rebuilt = SensorEvent.newBuilder().mergeFrom(parsed).build()+        assertTrue(full.toByteArray().contentEquals(rebuilt.toByteArray()))+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/StreamTransportAndCredentialTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/StreamTransportAndCredentialTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/StreamTransportAndCredentialTest.ktnew file mode 100644index 0000000000..e39c5fa7d0--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/StreamTransportAndCredentialTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.auto.protocol++import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.io.IOException+import java.io.InputStream+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class StreamTransportAndCredentialTest {++    @Test+    fun `stream transport reads writes flushes and closes both`() {+        val input = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4))+        val output = ByteArrayOutputStream()+        val transport = StreamTransport(input, output)+        val buffer = ByteArray(2)+        assertEquals(2, transport.read(buffer, 0, 2))+        assertContentEquals(byteArrayOf(1, 2), buffer)+        assertEquals(2, transport.read(buffer, 0, 2))+        assertEquals(-1, transport.read(buffer, 0, 2))+        transport.write(byteArrayOf(9, 8, 7), 1, 1)+        transport.flush()+        assertContentEquals(byteArrayOf(8), output.toByteArray())+        transport.close()+    }++    @Test+    fun `close still closes output when input close throws`() {+        val throwingInput = object : InputStream() {+            override fun read(): Int = -1+            override fun close(): Unit = throw IOException("input close failed")+        }+        val output = ByteArrayOutputStream()+        var outputClosed = false+        val trackingOutput = object : java.io.OutputStream() {+            override fun write(b: Int) = output.write(b)+            override fun close() { outputClosed = true }+        }+        val transport = StreamTransport(throwingInput, trackingOutput)+        assertFailsWith<IOException> { transport.close() }+        assertTrue(outputClosed)+    }++    @Test+    fun `read and write honour offsets`() {+        val transport = StreamTransport(ByteArrayInputStream(byteArrayOf(5, 6, 7)), ByteArrayOutputStream())+        val buffer = byteArrayOf(0, 0, 0, 0)+        assertEquals(3, transport.read(buffer, 1, 3))+        assertContentEquals(byteArrayOf(0, 5, 6, 7), buffer)+    }++    private fun asset(name: String): String = File("src/main/assets/gal", name).readText()++    @Test+    fun `credential asset names and expiry arithmetic`() {+        assertEquals("gal/client-cert.pem", GalCredential.CERT_ASSET)+        assertEquals("gal/client-key.pem", GalCredential.KEY_ASSET)+        assertEquals("gal/root.pem", GalCredential.ROOT_ASSET)+        val cert = asset("client-cert.pem")+        val notAfter = GalCredential.notAfterMillis(cert)+        assertTrue(notAfter > 0L)+        assertEquals(0L, GalCredential.daysRemaining(cert, notAfter))+        assertEquals(30L, GalCredential.daysRemaining(cert, notAfter - 30L * 86_400_000L - 3_600_000L))+        assertEquals(-2L, GalCredential.daysRemaining(cert, notAfter + 2L * 86_400_000L))+        // A context built from the shipped PEMs exposes TLSv1.2 engines.+        val context = GalCredential.create(cert, asset("client-key.pem"), asset("root.pem"))+        assertEquals("TLSv1.2", context.protocol)+    }++    @Test+    fun ` malformed private key is rejected`() {+        assertFailsWith<java.security.spec.InvalidKeySpecException> {+            GalCredential.create(asset("client-cert.pem"), "-----BEGIN PRIVATE KEY-----\naGVsbG8=\n-----END PRIVATE KEY-----", asset("root.pem"))+        }+    }+}