Debian Codegraph @

inst/testme/test-makeClusterSequential.R

raw
1 message("makeClusterSequential() ...")
2
3 ## Requires R (>= 4.4.0)
4 if (getRversion() < "4.4.0") {
5 message("Skipping because R version is less than 4.4.0")
6 message("makeClusterSequential() ... skipped")
7 } else {
8 library(parallelly)
9 library(parallel)
10
11 cl <- makeClusterSequential()
12 stopifnot(inherits(cl, "sequential_cluster"), length(cl) == 1L)
13
14 ## Test print.sequential_cluster
15 capture.output(print(cl))
16
17 ## Test print.sequential_node
18 capture.output(print(cl[[1]]))
19
20 ## Test basic parLapply functionality
21 y <- parLapply(cl, X = 1:3, fun = sqrt)
22 stopifnot(identical(y, lapply(1:3, sqrt)))
23
24 ## Test clusterEvalQ with side effects
25 abc <- 3.14
26 y <- clusterEvalQ(cl, { abc <- 42; abc })
27 stopifnot(identical(y, list(42)), abc == 3.14)
28
29 ## Export a variable to the cluster nodes
30 def <- 42
31 y <- clusterExport(cl, "def")
32 rm(def)
33 stopifnot(!exists("def"))
34 y <- clusterEvalQ(cl, { def })
35 stopifnot(identical(y, list(42)))
36
37 ## Test with run-time errors
38 y <- tryCatch(parLapply(cl, X = 1, fun = stop), error = identity)
39 stopifnot(inherits(y, "error"))
40
41 ## Test stopping the cluster
42 stopCluster(cl)
43
44 ## Test accessing an invalid node (after stopCluster)
45 res <- tryCatch({
46 parallel::sendData(cl[[1]], list(type = "EXEC", data = list(fun = identity, args = list(1))))
47 }, error = function(e) e)
48 stopifnot(inherits(res, "simpleError"), grepl("node is no longer valid", res$message))
49
50
51 ## Re-create cluster for other tests
52 cl <- makeClusterSequential()
53 node <- cl[[1]]
54
55 ## Test sendData with "DONE" type
56 parallel::sendData(node, list(type = "DONE"))
57 stopifnot(!isTRUE(node$envir[["...parallelly.valid..."]]))
58
59 ## Test sendData with unknown type
60 ## Test sendData with unknown type
61 ## Re-create cluster for this test, as the previous one was invalidated
62 cl_unknown <- makeClusterSequential()
63 node_unknown <- cl_unknown[[1]]
64
65 res <- tryCatch({
66 parallel::sendData(node_unknown, list(type = "UNKNOWN"))
67 }, error = function(e) e)
68 message("Error message for UNKNOWN type: ", res$message)
69 stopifnot(inherits(res, "simpleError"), grepl("type = ['‘]UNKNOWN['’] not yet implemented", res$message))
70
71 ## Test recvData internal error
72 ## Re-create cluster for this test
73 cl_internal_error <- makeClusterSequential()
74 node_internal_error <- cl_internal_error[[1]]
75
76 ## Manipulate internal state to trigger error
77 node_internal_error$envir[["value"]] <- list(type = "BAD_TYPE")
78
79 res <- tryCatch({
80 parallel::recvData(node_internal_error)
81 }, error = function(e) e)
82 stopifnot(inherits(res, "simpleError"), grepl("INTERNAL ERROR", res$message))
83
84 message("makeClusterSequential() ... done")
85 }