Skip to content

Commit

Permalink
Test error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
richfitz committed May 22, 2024
1 parent 5822030 commit afbc083
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
6 changes: 3 additions & 3 deletions inst/include/dust2/r/helpers.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ bool is_integer_like(T x, T eps) {
return std::abs(x - std::round(x)) <= eps;
}

template <typename T>
cpp11::integers as_integers(cpp11::doubles x, const char * name) {
inline cpp11::integers as_integers(cpp11::doubles x, const char * name) {
const auto len = x.size();
cpp11::writable::integers ret(x.size());
for (auto i = 0; i < len; ++i) {
Expand Down Expand Up @@ -156,7 +155,8 @@ inline std::vector<size_t> check_index(cpp11::sexp r_index, size_t max,
return ret;
}
if (TYPEOF(r_index) == REALSXP) {
return check_index(as_integers(r_index), max, name);
cpp11::doubles r_index_real = cpp11::as_cpp<cpp11::doubles>(r_index);
return check_index(as_integers(r_index_real, name), max, name);
}
if (TYPEOF(r_index) != INTSXP) {
cpp11::stop("Expected an integer vector for '%s'", name);
Expand Down
27 changes: 26 additions & 1 deletion tests/testthat/test-walk.R
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,32 @@ test_that("can simulate walk model with index", {
ptr1 <- obj1[[1]]
ptr2 <- obj2[[1]]

res1 <- dust2_cpu_walk_simulate(ptr1, 0:20, c(2L, 4L), TRUE)
res1 <- dust2_cpu_walk_simulate(ptr1, 0:20, c(2, 4), TRUE)
res2 <- dust2_cpu_walk_simulate(ptr2, 0:20, NULL, TRUE)
expect_equal(res1, res2[c(2, 4), , , ])
})


test_that("can validate index values", {
pars <- list(len = 3, sd = 1)
obj <- dust2_cpu_walk_alloc(pars, 0, 1, 10, 0, 42, FALSE)
ptr <- obj[[1]]
expect_error(
dust2_cpu_walk_simulate(ptr, 0:20, c("2", "4"), TRUE),
"Expected an integer vector for 'index'")
expect_error(
dust2_cpu_walk_simulate(ptr, 0:20, c(2, 2.9), TRUE),
"All values of 'index' must be integer-like, but 'index[2]' was not",
fixed = TRUE)
expect_error(
dust2_cpu_walk_simulate(ptr, 0:20, c(2, 20), TRUE),
"All values of 'index' must be in [1, 3], but 'index[2]' was 20",
fixed = TRUE)
expect_error(
dust2_cpu_walk_simulate(ptr, 0:20, c(2, 3, -4), TRUE),
"All values of 'index' must be in [1, 3], but 'index[3]' was -4",
fixed = TRUE)
expect_error(
dust2_cpu_walk_simulate(ptr, 0:20, integer(), TRUE),
"'index' must have nonzero length")
})

0 comments on commit afbc083

Please sign in to comment.