1context("Non-blocking opening connection")
2
3read_text <- function(x){
4  while (isIncomplete(x)) {
5    Sys.sleep(0.1)
6    txt <- readLines(x)
7    if(length(txt))
8      return(txt)
9  }
10}
11
12read_bin <- function(x){
13  while (isIncomplete(x)) {
14    Sys.sleep(0.1)
15    bin <- readBin(x, raw(), 100)
16    if(length(bin))
17      return(bin)
18  }
19}
20
21expect_immediate <- function(...){
22  expect_true(system.time(...)['elapsed'] < 0.5)
23}
24
25test_that("Non-blocking open does not block", {
26
27  # Get a regular string
28  con <- curl(httpbin("delay/1"))
29  expect_immediate(open(con, "rs", blocking = FALSE))
30  expect_immediate(readLines(con))
31  close(con)
32})
33
34test_that("Error handling for non-blocking open", {
35
36  # Get a regular string
37  con <- curl(httpbin("get"))
38  expect_immediate(open(con, "rs", blocking = FALSE))
39  expect_is(read_text(con), "character")
40  close(con)
41
42  # Test error during read text
43  h <- new_handle()
44  con <- curl(httpbin("status/418"), handle = h)
45  expect_immediate(open(con, "rs", blocking = FALSE))
46  expect_is(read_text(con), "character")
47  expect_equal(handle_data(h)$status_code, 418)
48  close(con)
49
50  # Test error during read binary
51  h <- new_handle()
52  con <- curl(httpbin("status/418"), handle = h)
53  expect_immediate(open(con, "rbs", blocking = FALSE))
54  expect_is(read_bin(con), "raw")
55  expect_equal(handle_data(h)$status_code, 418)
56  close(con)
57
58  # DNS error
59  con <- curl("http://this.is.invalid.co.za")
60  expect_immediate(open(con, "rs", blocking = FALSE))
61  expect_error(read_text(con), "resolv", ignore.case = TRUE) # matches "resolve" or "resolving"
62  close(con)
63
64  # Non existing host
65  con <- curl("http://240.0.0.1")
66  expect_immediate(open(con, "rs", blocking = FALSE))
67  expect_error(read_text(con))
68  close(con)
69
70  # Invalid port
71  con <- curl("http://8.8.8.8:666")
72  expect_immediate(open(con, "rs", blocking = FALSE))
73  expect_error(read_text(con))
74  close(con)
75})
76