tests/testthat/test-npy.R

test_that("a NumPy file written by the package reads back unchanged", {
    m <- matrix(c(TRUE, FALSE, TRUE, TRUE, FALSE, FALSE), 2, 3)
    f <- tempfile(fileext = ".npy")
    volumr:::npy_write_logical(m, f)
    expect_identical(vol_read_npy(f), m)
})

test_that("a file that is not a NumPy array is refused", {
    f <- tempfile(fileext = ".npy")
    writeBin(charToRaw("not a numpy file at all"), f)
    expect_error(vol_read_npy(f), "not a .npy file")
})

npy_raw <- function(descr, shape, bytes) {
    hdr <- sprintf("{'descr': '%s', 'fortran_order': False, 'shape': (%s), }",
                   descr, shape)
    hdr <- paste0(hdr, strrep(" ", 64L - ((10L + nchar(hdr) + 1L) %% 64L)), "\n")
    f <- tempfile(fileext = ".npy")
    con <- file(f, "wb")
    writeBin(c(as.raw(0x93), charToRaw("NUMPY"), as.raw(1L), as.raw(0L)), con)
    writeBin(nchar(hdr), con, size = 2L, endian = "little")
    writeBin(charToRaw(hdr), con)
    writeBin(bytes, con)
    close(con)
    f
}

test_that("unsigned integers read as unsigned", {
    # Regression: u1 bytes 128 and 255 came back as -128 and -1.
    f <- npy_raw("|u1", "4,", as.raw(c(0, 127, 128, 255)))
    expect_identical(vol_read_npy(f), c(0L, 127L, 128L, 255L))
    g <- npy_raw("<u4", "3,", as.raw(c(0, 0, 0, 128,  255, 255, 255, 255,  1, 0, 0, 0)))
    expect_identical(vol_read_npy(g), c(2^31, 2^32 - 1, 1))
})

test_that("a type the reader does not cover is refused", {
    f <- npy_raw("<f2", "2,", as.raw(c(0, 60, 0, 60)))
    expect_error(vol_read_npy(f), "is not read here")
    g <- npy_raw("<c16", "1,", as.raw(integer(16)))
    expect_error(vol_read_npy(g), "is not read here")
})

test_that("the example file written by NumPy reads in C order", {
    a <- vol_read_npy(system.file("extdata", "example.npy", package = "volumr"))
    expect_identical(dim(a), c(3L, 4L))
    expect_identical(a[1, ], c(1.5, -2.25, 3, 1e-5))
    expect_identical(a[2, 4], 1e16)
    expect_true(is.nan(a[3, 1]))
})

Try the volumr package in your browser

Any scripts or data that you put into this service are public.

volumr documentation built on Dec. 2, 2026, 5:07 p.m.