可以 readBin 的 textConnection 等价物
textConnection equivalent that can readBin
我正在为二进制格式解析器编写测试,其 API 接受 Connection 对象。我想把二进制数据的例子直接放到测试用例中,因为这些例子很短而且很多。
如果是文本格式,我会这样写:
test_that("readFoo parses message X", {
data <- readFoo(textConnection("Bar"))
expect_that(data$q, 1)
})
…但是 readFoo
在内部使用 readBin(…, 'raw')
,这需要二进制连接,而 textConnection 则不需要。因此,
test_that("readFoo parses message X", {
data <- readFoo(textConnection('\x01\x7a\x02\x2c\x7d\x0d\x5a\x0b\x0c\x01'))
expect_that(data$q, 1)
})
失败:
Error in readBin(conn, "raw", 10) : can only read from a binary connection
这个可以实现吗?
您可能想通过 rawConnection()
函数使用 a "raw connection",它的行为基本上类似于 textConnection()
。基本包文档中的交叉引用不是很好,所以很容易错过这个。
我正在为二进制格式解析器编写测试,其 API 接受 Connection 对象。我想把二进制数据的例子直接放到测试用例中,因为这些例子很短而且很多。
如果是文本格式,我会这样写:
test_that("readFoo parses message X", {
data <- readFoo(textConnection("Bar"))
expect_that(data$q, 1)
})
…但是 readFoo
在内部使用 readBin(…, 'raw')
,这需要二进制连接,而 textConnection 则不需要。因此,
test_that("readFoo parses message X", {
data <- readFoo(textConnection('\x01\x7a\x02\x2c\x7d\x0d\x5a\x0b\x0c\x01'))
expect_that(data$q, 1)
})
失败:
Error in readBin(conn, "raw", 10) : can only read from a binary connection
这个可以实现吗?
您可能想通过 rawConnection()
函数使用 a "raw connection",它的行为基本上类似于 textConnection()
。基本包文档中的交叉引用不是很好,所以很容易错过这个。