| 1 |
library(testit) |
| 2 |
|
| 3 |
# Generate the exact response body for given request parameters. |
| 4 |
# Used in both the test handler (to produce the response) and the assertions |
| 5 |
# (to compute the expected value), so %==% catches any proxy/routing mismatch. |
| 6 |
make_body = function(path, foo = '', post = '', method = '', x_custom = 'MISSING') { |
| 7 |
paste0( |
| 8 |
'path=', path, '\n', |
| 9 |
'foo=', foo, '\n', |
| 10 |
'post=', post, '\n', |
| 11 |
'method=', method, '\n', |
| 12 |
'x_custom=', x_custom |
| 13 |
) |
| 14 |
} |
| 15 |
|
| 16 |
# Extract the HTTP response body (strip status line + headers). |
| 17 |
# Works on the raw bytes returned by http_request() (handles both \r\n\r\n and \n\n). |
| 18 |
http_body = function(resp) { |
| 19 |
if (is.null(resp)) return(NULL) |
| 20 |
for (sep in c('\r\n\r\n', '\n\n')) { |
| 21 |
m = regexpr(sep, resp, fixed = TRUE) |
| 22 |
if (m[1L] > 0L) return(substring(resp, m[1L] + nchar(sep))) |
| 23 |
} |
| 24 |
resp |
| 25 |
} |
| 26 |
|
| 27 |
# Send a raw HTTP/1.0 request and return the full response as a string. |
| 28 |
# Use non-blocking I/O plus Content-Length checks to avoid partial-response flakes. |
| 29 |
http_request = function(host, port, method, path, body = NULL, extra_headers = '') { |
| 30 |
sock = tryCatch( |
| 31 |
socketConnection(host, port = port, open = 'r+b', blocking = FALSE, timeout = 5), |
| 32 |
error = function(e) NULL |
| 33 |
) |
| 34 |
if (is.null(sock)) return(NULL) |
| 35 |
on.exit(try(close(sock), silent = TRUE), add = TRUE) |
| 36 |
clen = if (is.null(body)) 0L else nchar(body, type = 'bytes') |
| 37 |
req = paste0( |
| 38 |
method, ' ', path, ' HTTP/1.0\r\n', |
| 39 |
'Host: ', host, '\r\n', |
| 40 |
if (clen > 0) paste0('Content-Length: ', clen, '\r\n') else '', |
| 41 |
extra_headers, |
| 42 |
'\r\n', |
| 43 |
if (!is.null(body)) body else '' |
| 44 |
) |
| 45 |
writeBin(req, sock) |
| 46 |
buf = raw(0L) |
| 47 |
# 120 * 0.1s = up to 12 seconds for slow CI environments. |
| 48 |
for (i in seq_len(120L)) { |
| 49 |
Sys.sleep(0.1) |
| 50 |
ready = tryCatch(socketSelect(list(sock), write = FALSE, timeout = 0), error = function(e) FALSE) |
| 51 |
if (!isTRUE(ready[1L])) next |
| 52 |
chunk = tryCatch(readBin(sock, raw(), n = 65536L), error = function(e) NULL) |
| 53 |
if (is.null(chunk)) next |
| 54 |
if (length(chunk) == 0L) break |
| 55 |
buf = c(buf, chunk) |
| 56 |
s = rawToChar(buf) |
| 57 |
sep = regexpr('\r\n\r\n|\n\n', s, perl = TRUE) |
| 58 |
if (sep[1L] < 0L) next |
| 59 |
body_start = sep[1L] + attr(sep, 'match.length') |
| 60 |
cl = regmatches(s, regexpr('(?i)Content-Length: *(\\d+)', s, perl = TRUE)) |
| 61 |
if (length(cl) == 0L || !nzchar(cl)) next |
| 62 |
expected = as.integer(sub('(?i).*Content-Length: *', '', cl, perl = TRUE)) |
| 63 |
if (nchar(s) - body_start + 1L >= expected) break |
| 64 |
} |
| 65 |
if (length(buf) == 0L) NULL else rawToChar(buf) |
| 66 |
} |
| 67 |
|
| 68 |
# Retry a request until a complete response with a non-empty body is received. |
| 69 |
http_request_full = function(host, port, method, path, body = NULL, extra_headers = '', tries = 30L) { |
| 70 |
resp = NULL |
| 71 |
for (i in seq_len(tries)) { |
| 72 |
resp = http_request(host, port, method, path, body, extra_headers) |
| 73 |
has_sep = !is.null(resp) && grepl('\r\n\r\n|\n\n', resp, perl = TRUE) |
| 74 |
b = http_body(resp) |
| 75 |
if (has_sep && !is.null(b) && nzchar(b)) break |
| 76 |
Sys.sleep(0.1) |
| 77 |
} |
| 78 |
resp |
| 79 |
} |
| 80 |
|
| 81 |
url_port = function(url) as.integer(sub('^https?://[^:]+:([0-9]+)/.*$', '\\1', url)) |
| 82 |
|
| 83 |
if ( |
| 84 |
has_fun('serverSocket') && has_fun('socketAccept') && |
| 85 |
!is.null(port <- random_port(error = FALSE)) |
| 86 |
) { |
| 87 |
|
| 88 |
# Run the proxy-backed app in a separate R process so requests are sent from |
| 89 |
# this R session to reduce random timing issues in CI. |
| 90 |
pid_file = tempfile(fileext = '.rds') |
| 91 |
saveRDS(NULL, pid_file) |
| 92 |
Rscript_call(function(make_body, port, pid_file, libs) { |
| 93 |
.libPaths(libs) |
| 94 |
saveRDS(Sys.getpid(), pid_file) |
| 95 |
on.exit(unlink(pid_file), add = TRUE) |
| 96 |
xfun::new_app( |
| 97 |
'', |
| 98 |
function(path, query, post, headers) { |
| 99 |
h = if (length(headers) > 0L) rawToChar(headers) else '' |
| 100 |
foo = if ('foo' %in% names(query)) query[['foo']] else '' |
| 101 |
post_str = if (length(post) > 0L) rawToChar(post) else '' |
| 102 |
method_str = { |
| 103 |
m = regmatches(h, regexpr('Request-Method: [^\r\n]+', h)) |
| 104 |
if (length(m) > 0L) sub('Request-Method: ', '', m) else '' |
| 105 |
} |
| 106 |
x_custom_str = { |
| 107 |
m = regmatches(h, regexpr('X-Custom: [^\r\n]+', h)) |
| 108 |
if (length(m) > 0L) sub('X-Custom: ', '', m) else 'MISSING' |
| 109 |
} |
| 110 |
list(payload = make_body(path, foo, post_str, method_str, x_custom_str), |
| 111 |
'content-type' = 'text/plain') |
| 112 |
}, |
| 113 |
open = NA, |
| 114 |
port = port |
| 115 |
) |
| 116 |
}, list(make_body = make_body, port = port, pid_file = pid_file, libs = .libPaths()), wait = FALSE) |
| 117 |
pid = NULL |
| 118 |
for (i in seq_len(100L)) { |
| 119 |
Sys.sleep(0.1) |
| 120 |
if (!file.exists(pid_file)) break |
| 121 |
pid = tryCatch(readRDS(pid_file), error = function(e) NULL) |
| 122 |
if (length(pid) == 1L) break |
| 123 |
} |
| 124 |
on.exit(if (length(pid) == 1L) try(proc_kill(pid), silent = TRUE), add = TRUE) |
| 125 |
|
| 126 |
# Wait for the background app to become reachable. Require the expected body, |
| 127 |
# not just a 200 status: R's internal httpd serves its "httpd error" page with |
| 128 |
# a 200 status during the brief window before the handler is registered, so a |
| 129 |
# status-only check could lock in that error page as `resp`. |
| 130 |
want = make_body('hello', method = 'GET') |
| 131 |
for (i in seq_len(50L)) { |
| 132 |
resp = http_request_full('127.0.0.1', port, 'GET', '/hello') |
| 133 |
if (!is.null(resp) && grepl('200 OK', resp, fixed = TRUE) && |
| 134 |
identical(http_body(resp), want)) break |
| 135 |
Sys.sleep(0.1) |
| 136 |
} |
| 137 |
|
| 138 |
assert('proxy root app responds to a GET request', { |
| 139 |
(!is.null(resp)) |
| 140 |
(grepl('200 OK', resp, fixed = TRUE)) |
| 141 |
(http_body(resp) %==% make_body('hello', method = 'GET')) |
| 142 |
}) |
| 143 |
|
| 144 |
assert('proxy query parameters are URL-decoded', { |
| 145 |
resp = http_request_full('127.0.0.1', port, 'GET', '/page?foo=bar%20baz') |
| 146 |
(!is.null(resp)) |
| 147 |
(http_body(resp) %==% make_body('page', foo = 'bar baz', method = 'GET')) |
| 148 |
}) |
| 149 |
|
| 150 |
assert('proxy POST body is forwarded correctly', { |
| 151 |
resp = http_request_full('127.0.0.1', port, 'POST', '/submit', body = 'hello=world') |
| 152 |
(!is.null(resp)) |
| 153 |
(http_body(resp) %==% make_body('submit', post = 'hello=world', method = 'POST')) |
| 154 |
}) |
| 155 |
|
| 156 |
assert('proxy request headers reach the handler', { |
| 157 |
resp = http_request_full('127.0.0.1', port, 'GET', '/hdr', |
| 158 |
extra_headers = 'X-Custom: test-value\r\n') |
| 159 |
(!is.null(resp)) |
| 160 |
(http_body(resp) %==% make_body('hdr', method = 'GET', x_custom = 'test-value')) |
| 161 |
}) |
| 162 |
|
| 163 |
assert('.find_proxy_port() excludes ports used by new_app(name = \"\")', { |
| 164 |
old_apps = .proxy$apps |
| 165 |
old_help = .proxy$help |
| 166 |
on.exit({ |
| 167 |
.proxy$apps = old_apps |
| 168 |
.proxy$help = old_help |
| 169 |
}, add = TRUE) |
| 170 |
.proxy$apps[['']] = list(type = 'proxy', port = 4322L, slot = 0L, key = 'xfun:4322') |
| 171 |
p = .find_proxy_port(4322:4325) |
| 172 |
(p != 4322L) |
| 173 |
}) |
| 174 |
|
| 175 |
assert('.find_proxy_port() excludes ports used by help_proxy()', { |
| 176 |
old_apps = .proxy$apps |
| 177 |
old_help = .proxy$help |
| 178 |
on.exit({ |
| 179 |
.proxy$apps = old_apps |
| 180 |
.proxy$help = old_help |
| 181 |
}, add = TRUE) |
| 182 |
.proxy$help[['4323']] = 1L |
| 183 |
p = .find_proxy_port(4323:4326) |
| 184 |
(p != 4323L) |
| 185 |
}) |
| 186 |
|
| 187 |
url = new_app( |
| 188 |
'test', |
| 189 |
function(path, query, post, headers) { |
| 190 |
h = if (length(headers) > 0L) rawToChar(headers) else '' |
| 191 |
foo = if ('foo' %in% names(query)) query[['foo']] else '' |
| 192 |
post_str = if (length(post) > 0L) rawToChar(post) else '' |
| 193 |
method_str = { |
| 194 |
m = regmatches(h, regexpr('Request-Method: [^\r\n]+', h)) |
| 195 |
if (length(m) > 0L) sub('Request-Method: ', '', m) else '' |
| 196 |
} |
| 197 |
list(payload = make_body(path, foo, post_str, method_str), 'content-type' = 'text/plain') |
| 198 |
}, |
| 199 |
open = FALSE |
| 200 |
) |
| 201 |
on.exit(stop_app('test'), add = TRUE) |
| 202 |
|
| 203 |
assert('new_app(name != \"\") uses legacy /custom/name/ path', { |
| 204 |
m = regexec('^http://127\\.0\\.0\\.1:([0-9]+)/custom/test/$', url) |
| 205 |
cap = regmatches(url, m)[[1]] |
| 206 |
(length(cap) == 2L) |
| 207 |
(!is.null(get0('test', .httpd_env(), inherits = FALSE))) |
| 208 |
}) |
| 209 |
|
| 210 |
assert('stop_app() deregisters legacy app handler', { |
| 211 |
stop_app('test') |
| 212 |
(is.null(.proxy$apps[['test']])) |
| 213 |
(is.null(get0('test', .httpd_env(), inherits = FALSE))) |
| 214 |
}) |
| 215 |
|
| 216 |
assert('html_view() uses default name "xfun-html"', { |
| 217 |
html_view('<p>hi</p>', open = FALSE) |
| 218 |
on.exit(stop_app('xfun-html'), add = TRUE) |
| 219 |
(!is.null(.proxy$apps[['xfun-html']])) |
| 220 |
(!is.null(get0('xfun-html', .httpd_env(), inherits = FALSE))) |
| 221 |
}) |
| 222 |
|
| 223 |
assert('html_view() accepts a custom name', { |
| 224 |
html_view('<p>hi</p>', name = 'my-app', open = FALSE) |
| 225 |
on.exit(stop_app('my-app'), add = TRUE) |
| 226 |
(!is.null(.proxy$apps[['my-app']])) |
| 227 |
(!is.null(get0('my-app', .httpd_env(), inherits = FALSE))) |
| 228 |
}) |
| 229 |
|
| 230 |
d = tempfile(); dir.create(d) |
| 231 |
writeLines('hello', file.path(d, 'a.txt')) |
| 232 |
url = serve_dir(d, name = 'serve-dir-test', open = FALSE) |
| 233 |
on.exit({ stop_app('serve-dir-test'); unlink(d, recursive = TRUE) }, add = TRUE) |
| 234 |
|
| 235 |
assert('serve_dir() registers an app and returns its URL', { |
| 236 |
(grepl('/custom/serve-dir-test/$', url)) |
| 237 |
(!is.null(.proxy$apps[['serve-dir-test']])) |
| 238 |
handler = get0('serve-dir-test', .httpd_env(), inherits = FALSE) |
| 239 |
(!is.null(handler)) |
| 240 |
# request for the served file |
| 241 |
r = handler('/custom/serve-dir-test/a.txt') |
| 242 |
(basename(r$file) %==% 'a.txt') |
| 243 |
# request for the directory listing |
| 244 |
r = handler('/custom/serve-dir-test/') |
| 245 |
(r$`content-type` %==% 'text/html') |
| 246 |
(grepl('a.txt', r$payload)) |
| 247 |
}) |
| 248 |
} |