| 1 |
describe("with_connection", { |
| 2 |
it("errors if connection is not named", { |
| 3 |
expect_error({ |
| 4 |
with_connection(list(TRUE), TRUE) |
| 5 |
}, "all(is.named(con)) is not TRUE", fixed = TRUE) |
| 6 |
}) |
| 7 |
|
| 8 |
it("creates a single connection", { |
| 9 |
tmp <- tempfile() |
| 10 |
on.exit(unlink(tmp)) |
| 11 |
expect_false(exists("con")) |
| 12 |
with_connection(list(con = file(tmp, "w")), { |
| 13 |
writeLines(c("foo", "bar"), con) |
| 14 |
}) |
| 15 |
expect_false(exists("con")) |
| 16 |
expect_equal(readLines(tmp), c("foo", "bar")) |
| 17 |
}) |
| 18 |
|
| 19 |
it("creates multiple connections", { |
| 20 |
tmp <- tempfile() |
| 21 |
tmp2 <- tempfile() |
| 22 |
on.exit(unlink(c(tmp, tmp2))) |
| 23 |
expect_false(exists("con")) |
| 24 |
expect_false(exists("con2")) |
| 25 |
with_connection(list(con = file(tmp, "w"), con2 = file(tmp2, "w")), { |
| 26 |
writeLines(c("foo", "bar"), con) |
| 27 |
writeLines(c("baz", "qux"), con2) |
| 28 |
}) |
| 29 |
expect_false(exists("con")) |
| 30 |
expect_false(exists("con2")) |
| 31 |
expect_equal(readLines(tmp), c("foo", "bar")) |
| 32 |
expect_equal(readLines(tmp2), c("baz", "qux")) |
| 33 |
}) |
| 34 |
|
| 35 |
it("works if there is an existing object with the same name", { |
| 36 |
tmp <- tempfile() |
| 37 |
|
| 38 |
con <- "foo" |
| 39 |
with_connection(list(con = file(tmp, "w")), { |
| 40 |
writeLines("foo", con) |
| 41 |
}) |
| 42 |
expect_true(exists("con")) |
| 43 |
expect_equal(readLines(tmp), "foo") |
| 44 |
}) |
| 45 |
|
| 46 |
it("works if there is an existing connection with the same name", { |
| 47 |
tmp <- tempfile() |
| 48 |
tmp2 <- tempfile() |
| 49 |
|
| 50 |
con <- file(tmp, "w") |
| 51 |
writeLines("foo", tmp) |
| 52 |
with_connection(list(con = file(tmp2, "w")), { |
| 53 |
writeLines("bar", con) |
| 54 |
}) |
| 55 |
close(con) |
| 56 |
|
| 57 |
expect_equal(readLines(tmp), "foo") |
| 58 |
expect_equal(readLines(tmp2), "bar") |
| 59 |
}) |
| 60 |
}) |
| 61 |
|
| 62 |
describe("local_connection", { |
| 63 |
it("creates a single connection", { |
| 64 |
tmp <- tempfile() |
| 65 |
on.exit(unlink(tmp)) |
| 66 |
expect_false(exists("con")) |
| 67 |
|
| 68 |
(function() { |
| 69 |
con <- local_connection(file(tmp, "w")) |
| 70 |
writeLines(c("foo", "bar"), con) |
| 71 |
})() |
| 72 |
expect_false(exists("con")) |
| 73 |
expect_equal(readLines(tmp), c("foo", "bar")) |
| 74 |
}) |
| 75 |
}) |