Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kalinowski committed May 28, 2024
1 parent fe8a702 commit 9133b29
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions tests/testthat/test-python-numpy.R
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,43 @@ test_that("numpy string arrays are correctly handled", {
"17", "18"), byrow = TRUE, ncol = 2))

})


test_that("numpy non-simple arrays work", {
# https://github.com/rstudio/reticulate/issues/1613
py_run_string("import numpy as np", convert = FALSE)
py_run_string(
"array = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)])",
convert = FALSE
)
result <- py_run_string("rec_array = array.view(np.recarray)", convert = FALSE)

# Test that attempting to convert a non-simple array fails gracefully,
# returns a PyObjectRef.
rec_array <- py_to_r(result$rec_array)
expect_equal(class(rec_array),
c("numpy.recarray", "numpy.ndarray", "python.builtin.object"))

# Test that a registered S3 method for the non-simple numpy array will be
# called. (Note, some packages, like {zellkonverter}, will register this
# directly for numpy.ndarray)
registerS3method("py_to_r", "numpy.recarray", function(x) {
tryCatch({
pandas <- import("pandas", convert = FALSE)
x <- pandas$DataFrame(x)$to_numpy()
x <- py_to_r(x)
return(x)
}, error = identity)
NextMethod()
})

on.exit({
rm(list = "py_to_r.numpy.recarray",
envir = environment(py_to_r)$.__S3MethodsTable__.)
})

arr <- py_to_r(result$rec_array)
expect_identical(arr, rbind(c(1, 2),
c(3, 4)))

})

0 comments on commit 9133b29

Please sign in to comment.