Debian Codegraph @

tests/tests.R

raw
1 # minitest - a minimal testing framework v0.0.5 --------------------------------
2 test_library <- function(package) library(package = package, character.only = TRUE)
3 test_true <- function(x) invisible(isTRUE(x) || {print(x); stop("the above was returned instead of TRUE")})
4 test_false <- function(x) invisible(isFALSE(x) || {print(x); stop("the above was returned instead of FALSE")})
5 test_null <- function(x) invisible(is.null(x) || {print(x); stop("the above was returned instead of NULL")})
6 test_notnull <- function(x) invisible(!is.null(x) || stop("returns NULL when expected to be not NULL"))
7 test_zero <- function(x) invisible(x == 0L || {print(x); stop("the above was returned instead of 0L")})
8 test_type <- function(type, x) invisible(typeof(x) == type || {stop("object of type '", typeof(x), "' was returned instead of '", type, "'")})
9 test_class <- function(class, x) invisible(inherits(x, class) || {stop("object of class '", paste(class(x), collapse = ", "), "' was returned instead of '", class, "'")})
10 test_equal <- function(a, b) invisible(a == b || {print(a); print(b); stop("the above expressions were not equal")})
11 test_identical <- function(a, b) invisible(identical(a, b) || {print(a); print(b); stop("the above expressions were not identical")})
12 test_print <- function(x) invisible(is.character(capture.output(print(x))) || stop("print output of expression cannot be captured as a character value"))
13 test_error <- function(x, containing = "") invisible(inherits(x <- tryCatch(x, error = identity), "error") && grepl(containing, x[["message"]], fixed = TRUE) || stop("Expected error message containing: ", containing, "\nActual error message: ", x[["message"]]))
14 NOT_CRAN <- Sys.getenv("NOT_CRAN") == "true"
15 # ------------------------------------------------------------------------------
16
17 test_library("nanonext")
18 nng_version()
19
20 later <- requireNamespace("later", quietly = TRUE)
21 promises <- requireNamespace("promises", quietly = TRUE)
22
23 test_class("nanoObject", n <- nano("req", listen = "inproc://nanonext", autostart = FALSE))
24 test_class("nanoObject", n1 <- nano("rep", dial = "inproc://nanonext", autostart = FALSE))
25 test_true(is_nano(n))
26 test_class("nanoSocket", n$socket)
27 test_class("nano", n$socket)
28 n$newmethod <- "doesnotwork"
29 test_null(n$newmethod)
30 test_type("integer", attr(n$socket, "id"))
31 test_equal(n$socket$state, "opened")
32 test_equal(n$socket$protocol, "req")
33 test_equal(n$send("not ready", mode = "serial"), 8L)
34 test_equal(n$recv(), 11L)
35 test_class("nano", n$opt("recv-size-max", 8192))
36 test_equal(n$opt("recv-size-max"), 8192L)
37 test_class("nano", n$opt("recv-buffer", 8L))
38 test_error(opt(n$socket, "recv-buffer") <- -1, "Incorrect type")
39 test_class("nano", n$opt("req:resend-time", 0L))
40 test_class("nano", n$opt("socket-name", "nano"))
41 test_equal(n$opt("socket-name"), "nano")
42 test_error(n$opt("socket-name", NULL), "argument")
43 test_print(n$listener[[1]])
44 test_class("nanoListener", n$listener[[1]])
45 test_equal(n$listener[[1]]$url, "inproc://nanonext")
46 test_equal(n$listener[[1]]$state, "not started")
47 test_class("nano", n$listener_opt("recv-size-max", 1024)[[1L]])
48 test_equal(n$listener_opt("recv-size-max")[[1L]], 1024L)
49 test_error(n$listener_opt("false", 100), "supported")
50 test_error(n$listener_opt("false"), "supported")
51 test_error(n$listener_opt("false", "false"), "supported")
52 test_error(n$listener_opt("false", NULL), "supported")
53 test_error(n$listener_opt("false", TRUE), "supported")
54 test_error(n$listener_opt("false", list()), "type")
55 test_zero(n$listener_start())
56 test_equal(n$listener[[1]]$state, "started")
57 test_print(n1$dialer[[1]])
58 test_class("nanoDialer", n1$dialer[[1]])
59 test_equal(n1$dialer[[1]]$url, "inproc://nanonext")
60 test_equal(n1$dialer[[1]]$state, "not started")
61 test_class("nano", n1$dialer_opt("reconnect-time-min", 1000)[[1L]])
62 test_equal(n1$dialer_opt("reconnect-time-min")[[1L]], 1000L)
63 test_class("nano", n1$dialer_opt("recv-size-max", 8192)[[1L]])
64 test_equal(n1$dialer_opt("recv-size-max")[[1L]], 8192L)
65 test_error(n1$dialer_opt("false", 100), "supported")
66 test_error(n1$dialer_opt("false"), "supported")
67 test_error(n1$dialer_opt("false", "false"), "supported")
68 test_error(n1$dialer_opt("false", NULL), "supported")
69 test_error(n1$dialer_opt("false", TRUE), "supported")
70 test_error(n1$dialer_opt("false", list()), "type")
71 test_zero(n1$dialer_start())
72 test_equal(n1$dialer[[1]]$state, "started")
73
74 test_error(n$send(list(), mode = "raw"), "atomic vector type")
75 test_error(n$recv(mode = "none"), "mode")
76 test_error(n$recv(mode = "int"), "mode")
77 test_error(n$recv(mode = "logica"), "mode")
78 test_error(n$recv(mode = "charact"), "mode")
79 test_error(n$recv(mode = "positrons"), "mode")
80 test_true(is_aio(raio <- recv_aio(n$socket, timeout = 1L, cv = substitute())))
81 test_print(raio)
82 test_class("errorValue", call_aio(raio)$data)
83 test_class("errorValue", raio$data)
84 test_zero(pipe_id(raio))
85 r <- n$send(data.frame(), block = FALSE)
86 if (r == 8L) r <- n$send(data.frame(), block = 500L)
87 test_zero(r)
88 r <- n1$recv(block = FALSE)
89 if (is_error_value(r)) r <- n1$recv(block = 500)
90 test_class("data.frame", r)
91 test_zero(n1$send(c("test", "", "spec"), mode = "raw", block = 500))
92 test_identical(n$recv("character", block = 500), c("test", "", "spec"))
93 test_zero(n$send(1:5, mode = "raw"))
94 test_equal(length(n1$recv("integer", block = 500)), 5L)
95 test_true(is_aio(saio <- n1$send_aio(paste(replicate(5, random(1e3L)), collapse = ""), mode = 1L, timeout = 900)))
96 test_print(saio)
97 if (later) test_null(.keep(saio, new.env()))
98 test_class("sendAio", call_aio(saio))
99 test_zero(saio$result)
100 test_error(n$send("wrong mode", mode = "none"), "mode")
101 test_error(n$send("wrong mode", mode = "ser"), "mode")
102 test_error(n$send("wrong mode", mode = "rawial"), "mode")
103 test_class("recvAio", raio <- n$recv_aio(timeout = 500))
104 test_print(raio)
105 test_equal(nchar(call_aio(raio)[["value"]]), 10000L)
106 test_type("integer", pipe_id(raio))
107 raio$newfield <- "doesnotwork"
108 test_null(raio$newfield)
109 test_class("sendAio", saio <- n$send_aio(c(1.1, 2.2), mode = "raw", timeout = 500))
110 saio$newfield <- "doesnotwork"
111 test_null(saio$newfield)
112 test_type("logical", unresolved(saio))
113 test_type("logical", .unresolved(saio))
114 test_class("recvAio", msg <- n1$recv_aio(mode = "numeric", timeout = 500))
115 test_identical(call_aio(msg), msg)
116 test_class("recvAio", msg <- n1$recv_aio(mode = "complex", timeout = 500))
117 test_null(stop_aio(msg))
118 test_null(stop_aio(n))
119 test_false(stop_request(n))
120 test_identical(call_aio(msg), msg)
121 test_class("errorValue", msg$data)
122 test_identical(call_aio(n), n)
123 test_class("sendAio", sraio <- n$send_aio(as.raw(0L), mode = "raw", timeout = 500))
124 test_class("recvAio", rraio <- n1$recv_aio(mode = 1L, timeout = 500))
125 test_true(is_nul_byte(suppressWarnings(call_aio_(rraio)$data)))
126 test_class("sendAio", sraio <- n$send_aio(as.raw(1L), mode = 2L, timeout = 500))
127 test_class("recvAio", rraio <- n1$recv_aio(mode = "raw", timeout = 500))
128 test_type("raw", call_aio(rraio)$data)
129 test_class("sendAio", sraio <- n$send_aio(c(1+2i, 4+3i), mode = "raw", timeout = 500))
130 test_class("recvAio", rraio <- n1$recv_aio(mode = "complex", timeout = 500))
131 test_type("complex", call_aio(rraio)$data)
132 test_class("sendAio", sraio <- n$send_aio(5, mode = "raw", timeout = 500))
133 test_class("recvAio", rraio <- n1$recv_aio(mode = "double", timeout = 500))
134 test_type("double", call_aio(rraio)$data)
135 test_class("sendAio", sraio <- n$send_aio(c(1, 2), mode = "raw", timeout = 500))
136 test_class("recvAio", rraio <- n1$recv_aio(mode = "numeric", timeout = 500))
137 test_true(is.numeric(call_aio(rraio)$data))
138 test_class("sendAio", sraio <- n$send_aio(c(1L, 2L, 3L), mode = "raw", timeout = 500))
139 test_class("recvAio", rraio <- n1$recv_aio(mode = "integer", timeout = 500))
140 test_type("integer", call_aio(rraio)$data)
141 test_class("sendAio", sraio <- n$send_aio(as.raw(0L), mode = "raw", timeout = 500))
142 test_class("recvAio", rraio <- n1$recv_aio(mode = "double", timeout = 500))
143 test_type("raw", suppressWarnings(call_aio(rraio)$data))
144 test_class("sendAio", sraio <- n$send_aio(as.raw(0L), mode = "raw", timeout = 500))
145 test_class("recvAio", rraio <- n1$recv_aio(mode = "integer", timeout = 500))
146 test_type("raw", suppressWarnings(call_aio(rraio)$data))
147 test_class("sendAio", sraio <- n$send_aio(as.raw(0L), mode = "raw", timeout = 500))
148 test_class("recvAio", rraio <- n1$recv_aio(mode = "logical", timeout = 500))
149 test_type("raw", suppressWarnings(collect_aio(rraio)))
150 test_class("sendAio", sraio <- n$send_aio(as.raw(0L), mode = "raw", timeout = 500))
151 test_class("recvAio", rraio <- n1$recv_aio(mode = "numeric", timeout = 500))
152 test_type("raw", suppressWarnings(rraio[]))
153 test_class("sendAio", sraio <- n$send_aio(as.raw(0L), mode = "raw", timeout = 500))
154 test_class("recvAio", rraio <- n1$recv_aio(mode = "complex", timeout = 500))
155 test_type("raw", suppressWarnings(collect_aio_(rraio)))
156 rcv <- cv()
157 test_equal(race_aio(list(rraio), rcv), 1L)
158 test_equal(race_aio(list(sraio, rraio), rcv), 1L)
159 test_equal(race_aio(list(rraio), NULL), 1L)
160 test_equal(race_aio(list(rraio), "invalid"), 1L)
161 rtest <- recv_aio(n1$socket, timeout = 100, cv = rcv)
162 test_equal(race_aio(list(rtest), rcv), 1L)
163 test_error(opt(rraio[["aio"]], "false") <- 0L, "valid")
164 test_error(subscribe(rraio[["aio"]], "false"), "valid")
165 test_error(opt(rraio[["aio"]], "false"), "valid")
166 test_error(stat(rraio[["aio"]], "pipes"), "valid")
167
168 test_zero(n$dial(url = "inproc://two", autostart = FALSE))
169 test_zero(n$dialer_start())
170 test_class("nanoDialer", n$dialer[[1L]])
171 test_type("double", stat(n$dialer[[1L]], "id"))
172 test_zero(n$listen(url = "inproc://three", autostart = FALSE))
173 test_zero(n$listener_start())
174 test_class("nanoListener", n$listener[[2L]])
175 test_type("double", stat(n$listener[[2L]], "id"))
176 test_zero(n$dial(url = "inproc://four"))
177 test_zero(close(n$listener[[1]]))
178 test_equal(suppressWarnings(start(n$listener[[1]])), 12L)
179 test_equal(suppressWarnings(close(n$listener[[1]])), 12L)
180 test_zero(close(n1$dialer[[1]]))
181 test_equal(suppressWarnings(start(n1$dialer[[1]])), 12L)
182 test_equal(suppressWarnings(close(n1$dialer[[1]])), 12L)
183 test_zero(reap(n$listener[[2]]))
184 test_zero(reap(n$dialer[[2]]))
185 test_zero(n$close())
186 test_zero(n1$close())
187 test_equal(suppressWarnings(n1$close()), 7L)
188 test_equal(n$socket[["state"]], "closed")
189 test_equal(n1$socket[state], "closed")
190
191 test_class("conditionVariable", cv <- cv())
192 test_print(cv)
193 test_false(until(cv, 10L))
194 test_false(until(cv, 10))
195 test_false(until_(cv, 10L))
196 test_false(until_(cv, 10))
197 test_false(until_(cv, "test"))
198 test_zero(cv_reset(cv))
199 test_zero(cv_value(cv))
200
201 test_class("nanoObject", req <- nano("req", listen = "inproc://testing"))
202 test_class("nanoSocket", rep <- socket("rep", dial = "inproc://testing", listen = "inproc://testing2"))
203 test_print(rep)
204 test_equal(stat(rep, "dialers"), 1)
205 test_equal(stat(rep, "protocol"), "rep")
206 test_null(stat(rep, "nonexistentstat"))
207 test_class("nano", req$opt("req:resend-time", 1000))
208 test_equal(req$opt("req:resend-time"), 1000L)
209 test_error(req$opt("none"), "supported")
210 test_type("externalptr", req$context_open())
211 test_class("nanoContext", req$context)
212 test_class("nano", req$context)
213 test_type("integer", req$context$id)
214 test_equal(req$context$state, "opened")
215 test_equal(req$context$protocol, "req")
216 test_class("nano", req$opt("send-timeout", 1000))
217 test_equal(req$opt("send-timeout"), 1000L)
218 test_error(req$opt("false", 100), "supported")
219 test_error(req$opt("false"), "supported")
220 test_error(req$opt("false", "false"), "supported")
221 test_error(req$opt("false", NULL), "supported")
222 test_error(req$opt("false", TRUE), "supported")
223 test_error(req$opt("false", list()), "type")
224
225 test_class("nanoContext", ctx <- context(rep))
226 test_print(ctx)
227 test_true(.mark())
228 test_class("sendAio", csaio <- req$send_aio(data.frame(), mode = 1L, timeout = 500))
229 test_zero(call_aio_(csaio)$result)
230 test_class("recvAio", craio <- recv_aio(ctx, mode = 8L, timeout = 500))
231 test_type("raw", res <- collect_aio(craio))
232 test_type("list", unserialize(res[9:length(res)]))
233 test_false(.mark(FALSE))
234 test_zero(req$send("context test", mode ="raw", block = 500))
235 test_equal(recv(ctx, mode = "string", block = 500), "context test")
236 test_type("integer", req$send(data.frame(), mode = "serial", block = 500))
237 test_class("recvAio", msg <- recv_aio(ctx, mode = "serial", timeout = 500))
238 test_type("logical", .unresolved(msg))
239 test_type("logical", unresolved(msg))
240 test_class("data.frame", call_aio(msg)$data)
241 test_false(unresolved(msg))
242 test_zero(req$send(c(TRUE, FALSE, TRUE), mode = 2L, block = 500))
243 test_class("recvAio", msg <- recv_aio(ctx, mode = 6L, timeout = 500))
244 test_type("logical", msg[])
245 test_identical(collect_aio(msg), collect_aio_(msg))
246 test_class("sendAio", err <- send_aio(ctx, msg[["data"]], mode = "serial"))
247 test_null(stop_aio(err))
248 test_class("sendAio", err <- send_aio(ctx, "test"))
249 test_class("errorValue", call_aio(err)$result)
250 test_class("errorValue", call_aio(list(err))[[1L]][["result"]])
251 test_class("errorValue", call_aio_(err)$result)
252 test_class("errorValue", call_aio_(list(item = err))[["item"]][["result"]])
253 test_class("errorValue", collect_aio(err))
254 test_class("errorValue", collect_aio(list(item = err))[["item"]])
255 test_class("errorValue", collect_aio_(list(err))[[1L]])
256 test_zero(req$send(serialize(NULL, NULL, ascii = TRUE), mode = 2L, block = 500))
257 test_null(call_aio(recv_aio(ctx, mode = 1L, timeout = 500))[["value"]])
258 test_class("sendAio", saio <- send_aio(ctx, as.raw(1L), mode = 2L, timeout = 500))
259 test_identical(req$recv(mode = 8L, block = 500), as.raw(1L))
260 test_class("recvAio", rek <- request(req$context, c(1+3i, 4+2i), send_mode = 2L, recv_mode = "complex", timeout = 500))
261 test_zero(reply(ctx, execute = identity, recv_mode = 3L, send_mode = "raw", timeout = 500))
262 test_type("complex", call_aio(rek)[["data"]])
263 test_class("recvAio", rek <- request(req$context, c(1+3i, 4+2i), send_mode = "serial", recv_mode = "serial", timeout = 500))
264 test_zero(reply(ctx, execute = identity, recv_mode = 1L, send_mode = 1L, timeout = 500))
265 test_type("complex", call_aio(rek)[["data"]])
266 test_type("integer", rek[["aio"]])
267
268 test_type("list", cfg <- serial_config(class = c("invalid", "custom"), sfunc = list(identity, function(x) raw(1L)), ufunc = list(identity, as.integer)))
269 opt(req$socket, "serial") <- cfg
270 opt(rep, "serial") <- cfg
271 custom <- list(`class<-`(new.env(), "custom"), new.env())
272 test_zero(send(req$socket, custom, mode = "serial", block = 500))
273 test_type("integer", recv(rep, block = 500)[[1L]])
274 custom <- list(`class<-`(new.env(), "unused"), new.env())
275 test_zero(send(req$socket, custom, mode = "serial", block = 500))
276 test_type("list", recv(rep, block = 500))
277 cfg <- serial_config("custom", function(x) as.raw(length(x)), function(x) lapply(seq_len(as.integer(x)), new.env))
278 test_type("list", cfg)
279 opt(req$socket, "serial") <- cfg
280 opt(rep, "serial") <- cfg
281 test_zero(send(rep, custom, block = 500))
282 test_type("list", recv(req$socket, mode = 1L, block = 500))
283 cfg <- serial_config(c("error_env", "string_class"), list(function(x) stop("serialization failue"), function(x) "serialized string"), list(function(x) stop(), function(x) stop()))
284 opt(req$socket, "serial") <- cfg
285 test_error(send(req$socket, `class<-`(new.env(), "error_env"), block = 500), "serialization failue")
286 test_error(send(req$socket, `class<-`(new.env(), "string_class"), block = 500), "string_class")
287 opt(req$socket, "serial") <- cfg
288 opt(req$socket, "serial") <- list()
289 opt(rep, "serial") <- list()
290 test_error(serial_config(1L, identity, identity), "must be a character vector")
291 test_error(serial_config(c("custom", "custom2"), list(identity), list(identity)), "must all be the same length")
292 test_error(serial_config("custom", "func1", "func2"), "must be a function or list of functions")
293 test_error(serial_config("custom", identity, "func2"), "must be a function or list of functions")
294 test_error(opt(rep, "wrong") <- cfg, "not supported")
295 test_error(opt(rep, "serial") <- pairlist(a = 1L), "not supported")
296
297 test_class("recvAio", cs <- request(req$context, "test", send_mode = "serial", cv = cv, timeout = 500, id = TRUE))
298 test_notnull(cs$data)
299 test_type("externalptr", ctxn <- .context(rep))
300 test_class("recvAio", cr <- recv_aio(ctxn, mode = 8L, cv = cv, timeout = 500))
301 test_type("raw", call_aio(cr)$data)
302 test_type("integer", cr$aio)
303 test_type("integer", send(ctxn, TRUE, mode = 0L, block = FALSE))
304 test_type("externalptr", ctxn <- .context(rep))
305 test_class("recvAio", cs <- request(.context(req$socket), data = TRUE, cv = NA, id = TRUE))
306 test_notnull(cs$data)
307 test_true(recv(ctxn, block = 500))
308 test_zero(send(ctxn, TRUE, mode = 1L, block = 500))
309 test_class("recvAio", cs <- request(.context(req$socket), data = TRUE, timeout = 5, id = TRUE))
310 test_false(stop_request(cs))
311 test_zero(reap(ctxn))
312 test_equal(reap(ctxn), 7L)
313 test_zero(pipe_notify(rep, cv, add = TRUE, flag = TRUE))
314 test_zero(pipe_notify(rep, cv, remove = TRUE, flag = tools::SIGCONT))
315 test_zero(pipe_notify(req$socket, cv = cv, add = TRUE))
316 test_zero(pipe_notify(rep, cv = NULL, add = TRUE, remove = TRUE))
317 test_error(request(err, "test", cv = cv), "valid")
318 test_error(recv_aio(err, cv = cv, timeout = 500))
319 test_error(wait(err), "valid")
320 test_error(wait_(err), "valid")
321 test_error(until(err, 10), "valid")
322 test_error(until_(err, 10), "valid")
323 test_error(cv_value(err), "valid")
324 test_error(cv_reset(err), "valid")
325 test_error(cv_signal(err), "valid")
326 test_error(pipe_notify(err, cv), "valid Socket")
327 test_error(pipe_notify(rep, err), "valid Condition Variable")
328 test_zero(req$context_close())
329 test_null(req$context_close)
330 test_zero(req$close())
331 test_null(req$context)
332 rep$dialer <- NULL
333 test_type("externalptr", rep$dialer[[1L]])
334 test_zero(close(ctx))
335 test_equal(suppressWarnings(close(ctx)), 7L)
336 test_zero(close(rep))
337
338 test_class("nanoObject", pub <- nano("pub", listen = "inproc://ps"))
339 test_class("nanoObject", sub <- nano("sub", dial = "inproc://ps", autostart = NA))
340 test_zero(cv_reset(cv))
341 test_zero(pipe_notify(pub$socket, cv, add = TRUE, remove = TRUE))
342 test_class("nano", sub$opt(name = "sub:prefnew", value = FALSE))
343 test_false(sub$opt(name = "sub:prefnew"))
344 test_error(sub$opt(name = "false", value = 100), "supported")
345 test_error(sub$opt(name = "false"), "supported")
346 test_error(sub$opt(name = "false", value = list()), "type")
347 test_class("nano", sub$subscribe("test"))
348 test_class("nano", subscribe(sub$socket, NULL))
349 test_class("nano", sub$unsubscribe("test"))
350 test_type("externalptr", sub$context_open())
351 test_class("nanoContext", sub$context)
352 test_class("nano", sub$subscribe(12))
353 test_class("nano", sub$unsubscribe(12))
354 test_class("nano", sub$subscribe(NULL))
355 test_zero(sub$context_close())
356 test_null(sub$context)
357 test_zero(sub$close())
358 test_zero(pub$close())
359 test_true(wait(cv))
360 test_type("externalptr", cv2 <- cv())
361 test_type("externalptr", cv3 <- cv())
362 test_type("externalptr", cv %~>% cv2 %~>% cv3)
363 test_zero(cv_signal(cv))
364 test_equal(cv_value(cv), 1L)
365 test_true(wait_(cv3))
366 test_type("externalptr", cv %~>% cv3)
367 test_error("a" %~>% cv3, "valid Condition Variable")
368 test_error(cv3 %~>% "a", "valid Condition Variable")
369
370 test_class("nanoObject", surv <- nano(protocol = "surveyor", listen = "inproc://sock1", dial = "inproc://sock2"))
371 test_print(surv)
372 test_class("nanoObject", resp <- nano(protocol = "respondent", listen = "inproc://sock2", dial = "inproc://sock1"))
373 test_zero(pipe_notify(surv$socket, cv, add = TRUE, remove = TRUE, flag = TRUE))
374 surv$dialer <- NULL
375 test_type("externalptr", surv$dialer[[1L]])
376 test_type("externalptr", surv$listener[[1L]])
377 test_class("nano", surv$survey_time(50))
378 test_zero(surv$send("survey", block = 500))
379 test_class("errorValue", surv$recv(block = 200))
380 test_type("externalptr", surv$context_open())
381 test_type("externalptr", resp$context_open())
382 test_class("nano", surv$survey_time(value = 2000))
383 test_zero(surv$context_close())
384 test_zero(resp$context_close())
385 test_zero(surv$close())
386 test_zero(resp$close())
387 test_false(wait(cv))
388 test_class("errorValue", resp$recv())
389
390 test_class("nanoObject", poly <- nano(protocol = "poly", listen = "inproc://polytest"))
391 test_equal(formals(poly$send)$pipe, 0L)
392 test_equal(formals(poly$send_aio)$pipe, 0L)
393 test_zero(poly$close())
394
395 test_zero(cv_reset(cv))
396 test_class("nanoSocket", poly <- socket(protocol = "poly"))
397 test_class("nanoSocket", poly1 <- socket(protocol = "poly"))
398 test_class("nanoSocket", poly2 <- socket(protocol = "poly"))
399 test_class("nanoMonitor", m <- monitor(poly, cv))
400 test_print(m)
401 test_zero(listen(poly))
402 test_null(read_monitor(m))
403 test_class("sendAio", send_aio(poly, "one", timeout = 50))
404 invisible(gc())
405 test_null(msleep(55))
406 test_zero(dial(poly1))
407 test_zero(dial(poly2))
408 test_true(wait(cv))
409 test_true(wait(cv))
410 test_equal(length(pipes <- read_monitor(m)), 2L)
411 test_zero(send_aio(poly, "one", timeout = 500, pipe = pipes[1L])[])
412 test_zero(send(poly, "two", block = 500, pipe = pipes[2L]))
413 test_type("integer", send(poly, "two", block = FALSE, pipe = pipes[2L]))
414 test_type("character", recv(poly1, block = 500))
415 test_type("character", recv(poly2, block = 500))
416 test_zero(reap(poly2))
417 test_zero(reap(poly1))
418 test_true(wait(cv))
419 test_type("integer", read_monitor(m))
420 test_error(read_monitor(poly), "valid Monitor")
421 test_error(monitor("socket", "cv"), "valid Socket")
422 test_error(monitor(poly, "cv"), "valid Condition Variable")
423 test_zero(reap(poly))
424
425 test_class("nanoSocket", bus <- socket(protocol = "bus"))
426 test_class("nanoSocket", push <- socket(protocol = "push"))
427 test_class("nanoSocket", pull <- socket(protocol = "pull"))
428 test_class("nanoSocket", pair <- socket(protocol = "pair"))
429 test_class("nano", bus)
430 test_error(context(bus), "Not supported")
431 test_error(context(push), "Not supported")
432 test_error(context(pull), "Not supported")
433 test_error(context(pair), "Not supported")
434 test_equal(suppressWarnings(listen(bus, url = "test", fail = "warn")), 3L)
435 test_error(listen(bus, url = "test", fail = "error"), "argument")
436 test_equal(listen(bus, url = "test", fail = "none"), 3L)
437 test_equal(suppressWarnings(dial(bus, url = "test", fail = 1L)), 3L)
438 test_error(dial(bus, url = "test", fail = 2L), "argument")
439 test_equal(dial(bus, url = "test", fail = 3L), 3L)
440 test_error(listen(bus, url = "tls+tcp://localhost/:0", tls = "wrong"), "valid TLS")
441 test_error(dial(bus, url = "tls+tcp://localhost/:0", tls = "wrong"), "valid TLS")
442 test_zero(close(bus))
443 test_equal(suppressWarnings(close(bus)), 7L)
444 test_null(stat(bus, "pipes"))
445 test_zero(close(push))
446 test_zero(close(pull))
447 test_zero(reap(pair))
448
449 test_error(socket(protocol = "newprotocol"), "protocol")
450 test_error(socket(dial = "test"), "argument")
451 test_error(socket(listen = "test"), "argument")
452
453 test_type("list", ncurl("http://www.cam.ac.uk/"))
454 test_type("list", res <- ncurl("http://www.cam.ac.uk/", follow = FALSE, response = TRUE))
455 if (res$status == 301L) test_true(length(res$headers) > 1L)
456 test_type("list", ncurl("http://www.cam.ac.uk/", follow = TRUE))
457 test_type("list", ncurl("https://postman-echo.com/post", convert = FALSE, method = "POST", headers = c(`Content-Type` = "application/octet-stream"), data = as.raw(1L), response = c("Date", "Server"), timeout = 3000))
458 test_class("errorValue", ncurl("http")$data)
459 test_class("recvAio", haio <- ncurl_aio("http://www.cam.ac.uk/", timeout = 3000L))
460 test_true(is_aio(haio))
461 test_type("integer", call_aio(haio)$status)
462 test_class("ncurlAio", haio <- ncurl_aio("https://www.cam.ac.uk/", convert = FALSE, response = "server", timeout = 3000L))
463 test_notnull(haio$status)
464 if (call_aio(haio)$status == 200L) test_notnull(haio$headers)
465 test_class("ncurlAio", put1 <- ncurl_aio("https://postman-echo.com/put", method = "PUT", headers = c(`Content-Type` = "text/plain", Authorization = "Bearer token"), data = "test", response = TRUE, timeout = 3000L))
466 test_print(put1)
467 test_type("integer", call_aio_(put1)$status)
468 if (put1$status == 200L) test_notnull(put1$headers)
469 if (put1$status == 200L) test_notnull(put1$data)
470 test_null(stop_aio(put1))
471 test_false(stop_request(put1))
472 test_class("ncurlAio", haio <- ncurl_aio("https://i.i"))
473 test_class("errorValue", call_aio(haio)$data)
474 test_print(haio$data)
475 test_class("ncurlAio", ncaio <- ncurl_aio("https://nanonext.r-lib.org/reference/figures/logo.png"))
476 if (suppressWarnings(call_aio(ncaio)$status == 200L)) test_type("raw", ncaio$data)
477 test_class("errorValue", ncurl_aio("http")$data)
478 sess <- ncurl_session("https://postman-echo.com/post", method = "POST", headers = c(`Content-Type` = "text/plain"), data = "test", response = c("date", "Server"), timeout = 3000L)
479 test_true(is_ncurl_session(sess) || is_error_value(sess))
480 if (is_ncurl_session(sess)) test_equal(length(transact(sess)), 3L)
481 if (is_ncurl_session(sess)) test_zero(close(sess))
482 if (is_ncurl_session(sess)) test_equal(suppressWarnings(close(sess)), 7L)
483 sess <- ncurl_session("https://postman-echo.com/post", convert = FALSE, method = "POST", headers = c(`Content-Type` = "text/plain"), timeout = 3000)
484 test_true(is_ncurl_session(sess) || is_error_value(sess))
485 if (is_ncurl_session(sess)) test_equal(length(transact(sess)), 3L)
486 if (is_ncurl_session(sess)) test_zero(close(sess))
487 if (is_ncurl_session(sess)) test_equal(transact(sess)$data, 7L)
488 sess_all <- ncurl_session("https://postman-echo.com/get", response = TRUE, timeout = 3000L)
489 test_true(is_ncurl_session(sess_all) || is_error_value(sess_all))
490 if (is_ncurl_session(sess_all)) {
491 trans_all <- transact(sess_all)
492 test_true(length(trans_all$headers) > 0L)
493 test_zero(close(sess_all))
494 }
495 test_class("errorValue", suppressWarnings(ncurl_session("https://i")))
496 test_error(ncurl_aio("https://", tls = "wrong"), "valid TLS")
497 test_error(ncurl("https://www.cam.ac.uk/", tls = "wrong"), "valid TLS")
498 test_type("externalptr", etls <- tls_config())
499 test_error(stream(dial = "wss://127.0.0.1:5555", textframes = TRUE, tls = etls))
500 test_error(stream(dial = "wss://127.0.0.1:5555"))
501 test_error(stream(dial = "errorValue3"), "argument")
502 test_error(stream(dial = "inproc://notsup"), "Not supported")
503 test_error(stream(dial = "wss://127.0.0.1:5555", tls = "wrong"), "valid TLS")
504 test_error(stream(listen = "errorValue3"), "argument")
505 test_error(stream(listen = "inproc://notsup"), "Not supported")
506 test_error(stream(listen = "errorValue3", tls = "wrong"), "valid TLS")
507 test_error(stream(), "specify a URL")
508
509 test_type("character", ver <- nng_version())
510 test_equal(length(ver), 2L)
511 test_equal(nng_error(5L), "5 | Timed out")
512 test_equal(nng_error(8), "8 | Try again")
513 test_true(is_nul_byte(as.raw(0L)))
514 test_false(is_nul_byte(NULL))
515 test_false(is_error_value(1L))
516 test_type("double", mclock())
517 test_null(msleep(1L))
518 test_null(msleep(1))
519 test_null(msleep("a"))
520 test_null(msleep(-1L))
521 test_type("character", urlp <- parse_url("://"))
522 test_equal(length(urlp), 7L)
523 test_true(all(nzchar(parse_url("wss://use:r@[::1]/path?q=1#name"))))
524 test_type("character", random())
525 test_equal(nchar(random(1)), 2L)
526 test_equal(nchar(random(1024)), 2048L)
527 test_equal(length(random(4L, convert = FALSE)), 4L)
528 test_error(random(1025), "between 1 and 1024")
529 test_error(random(0), "between 1 and 1024")
530 test_error(random(-1), "between 1 and 1024")
531 test_error(random("test"), "integer")
532 test_error(parse_url("tcp:/"), "argument")
533 test_equal(parse_url("://missing/scheme")["scheme"], "")
534 test_equal(parse_url("tcp://")["port"], "")
535 for (i in c(100:103, 200:208, 226, 300:308, 400:426, 428:431, 451, 500:511, 600))
536 test_type("character", status_code(i))
537
538 s <- tryCatch(stream(dial = "wss://echo.websocket.org/", textframes = TRUE), error = function(e) NULL)
539 if (is_nano(s)) test_notnull(recv(s, block = 500L))
540 if (is_nano(s)) test_type("character", opt(s, "ws:response-headers"))
541 if (is_nano(s)) test_error(opt(s, "ws:request-headers") <- "test\n", 24)
542 if (is_nano(s)) test_type("integer", send(s, c("message1", "test"), block = 500L))
543 if (is_nano(s)) test_notnull(recv(s, block = FALSE))
544 if (is_nano(s)) test_type("integer", send(s, "message2", block = FALSE))
545 if (is_nano(s)) test_notnull(suppressWarnings(recv(s, mode = 9L, block = 100)))
546 if (is_nano(s)) test_type("integer", send(s, 2L, block = 500))
547 if (is_nano(s)) test_class("recvAio", sr <- recv_aio(s, mode = "integer", timeout = 500L))
548 if (is_nano(s)) test_notnull(suppressWarnings(call_aio(sr)[["data"]]))
549 if (is_nano(s)) test_null(stop_aio(sr))
550 if (is_nano(s)) test_class("sendAio", ss <- send_aio(s, "async", timeout = 500L))
551 if (is_nano(s)) test_type("integer", ss[])
552 if (is_nano(s)) test_null(stop_aio(ss))
553 if (is_nano(s)) test_type("integer", send(s, 12.56, mode = "raw", block = 500L))
554 if (is_nano(s)) test_class("recvAio", sr <- recv_aio(s, mode = "double", timeout = 500L, cv = cv))
555 if (is_nano(s)) test_notnull(suppressWarnings(call_aio_(sr)[["data"]]))
556 if (is_nano(s)) test_true(cv_value(cv) > 0L)
557 if (is_nano(s)) test_type("character", opt(s, "ws:request-headers"))
558 if (is_nano(s)) test_notnull(opt(s, "tcp-nodelay") <- FALSE)
559 if (is_nano(s)) test_error(opt(s, "none"), "supported")
560 if (is_nano(s)) test_error(`opt<-`(s, "none", list()), "supported")
561 if (is_nano(s)) test_print(s)
562 if (is_nano(s)) test_type("integer", close(s))
563
564 test_equal(nanonext:::.DollarNames.ncurlAio(NULL, "sta"), "status")
565 test_equal(nanonext:::.DollarNames.recvAio(NULL, "dat"), "data")
566 test_equal(nanonext:::.DollarNames.sendAio(NULL, "r"), "result")
567 test_zero(length(nanonext:::.DollarNames.nano(NULL)))
568
569 fakesock <- `class<-`(new.env(), "nanoSocket")
570 test_error(dial(fakesock), "valid Socket")
571 test_error(dial(fakesock, autostart = FALSE), "valid Socket")
572 test_error(listen(fakesock), "valid Socket")
573 test_error(listen(fakesock, autostart = FALSE), "valid Socket")
574 test_error(context(fakesock), "valid Socket")
575 test_error(.context(fakesock), "valid Socket")
576 test_error(stat(fakesock, "pipes"), "valid Socket")
577 test_error(close(fakesock), "valid Socket")
578 test_false(.unresolved(fakesock))
579 fakectx <- `class<-`("test", "nanoContext")
580 test_false(unresolved(fakectx))
581 test_false(.unresolved(fakectx))
582 test_error(request(fakectx, data = "test"), "valid Context")
583 test_error(subscribe(fakectx, NULL), "valid")
584 test_error(close(fakectx), "valid Context")
585 test_equal(reap(fakectx), 3L)
586 fakestream <- `class<-`("test", "nanoStream")
587 test_print(fakestream)
588 fakesession <- `class<-`("test", "ncurlSession")
589 test_print(fakesession)
590 test_error(transact(fakesession), "valid")
591 test_error(close(fakesession), "valid")
592 test_error(send(fakestream, "test"), "valid")
593 test_error(send_aio(fakestream, "test"), "valid")
594 test_error(recv(fakestream), "valid")
595 test_error(recv_aio(fakestream), "valid")
596 test_error(opt(fakestream, name = "test") <- "test", "valid")
597 test_error(opt(fakestream, name = "test"), "valid")
598 test_equal(close(fakestream), 7L)
599 fakedial <- `class<-`("test", "nanoDialer")
600 test_error(start(fakedial), "valid Dialer")
601 test_error(close(fakedial), "valid Dialer")
602 fakelist <- `class<-`("test", "nanoListener")
603 test_error(start(fakelist), "valid Listener")
604 test_error(close(fakelist), "valid Listener")
605 unres <- `class<-`(NA, "unresolvedValue")
606 test_false(unresolved(unres))
607 test_print(unres)
608 test_type("logical", unres <- unresolved(list("a", "b")))
609 test_equal(length(unres), 1L)
610 test_type("integer", unres <- .unresolved(list("a", "b")))
611 test_equal(length(unres), 1L)
612 test_zero(race_aio(list(), cv()))
613 test_zero(race_aio("not a list", cv()))
614 test_zero(race_aio(list("a", "b"), cv()))
615 test_identical(call_aio("a"), "a")
616 test_identical(call_aio_("a"), "a")
617 test_error(collect_aio_("a"), "object is not an Aio or list of Aios")
618 test_error(collect_aio_(list("a")), "object is not an Aio or list of Aios")
619 test_error(collect_aio(list(fakesock)), "object is not an Aio or list of Aios")
620 test_null(stop_aio("a"))
621 test_false(stop_request("a"))
622 test_null(stop_aio(list("a")))
623 test_false(stop_request(list("a")))
624 test_null(.keep(NULL, new.env()))
625 test_null(.keep(new.env(), new.env()))
626
627 pem <- "-----BEGIN CERTIFICATE----- -----END CERTIFICATE-----"
628 test_tls <- function(pem) {
629 file <- tempfile()
630 on.exit(unlink(file))
631 cat(pem, file = file)
632 test_error(tls_config(client = file), "Cryptographic error")
633 test_error(tls_config(server = file), "Cryptographic error")
634 }
635 test_true(test_tls(pem = pem))
636 test_error(tls_config(client = c(pem, pem)), "Cryptographic error")
637 test_error(tls_config(server = c(pem, pem)), "Cryptographic error")
638 test_type("list", cert <- write_cert(cn = "127.0.0.1"))
639 test_equal(length(cert), 2L)
640 test_type("character", cert[[1L]])
641 test_identical(names(cert), c("server", "client"))
642 test_type("externalptr", tls <- tls_config(client = cert$client))
643 test_class("tlsConfig", tls)
644 test_print(tls)
645 test_class("errorValue", ncurl("https://www.cam.ac.uk/", tls = tls)$status)
646 test_class("errorValue", call_aio(ncurl_aio("https://www.cam.ac.uk/", tls = tls))$data)
647 test_error(ncurl_session("https://www.cam.ac.uk/", tls = cert$client), "not a valid TLS")
648 sess <- ncurl_session("https://www.cam.ac.uk/", tls = tls)
649 test_true(is_ncurl_session(sess) || is_error_value(sess))
650 if (is_ncurl_session(sess)) test_class("errorValue", transact(sess)[["headers"]])
651 test_type("externalptr", s <- socket(listen = "tls+tcp://127.0.0.1:0", tls = tls_config(server = cert$server)))
652 test_true(parse_url(s$listener[[1]]$url)[["port"]] > 0L)
653 test_type("externalptr", s1 <- socket(dial = s$listener[[1]]$url, tls = tls))
654 test_true(suppressWarnings(dial(s, url = "tls+tcp://.", tls = tls)) > 0)
655 test_true(suppressWarnings(listen(s, url = "tls+tcp://.", tls = tls)) > 0)
656 test_zero(close(s1))
657 test_zero(close(s))
658 test_type("externalptr", s <- socket(listen = "tcp://127.0.0.1:0", autostart = FALSE))
659 test_zero(parse_url(s$listener[[1]]$url)[["port"]])
660 test_zero(start(s$listener[[1]]))
661 test_true(parse_url(s$listener[[1]]$url)[["port"]] > 0L)
662 test_zero(close(s))
663 if (promises) test_class("nano", s <- socket(listen = "inproc://nanonext"))
664 if (promises) test_class("nano", s1 <- socket(dial = "inproc://nanonext"))
665 if (promises) test_class("recvAio", r <- recv_aio(s, timeout = 500L))
666 if (promises) test_true(promises::is.promise(promises::then(r, identity, identity)))
667 if (promises) test_type("integer", send(s1, "promises test\n", block = 500L))
668 if (promises) test_class("recvAio", r2 <- recv_aio(s, timeout = 1L))
669 if (promises) test_true(promises::is.promising(call_aio(r2)))
670 if (promises) test_true(promises::is.promise(promises::then(r2, identity, identity)))
671 if (promises) test_true(promises::is.promising(call_aio(r)))
672 if (promises) test_type("integer", send(s1, "promises test2\n", block = 500L))
673 if (promises) test_true(promises::is.promise(promises::then(call_aio(recv_aio(s, timeout = 500L)), identity, identity)))
674 if (promises) test_true(is_aio(n <- ncurl_aio("https://www.cam.ac.uk/", timeout = 3000L)))
675 if (promises) test_true(promises::is.promise(promises::then(n, identity, identity)))
676 if (promises) test_true(promises::is.promising(call_aio(n)))
677 if (promises) test_true(promises::is.promise(promises::as.promise(call_aio(ncurl_aio("https://www.cam.ac.uk/", timeout = 3000L)))))
678 if (promises) { later::run_now(1L); later::run_now() }
679 if (promises) test_zero(close(s1))
680 if (promises) test_zero(close(s))
681 if (promises) { later::run_now(1L); later::run_now() }
682 test_type("character", ip_addr())
683 test_type("character", names(ip_addr()))
684 test_null(write_stdout(""))
685 test_false(identical(get0(".Random.seed"), {.advance(); .Random.seed}))
686 test_type("integer", .Call(nanonext:::rnng_traverse_precious))
687
688 test_error(.dispatcher("invalid", NULL, NULL, NULL, NULL, NULL, NULL), "valid Socket")
689 test_class("nanoSocket", dsock <- socket("rep"))
690 test_error(.dispatcher(dsock, "invalid", NULL, NULL, NULL, NULL, NULL), "valid Socket")
691 test_class("nanoSocket", dpsock <- socket("poly"))
692 test_error(.dispatcher(dsock, dpsock, "invalid", NULL, NULL, NULL, NULL), "valid Monitor")
693 test_zero(close(dpsock))
694 test_zero(close(dsock))
695
696 if (NOT_CRAN) {
697 if (.Platform$OS.type == "windows") {
698 url_rep <- sprintf("ipc://nanonext-rep-%d", Sys.getpid())
699 url_poly <- sprintf("ipc://nanonext-poly-%d", Sys.getpid())
700 } else {
701 url_rep <- sprintf("ipc://%s", tempfile())
702 url_poly <- sprintf("ipc://%s", tempfile())
703 }
704 dispatcher_code <- sprintf('
705 library(nanonext)
706 cv <- cv()
707 rep_sock <- socket("rep", listen = "%s")
708 poly_sock <- socket("poly", listen = "%s")
709 mon <- monitor(poly_sock, cv)
710 pipe_notify(rep_sock, cv, remove = TRUE, flag = tools::SIGTERM)
711 .dispatcher(rep_sock, poly_sock, mon, raw(10), NULL, new.env(), function(e) integer(7))
712 close(poly_sock)
713 ', url_rep, url_poly)
714 script <- tempfile(fileext = ".R")
715 writeLines(dispatcher_code, script)
716 Rscript <- file.path(R.home("bin"), if (.Platform$OS.type == "windows") "Rscript.exe" else "Rscript")
717 system2(Rscript, script, wait = FALSE, stdout = FALSE, stderr = FALSE)
718 Sys.sleep(0.5)
719 daemon <- socket("poly", dial = url_poly)
720 Sys.sleep(0.3)
721 init_data <- recv(daemon, mode = "raw", block = 2000)
722 test_type("raw", init_data)
723 client <- socket("req", dial = url_rep)
724 Sys.sleep(0.1)
725 send(client, raw(8), mode = "raw", block = 2000)
726 status <- recv(client, mode = "integer", block = 2000)
727 test_equal(length(status), 5L)
728 test_true(status[1L] >= 1L)
729 test_true(status[2L] >= 1L)
730 cancel_msg <- raw(8)
731 cancel_msg[5] <- as.raw(99L)
732 send(client, cancel_msg, mode = "raw", block = 2000)
733 cancel_result <- recv(client, mode = "integer", block = 2000)
734 test_equal(cancel_result, 0L)
735 task_exec <- raw(13)
736 task_exec[1] <- as.raw(0x07)
737 task_exec[5] <- as.raw(60L)
738 send(client, task_exec, mode = "raw", block = 2000)
739 task_exec_recv <- recv(daemon, mode = "raw", block = 2000)
740 test_type("raw", task_exec_recv)
741 cancel_exec <- raw(8)
742 cancel_exec[5] <- as.raw(60L)
743 send(client, cancel_exec, mode = "raw", block = 2000)
744 cancel_exec_res <- recv(client, mode = "integer", block = 2000)
745 test_equal(cancel_exec_res, 1L)
746 cancel_sig <- recv(daemon, mode = "raw", block = 2000)
747 test_equal(length(cancel_sig), 0L)
748 send(daemon, raw(13), mode = "raw", block = 2000)
749 recv(client, mode = "raw", block = 2000)
750 task_busy <- raw(13)
751 task_busy[1] <- as.raw(0x07)
752 task_busy[5] <- as.raw(70L)
753 send(client, task_busy, mode = "raw", block = 2000)
754 task_queued <- raw(13)
755 task_queued[1] <- as.raw(0x07)
756 task_queued[5] <- as.raw(71L)
757 send(client, task_queued, mode = "raw", block = 2000)
758 cancel_inq <- raw(8)
759 cancel_inq[5] <- as.raw(71L)
760 send(client, cancel_inq, mode = "raw", block = 2000)
761 cancel_inq_res <- recv(client, mode = "integer", block = 2000)
762 test_equal(cancel_inq_res, 1L)
763 recv(daemon, mode = "raw", block = 2000)
764 send(daemon, raw(13), mode = "raw", block = 2000)
765 recv(client, mode = "raw", block = 2000)
766 task_q1 <- raw(13)
767 task_q1[1] <- as.raw(0x07)
768 task_q1[5] <- as.raw(72L)
769 send(client, task_q1, mode = "raw", block = 2000)
770 task_q2 <- raw(13)
771 task_q2[1] <- as.raw(0x07)
772 task_q2[5] <- as.raw(73L)
773 send(client, task_q2, mode = "raw", block = 2000)
774 recv(daemon, mode = "raw", block = 2000)
775 send(daemon, raw(13), mode = "raw", block = 2000)
776 recv(client, mode = "raw", block = 2000)
777 q2_recv <- recv(daemon, mode = "raw", block = 2000)
778 test_type("raw", q2_recv)
779 send(daemon, raw(13), mode = "raw", block = 2000)
780 recv(client, mode = "raw", block = 2000)
781 task_msg <- raw(13)
782 task_msg[1] <- as.raw(0x07)
783 task_msg[5] <- as.raw(1L)
784 send(client, task_msg, mode = "raw", block = 2000)
785 task_recv <- recv(daemon, mode = "raw", block = 2000)
786 test_type("raw", task_recv)
787 send(daemon, raw(13), mode = "raw", block = 2000)
788 result <- recv(client, mode = "raw", block = 2000)
789 test_type("raw", result)
790 sync_task <- raw(13)
791 sync_task[1] <- as.raw(0x07)
792 sync_task[4] <- as.raw(0x01)
793 sync_task[5] <- as.raw(80L)
794 send(client, sync_task, mode = "raw", block = 2000)
795 sync_recv <- recv(daemon, mode = "raw", block = 2000)
796 test_type("raw", sync_recv)
797 send(daemon, raw(13), mode = "raw", block = 2000)
798 recv(client, mode = "raw", block = 2000)
799 daemon2 <- socket("poly", dial = url_poly)
800 Sys.sleep(0.3)
801 init_data2 <- recv(daemon2, mode = "raw", block = 2000)
802 test_type("raw", init_data2)
803 next_task <- raw(13)
804 next_task[1] <- as.raw(0x07)
805 next_task[5] <- as.raw(81L)
806 send(client, next_task, mode = "raw", block = 2000)
807 next_recv <- recv(daemon2, mode = "raw", block = 2000)
808 test_type("raw", next_recv)
809 send(daemon2, raw(13), mode = "raw", block = 2000)
810 recv(client, mode = "raw", block = 2000)
811 close(daemon2)
812 Sys.sleep(0.1)
813 post_sync <- raw(13)
814 post_sync[1] <- as.raw(0x07)
815 post_sync[5] <- as.raw(82L)
816 send(client, post_sync, mode = "raw", block = 2000)
817 post_recv <- recv(daemon, mode = "raw", block = 2000)
818 test_type("raw", post_recv)
819 mark_resp <- raw(13)
820 mark_resp[1] <- as.raw(0x07)
821 mark_resp[4] <- as.raw(0x01)
822 send(daemon, mark_resp, mode = "raw", block = 2000)
823 mark_res <- recv(client, mode = "raw", block = 2000)
824 test_type("raw", mark_res)
825 disc_sig <- recv(daemon, mode = "raw", block = 2000)
826 test_equal(length(disc_sig), 0L)
827 close(daemon)
828 daemon3 <- socket("poly", dial = url_poly)
829 Sys.sleep(0.3)
830 recv(daemon3, mode = "raw", block = 2000)
831 reset_task <- raw(13)
832 reset_task[1] <- as.raw(0x07)
833 reset_task[5] <- as.raw(90L)
834 send(client, reset_task, mode = "raw", block = 2000)
835 recv(daemon3, mode = "raw", block = 2000)
836 close(daemon3)
837 Sys.sleep(0.2)
838 reset_result <- recv(client, mode = "raw", block = 2000)
839 test_equal(length(reset_result), 10L)
840 send(client, raw(8), mode = "raw", block = 2000)
841 status_final <- recv(client, mode = "integer", block = 2000)
842 test_equal(status_final[1L], 0L)
843 close(client)
844 Sys.sleep(0.5)
845 unlink(script)
846 }
847
848 if (NOT_CRAN) {
849 cert <- write_cert(cn = "127.0.0.1")
850 certfile <- tempfile()
851 cat(cert$server, file = certfile, sep = "\n")
852 certfile <- gsub("\\", "/", certfile, fixed = TRUE)
853 stream_code <- sprintf('
854 library(nanonext)
855 s <- stream(listen = "tcp://127.0.0.1:25555")
856 msg <- recv(s, mode = "character", block = 2000)
857 send(s, paste0("reply:", msg), block = 2000)
858 msg2 <- recv(s, mode = "character", block = 2000)
859 send(s, paste0("async:", msg2), block = 2000)
860 Sys.sleep(0.1)
861 close(s)
862 tls <- tls_config(server = "%s")
863 s <- stream(listen = "wss://127.0.0.1:25555/secure", tls = tls, textframes = TRUE)
864 Sys.sleep(0.1)
865 close(s)
866 ', certfile)
867 script <- tempfile(fileext = ".R")
868 writeLines(stream_code, script)
869 Rscript <- file.path(R.home("bin"), if (.Platform$OS.type == "windows") "Rscript.exe" else "Rscript")
870 system2(Rscript, script, wait = FALSE, stdout = FALSE, stderr = FALSE)
871 Sys.sleep(0.5)
872 s <- tryCatch(stream(dial = "tcp://127.0.0.1:25555", buffer = 1024L), error = identity)
873 if (is_nano(s)) {
874 test_class("nanoStream", s)
875 test_zero(send(s, "test", block = 2000))
876 test_equal(recv(s, mode = "character"), "reply:test")
877 test_class("sendAio", sa <- send_aio(s, "async_test", timeout = 2000))
878 test_zero(call_aio(sa)$result)
879 test_class("recvAio", ra <- recv_aio(s, mode = "character", timeout = 2000))
880 test_equal(call_aio(ra)$data, "async:async_test")
881 Sys.sleep(0.1)
882 test_zero(close(s))
883 test_equal(close(s), 7L)
884 Sys.sleep(0.3)
885 tls <- tls_config(client = cert$client)
886 s <- tryCatch(stream(dial = "wss://127.0.0.1:25555/secure", tls = tls, textframes = TRUE), error = identity)
887 if (is_nano(s)) {
888 test_class("nanoStream", s)
889 Sys.sleep(0.1)
890 test_zero(close(s))
891 test_equal(close(s), 7L)
892 }
893 }
894 unlink(script)
895 unlink(certfile)
896 }
897
898 test_error(http_server("http://127.0.0.1:29995", tls = "invalid"), "valid TLS")
899 fakeserver <- `class<-`("test", "nanoServer")
900 test_error(close(fakeserver), "valid HTTP Server")
901 test_class("list", suppressWarnings(handler_file("/bad", "/nonexistent/file.txt")))
902 test_error(handler_redirect("/bad", "/good", status = 999L), "301, 302, 303, 307, or 308")
903 fakestream_conn <- `class<-`("test", "nanoStreamConn")
904 test_print(fakestream_conn)
905
906 test_equal(format_sse("Hello"), "data: Hello\n\n")
907 test_equal(format_sse("Hello", event = "msg"), "event: msg\ndata: Hello\n\n")
908 test_equal(format_sse("Hello", id = "1"), "id: 1\ndata: Hello\n\n")
909 test_equal(format_sse("Hello", retry = 1000), "retry: 1000\ndata: Hello\n\n")
910 test_equal(format_sse("Line1\nLine2"), "data: Line1\ndata: Line2\n\n")
911 test_equal(format_sse("test", event = "e", id = "2", retry = 500), "event: e\nid: 2\nretry: 500\ndata: test\n\n")
912
913 if (later && NOT_CRAN) {
914 test_error(http_server("http://127.0.0.1:0", handlers = list(list(type = 99L, path = "/"))), "Invalid argument")
915 received_headers <- NULL
916 test_class("nanoServer", srv <- http_server(
917 url = "http://127.0.0.1:0",
918 handlers = list(
919 handler("/test", function(req) list(status = 200L, body = "OK")),
920 handler("/api/data", function(req) {
921 list(status = 200L, headers = c("Content-Type" = "application/json"), body = '{"value":42}')
922 }),
923 handler("/headers", function(req) {
924 received_headers <<- req$headers
925 list(status = 200L, body = paste(names(req$headers), collapse = ","))
926 }),
927 handler("/echo-body", function(req) {
928 list(status = 200L, body = req$body)
929 }, method = "POST"),
930 handler("/patch", function(req) {
931 list(status = 200L, body = paste0("patched:", rawToChar(req$body)))
932 }, method = "PATCH"),
933 handler("/error", function(req) stop(simpleError(""))),
934 handler("/api", function(req) list(status = 200L, body = paste("path:", req$uri)), prefix = TRUE),
935 handler("/any", function(req) list(status = 200L, body = req$method), method = "*"),
936 handler("/put", function(req) list(status = 200L, body = "PUT OK"), method = "PUT"),
937 handler("/delete", function(req) list(status = 200L, body = "DELETE OK"), method = "DELETE"),
938 handler("/raw", function(req) list(status = 200L, body = charToRaw("raw response"))),
939 handler("/default-status", function(req) list(body = "no status")),
940 handler("/no-body", function(req) list(status = 204L))
941 )
942 ))
943 test_print(srv)
944 test_equal(srv$state, "not started")
945 test_zero(parse_url(srv$url)[["port"]])
946 test_zero(srv$start())
947 test_equal(srv$state, "started")
948 test_true(parse_url(srv$url)[["port"]] > 0L)
949 base_url <- srv$url
950 Sys.sleep(0.1)
951 aio <- ncurl_aio(paste0(base_url, "/test"), timeout = 2000)
952 while (unresolved(aio)) later::run_now(1)
953 test_equal(aio$status, 200L)
954 test_equal(aio$data, "OK")
955 aio <- ncurl_aio(paste0(base_url, "/api/data"), timeout = 2000)
956 while (unresolved(aio)) later::run_now(1)
957 test_equal(aio$status, 200L)
958 test_equal(aio$data, '{"value":42}')
959 aio <- ncurl_aio(
960 paste0(base_url, "/headers"),
961 headers = c("X-Custom-Header" = "test123", "X-Another-Header" = "value456"),
962 timeout = 2000
963 )
964 while (unresolved(aio)) later::run_now(1)
965 test_equal(aio$status, 200L)
966 test_true("X-Custom-Header" %in% names(received_headers))
967 test_true("X-Another-Header" %in% names(received_headers))
968 test_equal(received_headers[["X-Custom-Header"]], "test123")
969 test_equal(received_headers[["X-Another-Header"]], "value456")
970 aio <- ncurl_aio(paste0(base_url, "/error"), timeout = 2000)
971 while (unresolved(aio)) later::run_now(1)
972 test_equal(aio$status, 500L)
973 aio <- ncurl_aio(paste0(base_url, "/api/users/123"), timeout = 2000)
974 while (unresolved(aio)) later::run_now(1)
975 test_equal(aio$status, 200L)
976 test_equal(aio$data, "path: /api/users/123")
977 aio <- ncurl_aio(paste0(base_url, "/any"), timeout = 2000)
978 while (unresolved(aio)) later::run_now(1)
979 test_equal(aio$status, 200L)
980 aio <- ncurl_aio(paste0(base_url, "/any"), method = "POST", timeout = 2000)
981 while (unresolved(aio)) later::run_now(1)
982 test_equal(aio$status, 200L)
983 aio <- ncurl_aio(paste0(base_url, "/put"), method = "PUT", timeout = 2000)
984 while (unresolved(aio)) later::run_now(1)
985 test_equal(aio$status, 200L)
986 test_equal(aio$data, "PUT OK")
987 aio <- ncurl_aio(paste0(base_url, "/delete"), method = "DELETE", timeout = 2000)
988 while (unresolved(aio)) later::run_now(1)
989 test_equal(aio$status, 200L)
990 test_equal(aio$data, "DELETE OK")
991 aio <- ncurl_aio(paste0(base_url, "/raw"), timeout = 2000)
992 while (unresolved(aio)) later::run_now(1)
993 test_equal(aio$status, 200L)
994 test_equal(aio$data, "raw response")
995 aio <- ncurl_aio(paste0(base_url, "/default-status"), timeout = 2000)
996 while (unresolved(aio)) later::run_now(1)
997 test_equal(aio$status, 200L)
998 test_equal(aio$data, "no status")
999 aio <- ncurl_aio(paste0(base_url, "/no-body"), timeout = 2000)
1000 while (unresolved(aio)) later::run_now(1)
1001 test_equal(aio$status, 204L)
1002 aio <- ncurl_aio(paste0(base_url, "/echo-body"), method = "POST",
1003 headers = c("Content-Type" = "text/plain"),
1004 data = "post data", timeout = 2000)
1005 while (unresolved(aio)) later::run_now(1)
1006 test_equal(aio$status, 200L)
1007 aio <- ncurl_aio(paste0(base_url, "/patch"), method = "PATCH",
1008 headers = c("Content-Type" = "text/plain"),
1009 data = "hello", timeout = 2000)
1010 while (unresolved(aio)) later::run_now(1)
1011 test_equal(aio$status, 200L)
1012 aio <- ncurl_aio(paste0(base_url, "/nonexistent"), timeout = 2000)
1013 while (unresolved(aio)) later::run_now(1)
1014 test_equal(aio$status, 404L)
1015 aio <- ncurl_aio(paste0(base_url, "/put"), timeout = 2000)
1016 while (unresolved(aio)) later::run_now(1)
1017 test_equal(aio$status, 405L)
1018 test_zero(srv$close())
1019 }
1020
1021 if (later && NOT_CRAN) {
1022 test_class("nanoServer", srv <- http_server(
1023 url = "http://127.0.0.1:0",
1024 handlers = handler("/single", function(req) list(status = 200L, body = "single handler"))
1025 ))
1026 test_zero(srv$start())
1027 Sys.sleep(0.1)
1028 aio <- ncurl_aio(paste0(srv$url, "/single"), timeout = 2000)
1029 while (unresolved(aio)) later::run_now(1)
1030 test_equal(aio$status, 200L)
1031 test_equal(aio$data, "single handler")
1032 test_zero(srv$close())
1033 }
1034
1035 if (later && NOT_CRAN) {
1036 msgs <- list()
1037 ws_conn <- NULL
1038 ws_req <- NULL
1039 test_class("nanoServer", srv <- http_server(
1040 url = "http://127.0.0.1:0",
1041 handlers = list(
1042 handler("/", function(req) list(status = 200L, body = "index")),
1043 handler_ws(
1044 "/ws",
1045 on_message = function(ws, data) {
1046 msgs <<- c(msgs, list(data))
1047 ws$send(data)
1048 },
1049 on_open = function(ws, req) {
1050 ws_conn <<- ws
1051 ws_req <<- req
1052 msgs <<- c(msgs, list("open"))
1053 },
1054 on_close = function(ws) { msgs <<- c(msgs, list("close")) },
1055 textframes = TRUE
1056 ),
1057 handler_ws("/ws-reject", function(ws, data) ws$send(data), on_open = function(ws, req) ws$close())
1058 )
1059 ))
1060 test_zero(srv$start())
1061 base_url <- srv$url
1062 ws_url <- sub("^http", "ws", base_url)
1063 Sys.sleep(0.1)
1064 aio <- ncurl_aio(paste0(base_url, "/"), timeout = 2000)
1065 while (unresolved(aio)) later::run_now(1)
1066 test_equal(aio$status, 200L)
1067 test_equal(aio$data, "index")
1068 ws <- tryCatch(stream(dial = paste0(ws_url, "/ws"), textframes = TRUE), error = identity)
1069 if (is_nano(ws)) {
1070 while (is.null(ws_conn)) later::run_now(1)
1071 test_class("nanoWsConn", ws_conn)
1072 test_print(ws_conn)
1073 test_type("integer", ws_conn$id)
1074 test_type("closure", ws_conn$send)
1075 test_type("closure", ws_conn$close)
1076 test_null(ws_conn$nonexistent)
1077 test_type("list", ws_req)
1078 test_equal(ws_req$uri, "/ws")
1079 test_type("character", ws_req$headers)
1080 test_false(is.null(names(ws_req$headers)))
1081 test_zero(send(ws, "hello", block = 500))
1082 while (length(msgs) < 2L) later::run_now(1)
1083 reply <- recv(ws, block = 500, mode = "character")
1084 test_equal(reply, "hello")
1085 test_zero(ws_conn$send(charToRaw("raw-from-server")))
1086 raw_reply <- recv(ws, block = 500, mode = "raw")
1087 test_type("raw", raw_reply)
1088 test_error(ws_conn$send(123L), "`data` must be raw or character")
1089 test_error(ws_conn$send(list(a = 1)), "`data` must be raw or character")
1090 test_zero(close(ws))
1091 while (length(msgs) < 3L) later::run_now(1)
1092 test_equal(msgs[[1]], "open")
1093 test_equal(msgs[[2]], "hello")
1094 test_equal(ws_conn$close(), 7L)
1095 test_equal(ws_conn$send("after close"), 7L)
1096 test_equal(ws_conn$send(charToRaw("raw after close")), 7L)
1097 }
1098 ws_reject <- tryCatch(stream(dial = paste0(ws_url, "/ws-reject")), error = identity)
1099 if (is_nano(ws_reject)) {
1100 later::run_now(1)
1101 close(ws_reject)
1102 }
1103 ws_req <- NULL
1104 ws_h <- tryCatch(stream(dial = paste0(ws_url, "/ws"), textframes = TRUE,
1105 headers = c(Authorization = "Bearer testtoken", "X-Custom" = "value1")),
1106 error = identity)
1107 if (is_nano(ws_h)) {
1108 while (is.null(ws_req)) later::run_now(1)
1109 test_equal(ws_req$headers[["Authorization"]], "Bearer testtoken")
1110 test_equal(ws_req$headers[["X-Custom"]], "value1")
1111 n_msgs <- length(msgs)
1112 close(ws_h)
1113 while (length(msgs) == n_msgs) later::run_now(1)
1114 }
1115 test_zero(srv$close())
1116 test_error(http_server(url = "http://127.0.0.1:0", handlers = list(
1117 handler_ws(paste0("/", strrep("x", 8180)), function(ws, data) ws$send(data))
1118 )), "Invalid argument")
1119 }
1120
1121 if (later && NOT_CRAN) {
1122 gc_srv <- http_server(
1123 url = "http://127.0.0.1:0",
1124 handlers = list(
1125 handler("/gc", function(req) list(status = 200L, body = "gc test"))
1126 )
1127 )
1128 test_zero(gc_srv$start())
1129 Sys.sleep(0.1)
1130 rm(gc_srv)
1131 Sys.sleep(0.1)
1132 invisible(gc())
1133 }
1134
1135 if (later && NOT_CRAN) {
1136 wss_cert <- write_cert(cn = "127.0.0.1")
1137 wss_tls_server <- tls_config(server = wss_cert$server)
1138 wss_tls_client <- tls_config(client = wss_cert$client)
1139 wss_msgs <- list()
1140 test_class("nanoServer", wss_srv <- http_server(
1141 url = "https://127.0.0.1:0",
1142 handlers = list(
1143 handler("/secure", function(req) list(status = 200L, body = "secure")),
1144 handler_ws(
1145 "/wss",
1146 on_message = function(ws, data) {
1147 wss_msgs <<- c(wss_msgs, list(data))
1148 ws$send(paste0("wss:", data))
1149 },
1150 on_open = function(ws, req) { wss_msgs <<- c(wss_msgs, list("wss_open")) },
1151 on_close = function(ws) { wss_msgs <<- c(wss_msgs, list("wss_close")) },
1152 textframes = TRUE
1153 )
1154 ),
1155 tls = wss_tls_server
1156 ))
1157 test_zero(wss_srv$start())
1158 wss_base_url <- wss_srv$url
1159 wss_ws_url <- sub("^https", "wss", wss_base_url)
1160 Sys.sleep(1L)
1161 wss_aio <- ncurl_aio(paste0(wss_base_url, "/secure"), tls = wss_tls_client, timeout = 2000)
1162 while (unresolved(wss_aio)) later::run_now(1)
1163 if (wss_aio$status == 200L) test_equal(wss_aio$data, "secure")
1164 wss_client <- tryCatch(stream(dial = paste0(wss_ws_url, "/wss"), tls = wss_tls_client, textframes = TRUE), error = identity)
1165 if (is_nano(wss_client)) {
1166 while (length(wss_msgs) < 1L) later::run_now(1)
1167 test_zero(send(wss_client, "secure_hello", block = 500))
1168 while (length(wss_msgs) < 2L) later::run_now(1)
1169 wss_reply <- recv(wss_client, block = 500, mode = "character")
1170 test_equal(wss_reply, "wss:secure_hello")
1171 test_zero(close(wss_client))
1172 later::run_now(1)
1173 test_equal(wss_msgs[[1]], "wss_open")
1174 test_equal(wss_msgs[[2]], "secure_hello")
1175 }
1176 test_zero(wss_srv$close())
1177 }
1178
1179 # Test multiple WebSocket endpoints and concurrent connections
1180 if (later && NOT_CRAN) {
1181 echo_msgs <- list()
1182 upper_msgs <- list()
1183 conn_ids <- c()
1184 ws_shutdown_closed <- 0L
1185 test_class("nanoServer", multi_ws_srv <- http_server(
1186 url = "http://127.0.0.1:0",
1187 handlers = list(
1188 handler_ws("/echo", function(ws, data) {
1189 echo_msgs <<- c(echo_msgs, list(data))
1190 ws$send(data)
1191 }),
1192 handler_ws("/upper", function(ws, data) {
1193 upper_msgs <<- c(upper_msgs, list(data))
1194 ws$send(toupper(data))
1195 }, on_open = function(ws, req) {
1196 conn_ids <<- c(conn_ids, ws$id)
1197 }, on_close = function(ws) {
1198 ws_shutdown_closed <<- ws_shutdown_closed + 1L
1199 }, textframes = TRUE)
1200 )
1201 ))
1202 test_zero(multi_ws_srv$start())
1203 test_zero(multi_ws_srv$start())
1204 base_url <- multi_ws_srv$url
1205 ws_url <- sub("^http", "ws", base_url)
1206 Sys.sleep(0.1)
1207
1208 ws_echo <- tryCatch(stream(dial = paste0(ws_url, "/echo")), error = identity)
1209 if (is_nano(ws_echo)) {
1210 later::run_now(1)
1211 test_zero(send(ws_echo, charToRaw("binary_test"), block = 500))
1212 while (length(echo_msgs) < 1L) later::run_now(1)
1213 echo_reply <- recv(ws_echo, block = 500, mode = "raw")
1214 test_equal(rawToChar(echo_reply), "binary_test")
1215 test_zero(close(ws_echo))
1216 later::run_now(1)
1217 }
1218
1219 ws_upper1 <- tryCatch(stream(dial = paste0(ws_url, "/upper"), textframes = TRUE), error = identity)
1220 ws_upper2 <- tryCatch(stream(dial = paste0(ws_url, "/upper"), textframes = TRUE), error = identity)
1221 if (is_nano(ws_upper1) && is_nano(ws_upper2)) {
1222 while (length(conn_ids) < 2L) later::run_now(1)
1223 test_equal(length(conn_ids), 2L)
1224 test_true(conn_ids[1] != conn_ids[2])
1225
1226 test_zero(send(ws_upper1, "hello", block = 500))
1227 test_zero(send(ws_upper2, "world", block = 500))
1228 while (length(upper_msgs) < 2L) later::run_now(1)
1229 upper_reply1 <- recv(ws_upper1, block = 500, mode = "character")
1230 upper_reply2 <- recv(ws_upper2, block = 500, mode = "character")
1231 test_equal(upper_reply1, "HELLO")
1232 test_equal(upper_reply2, "WORLD")
1233
1234 test_equal(ws_shutdown_closed, 0L)
1235 test_zero(multi_ws_srv$close())
1236 while (ws_shutdown_closed < 2L) later::run_now(1)
1237 test_equal(ws_shutdown_closed, 2L)
1238
1239 close(ws_upper1)
1240 close(ws_upper2)
1241 } else {
1242 multi_ws_srv$close()
1243 }
1244 test_error(multi_ws_srv$start(), "valid HTTP Server")
1245 }
1246
1247 # Test static handlers, redirects, and prefix parameter
1248 if (later && NOT_CRAN) {
1249 test_class("list", suppressWarnings(handler_directory("/bad", "/nonexistent/directory")))
1250
1251 static_test_dir <- tempfile()
1252 dir.create(static_test_dir)
1253 writeLines("Hello from file", file.path(static_test_dir, "test.txt"))
1254 writeLines("<html><body>Index</body></html>", file.path(static_test_dir, "index.html"))
1255
1256 test_class("nanoServer", static_srv <- http_server(
1257 url = "http://127.0.0.1:0",
1258 handlers = list(
1259 handler_file("/single.txt", file.path(static_test_dir, "test.txt")),
1260 handler_file("/tree-file", file.path(static_test_dir, "test.txt"), prefix = TRUE),
1261 handler_directory("/files", static_test_dir),
1262 handler_inline("/inline", "Inline content", content_type = "text/plain"),
1263 handler_inline("/tree-inline", "tree inline", content_type = "text/plain", prefix = TRUE),
1264 handler_inline("/binary", as.raw(c(0x89, 0x50, 0x4e, 0x47))),
1265 handler_redirect("/r301", "/single.txt", status = 301L),
1266 handler_redirect("/r302", "/single.txt", status = 302L),
1267 handler_redirect("/r303", "/single.txt", status = 303L),
1268 handler_redirect("/r307", "/single.txt", status = 307L),
1269 handler_redirect("/r308", "/single.txt", status = 308L),
1270 handler_redirect("/tree-redir", "/single.txt", status = 302L, prefix = TRUE)
1271 )
1272 ))
1273 test_zero(static_srv$start())
1274 base_url <- static_srv$url
1275 Sys.sleep(0.1)
1276
1277 aio <- ncurl_aio(paste0(base_url, "/single.txt"), timeout = 2000)
1278 while (unresolved(aio)) later::run_now(1)
1279 test_equal(aio$status, 200L)
1280 test_equal(trimws(aio$data), "Hello from file")
1281
1282 aio <- ncurl_aio(paste0(base_url, "/tree-file/extra"), timeout = 2000)
1283 while (unresolved(aio)) later::run_now(1)
1284 test_equal(aio$status, 200L)
1285
1286 aio <- ncurl_aio(paste0(base_url, "/files/test.txt"), timeout = 2000)
1287 while (unresolved(aio)) later::run_now(1)
1288 test_equal(aio$status, 200L)
1289
1290 aio <- ncurl_aio(paste0(base_url, "/inline"), timeout = 2000)
1291 while (unresolved(aio)) later::run_now(1)
1292 test_equal(aio$status, 200L)
1293 test_equal(aio$data, "Inline content")
1294
1295 aio <- ncurl_aio(paste0(base_url, "/tree-inline/extra"), timeout = 2000)
1296 while (unresolved(aio)) later::run_now(1)
1297 test_equal(aio$status, 200L)
1298 test_equal(aio$data, "tree inline")
1299
1300 aio <- ncurl_aio(paste0(base_url, "/binary"), timeout = 2000)
1301 while (unresolved(aio)) later::run_now(1)
1302 test_equal(aio$status, 200L)
1303
1304 for (code in c(301L, 302L, 303L, 307L, 308L)) {
1305 aio <- ncurl_aio(paste0(base_url, "/r", code), timeout = 2000)
1306 while (unresolved(aio)) later::run_now(1)
1307 test_equal(aio$status, code)
1308 }
1309
1310 aio <- ncurl_aio(paste0(base_url, "/tree-redir/extra"), timeout = 2000)
1311 while (unresolved(aio)) later::run_now(1)
1312 test_equal(aio$status, 302L)
1313
1314 test_zero(static_srv$close())
1315 unlink(static_test_dir, recursive = TRUE)
1316 }
1317
1318 if (later && NOT_CRAN) {
1319 stream_conn <- NULL
1320 stream_closed <- FALSE
1321 received_methods <- character()
1322 test_class("nanoServer", stream_srv <- http_server(
1323 url = "http://127.0.0.1:0",
1324 handlers = list(
1325 handler_stream(
1326 "/events",
1327 on_request = function(conn, req) {
1328 stream_conn <<- conn
1329 conn$set_status(200L)
1330 conn$set_header("Content-Type", "text/event-stream")
1331 conn$set_header("Cache-Control", "no-cache")
1332 conn$send(format_sse(data = "connected"))
1333 },
1334 on_close = function(conn) {
1335 stream_closed <<- TRUE
1336 }
1337 ),
1338 handler_stream(
1339 "/stream",
1340 on_request = function(conn, req) {
1341 received_methods <<- c(received_methods, req$method)
1342 conn$set_header("Content-Type", "text/plain")
1343 conn$send(paste0("method:", req$method))
1344 conn$close()
1345 }
1346 ),
1347 handler_stream(
1348 "/prefix-stream",
1349 on_request = function(conn, req) {
1350 conn$set_header("Content-Type", "text/plain")
1351 conn$send(paste0("prefix:", req$uri))
1352 conn$close()
1353 },
1354 prefix = TRUE
1355 )
1356 )
1357 ))
1358 test_zero(stream_srv$start())
1359 base_url <- stream_srv$url
1360 Sys.sleep(0.1)
1361
1362 sse_client <- tryCatch(stream(dial = paste0("tcp://", sub("^http://", "", base_url), "/events")), error = identity)
1363 if (is_nano(sse_client)) {
1364
1365 http_req <- "GET /events HTTP/1.1\r\nHost: 127.0.0.1\r\nAccept: text/event-stream\r\n\r\n"
1366 test_zero(send(sse_client, http_req, block = 500))
1367 while (is.null(stream_conn)) later::run_now(1)
1368
1369 test_class("nanoStreamConn", stream_conn)
1370 test_print(stream_conn)
1371 test_type("integer", stream_conn$id)
1372 test_type("closure", stream_conn$send)
1373 test_type("closure", stream_conn$close)
1374 test_type("closure", stream_conn$set_status)
1375 test_type("closure", stream_conn$set_header)
1376 test_null(stream_conn$nonexistent)
1377
1378 test_error(stream_conn$set_status(201L), "after headers have been sent")
1379 test_error(stream_conn$set_header("X-Test", "value"), "after headers have been sent")
1380
1381 test_zero(stream_conn$send(format_sse(data = "update")))
1382 test_zero(stream_conn$send(charToRaw("raw-chunk")))
1383
1384 test_error(stream_conn$send(123L), "`data` must be raw or character")
1385 test_error(stream_conn$send(list()), "`data` must be raw or character")
1386
1387 test_zero(stream_conn$close())
1388 while (!stream_closed) later::run_now(1)
1389 test_true(stream_closed)
1390
1391 test_error(stream_conn$send("after close"), "valid connection")
1392 test_class("errorValue", stream_conn$close())
1393
1394 close(sse_client)
1395 }
1396
1397 get_aio <- ncurl_aio(paste0(base_url, "/stream"))
1398 while (unresolved(get_aio)) later::run_now(1)
1399 test_equal(call_aio(get_aio)$status, 200L)
1400
1401 post_aio <- ncurl_aio(paste0(base_url, "/stream"), method = "POST", data = "test")
1402 while (unresolved(post_aio)) later::run_now(1)
1403 test_equal(call_aio(post_aio)$status, 200L)
1404
1405 test_true("GET" %in% received_methods)
1406 test_true("POST" %in% received_methods)
1407
1408 prefix_aio <- ncurl_aio(paste0(base_url, "/prefix-stream/sub/path"), timeout = 2000)
1409 while (unresolved(prefix_aio)) later::run_now(1)
1410 test_equal(call_aio(prefix_aio)$status, 200L)
1411
1412 test_zero(stream_srv$close())
1413 }
1414
1415 test_null(.dispatcher_stop("invalid"))
1416 test_null(.dispatcher_wait("invalid", 1L))
1417 test_equal(length(.dispatcher_info("invalid")), 5L)
1418 test_null(.dispatcher_gate("invalid"))
1419 test_null(.dispatcher_try_gate("invalid"))
1420 test_identical(.dispatcher_capacity("invalid"), c(used = NA_real_, peak = NA_real_, capacity = NA_real_))
1421
1422 if (NOT_CRAN) {
1423 if (.Platform$OS.type == "windows") {
1424 disp_poly_url <- sprintf("ipc://nanonext-dpoly-%d", Sys.getpid())
1425 } else {
1426 disp_poly_url <- sprintf("ipc://%s", tempfile())
1427 }
1428 disp_inproc_url <- sprintf("inproc://disp-test-%d", Sys.getpid())
1429 RNGkind("L'Ecuyer-CMRG")
1430 .advance()
1431 stream <- .Random.seed
1432 cvar <- cv()
1433 client <- socket("req", listen = disp_inproc_url)
1434 disp <- .dispatcher_start(disp_poly_url, disp_inproc_url, NULL, NULL, stream, NULL, cvar)
1435 test_type("externalptr", disp)
1436 daemon <- socket("poly", dial = disp_poly_url)
1437 .dispatcher_wait(disp, 1L)
1438 init_data <- recv(daemon, mode = "raw", block = 2000)
1439 test_type("raw", init_data)
1440 info <- .dispatcher_info(disp)
1441 test_equal(length(info), 5L)
1442 test_true(info[1L] >= 1L)
1443 test_true(info[2L] >= 1L)
1444 cap <- .dispatcher_capacity(disp)
1445 test_type("double", cap)
1446 test_identical(names(cap), c("used", "peak", "capacity"))
1447 test_true(is.na(cap[["capacity"]]))
1448 test_true(cap[["used"]] >= 0)
1449 test_true(cap[["peak"]] >= cap[["used"]])
1450 send(client, raw(8), mode = "raw", block = 2000)
1451 status <- recv(client, mode = "integer", block = 2000)
1452 test_equal(length(status), 5L)
1453 task_msg <- raw(13)
1454 task_msg[1] <- as.raw(0x07)
1455 task_msg[5] <- as.raw(1L)
1456 send(client, task_msg, mode = "raw", block = 2000)
1457 task_recv <- recv(daemon, mode = "raw", block = 2000)
1458 test_type("raw", task_recv)
1459 send(daemon, raw(13), mode = "raw", block = 2000)
1460 result <- recv(client, mode = "raw", block = 2000)
1461 test_type("raw", result)
1462 info2 <- .dispatcher_info(disp)
1463 test_true(info2[5L] >= 1L)
1464 ctx <- context(client)
1465 aio <- request(ctx, data = "task", id = disp)
1466 task_recv2 <- recv(daemon, mode = "raw", block = 2000)
1467 test_type("raw", task_recv2)
1468 test_true(stop_request(aio))
1469 cancel_sig <- recv(daemon, mode = "raw", block = 2000)
1470 test_equal(length(cancel_sig), 0L)
1471 close(ctx)
1472 ctx2 <- context(client)
1473 aio2 <- request(ctx2, data = "queued_task", id = disp)
1474 while (.dispatcher_info(disp)[3L] == 0L) msleep(1)
1475 send(daemon, raw(13), mode = "raw", block = 2000)
1476 test_true(stop_request(aio2))
1477 close(ctx2)
1478 test_null(.dispatcher_stop(disp))
1479 test_equal(length(.dispatcher_info(disp)), 5L)
1480 test_null(.dispatcher_stop(disp))
1481 close(daemon)
1482 close(client)
1483 cvar2 <- cv()
1484 client2 <- socket("req", listen = disp_inproc_url)
1485 disp2 <- .dispatcher_start(disp_poly_url, disp_inproc_url, NULL, NULL, stream, 2L, cvar2)
1486 test_type("externalptr", disp2)
1487 test_true(.dispatcher_gate(disp2))
1488 test_true(.dispatcher_try_gate(disp2))
1489 test_equal(.dispatcher_capacity(disp2)[["capacity"]], 2)
1490 test_null(.dispatcher_stop(disp2))
1491 close(client2)
1492 cvar2u <- cv()
1493 client2u <- socket("req", listen = disp_inproc_url)
1494 disp2u <- .dispatcher_start(disp_poly_url, disp_inproc_url, NULL, NULL, stream, NULL, cvar2u)
1495 test_true(.dispatcher_try_gate(disp2u))
1496 test_null(.dispatcher_stop(disp2u))
1497 close(client2u)
1498 disp_tls_cert <- write_cert(cn = "127.0.0.1")
1499 disp_tls <- tls_config(server = disp_tls_cert$server)
1500 disp_inproc_url3 <- sprintf("inproc://disp-test3-%d", Sys.getpid())
1501 cvar3 <- cv()
1502 client3 <- socket("req", listen = disp_inproc_url3)
1503 disp3 <- .dispatcher_start("tls+tcp://127.0.0.1:0", disp_inproc_url3, disp_tls, NULL, stream, NULL, cvar3)
1504 test_type("externalptr", disp3)
1505 disp3_url <- attr(disp3, "url")
1506 test_type("character", disp3_url)
1507 disp_tls_client <- tls_config(client = disp_tls_cert$client)
1508 daemon3 <- socket("poly", dial = disp3_url, tls = disp_tls_client)
1509 .dispatcher_wait(disp3, 1L)
1510 init_data3 <- recv(daemon3, mode = "raw", block = 2000)
1511 test_type("raw", init_data3)
1512 test_true(.dispatcher_info(disp3)[1L] >= 1L)
1513 test_null(.dispatcher_stop(disp3))
1514 close(daemon3)
1515 close(client3)
1516 }
1517
1518 if (!interactive() && NOT_CRAN) {
1519 test_class("conditionVariable", cv <- cv())
1520 f <- file("stdin", open = "r")
1521 test_true(is_nano(reader <- read_stdin()))
1522 test_zero(pipe_notify(reader, cv, remove = TRUE, flag = TRUE))
1523 test_true(is_aio(r <- recv_aio(reader, mode = "raw", cv = cv)))
1524 close(f)
1525 test_false(wait(cv))
1526 test_zero(close(reader))
1527 test_equal(collect_aio(r), 7L)
1528 }
1529
1530 if (Sys.info()[["sysname"]] == "Linux") {
1531 rm(list = ls())
1532 invisible(gc())
1533 .Call(nanonext:::rnng_fini_priors)
1534 Sys.sleep(1L)
1535 .Call(nanonext:::rnng_fini)
1536 invisible()
1537 }