I'm writing tests for a binary format parser, whose API accepts a Connection object. I'd like to put examples of binary data directly into test cases, as these examples are short and numerous.
If it was a text format, I'd just write:
test_that("readFoo parses message X", {
data <- readFoo(textConnection("Bar"))
expect_that(data$q, 1)
})
…but readFoo
uses readBin(…, 'raw')
internally, and this requires a binary connection, which textConnection is not. Therefore,
test_that("readFoo parses message X", {
data <- readFoo(textConnection('\x01\x7a\x02\x2c\x7d\x0d\x5a\x0b\x0c\x01'))
expect_that(data$q, 1)
})
fails with:
Error in readBin(conn, "raw", 10) : can only read from a binary connection
Is it possible to make this work?
You probably want to use a "raw connection" via the rawConnection()
function, which behaves basically like textConnection()
. The cross-references in the base package documentation aren't great, so it can be easy to miss this one.