I’m trying to refactor my code to be more testable.
The code I am writing does a lot of interactions with the ethernet port.
Here is an example:
/// read a packed struct from SII, using station addressing
/// this function sends some stuff over the ethernet port and the
/// resulting responses are parsed and returned as the packed struct type
/// provided.
pub fn readSIIFP_ps(
port: *Port,
comptime T: type,
station_address: u16,
eeprom_address: u16,
retries: u32,
recv_timeout_us: u32,
eeprom_timeout_us: u32,
) !T {
// count how many 4-byte transactions need to be performed
const n_4_bytes = @divExact(@bitSizeOf(T), 32);
// stack allocated buffer to assemble the results of each 4-byte transaction
var bytes: [@divExact(@bitSizeOf(T), 8)]u8 = undefined;
// do the transactions
for (0..n_4_bytes) |i| {
// send and recv some complex stuff over the ethernet port
// resulting in an error or 4 bytes.
const source: [4]u8 = try readSII4ByteFP(
port,
station_address,
eeprom_address + 2 * @as(u16, @intCast(i)), // eeprom address is WORD address
retries,
recv_timeout_us,
eeprom_timeout_us,
);
// assemble however many of these 4 byte sections into memory
@memcpy(bytes[i * 4 .. i * 4 + 4], &source);
}
// interpret the memory correctly based on host endianness
return nic.packFromECat(T, bytes);
}
I realize that I should be able to test this code without an etherenet port. Perhaps my function should accept a std.io.Reader
so I can inject my own 4-byte sequences to test against? But then I need to figure out how to construct one of these famous readers…