Debian Codegraph @

inst/testme/test-isConnectionValid.R

raw
1 library(parallelly)
2
3 message("isConnectionValid() ...")
4
5 ## Test connectionId()
6
7 ## Test with stdin, stdout, stderr
8 stopifnot(connectionId(stdin()) == 0L)
9 stopifnot(connectionId(stdout()) == 1L)
10 stopifnot(connectionId(stderr()) == 2L)
11
12 ## Test with a connection that has no conn_id attribute
13 con_no_id <- file(tempfile(), open = "w+")
14 class(con_no_id) <- c("test_connection", class(con_no_id)) ## Inherit from connection
15 attr(con_no_id, "conn_id") <- NULL ## Ensure no conn_id
16 res <- connectionId(con_no_id)
17 stopifnot(is.na(res))
18 try(close(con_no_id))
19
20 ## Test with a serialized connection (should return -1L)
21 con_ser <- file(tempfile(), open = "w")
22 x_ser <- list(con = con_ser)
23 y_ser <- unserialize(serialize(x_ser, connection = NULL))
24 stopifnot(connectionId(y_ser$con) == -1L)
25 close(con_ser)
26
27 ## Test with a valid file connection
28 con_valid <- file(tempfile(), open = "w+")
29 id_valid <- connectionId(con_valid)
30 stopifnot(is.integer(id_valid), id_valid >= 3L)
31 close(con_valid)
32
33
34 ## Test isConnectionValid()
35
36 ## Test with stdin, stdout, stderr
37 stopifnot(isConnectionValid(stdin()))
38 stopifnot(isConnectionValid(stdout()))
39 stopifnot(isConnectionValid(stderr()))
40
41 ## Test with a serialized connection (should be FALSE)
42 con_ser_valid <- file(tempfile(), open = "w")
43 x_ser_valid <- list(con = con_ser_valid)
44 y_ser_valid <- unserialize(serialize(x_ser_valid, connection = NULL))
45 res_ser_valid <- isConnectionValid(y_ser_valid$con)
46 stopifnot(!res_ser_valid, inherits(attr(res_ser_valid, "reason"), "character"))
47 close(con_ser_valid)
48
49 ## Test with a valid connection
50 con_real_valid <- file(tempfile(), open = "w+")
51 stopifnot(isConnectionValid(con_real_valid))
52 close(con_real_valid)
53
54
55 ## Test with a connection where index is not found in getAllConnections()
56 # 1. Create a connection
57 con_temp_file <- file(tempfile(), open = "w+")
58
59 # 2. Close it, so its index is no longer in getAllConnections()
60 close(con_temp_file)
61
62 # 3. Now `con_temp_file` is a "zombie" object - its index is preserved
63 # but `is.element(as.integer(con_temp_file), getAllConnections())` is FALSE.
64 res_non_existent <- isConnectionValid(con_temp_file)
65 stopifnot(!res_non_existent, inherits(attr(res_non_existent, "reason"), "character"))
66
67
68 message("isConnectionValid() ... done")