Debian Codegraph @

tests/testthat/test-db.R

raw
1 describe("with_db_connection", {
2 skip_if_not_installed("RSQLite")
3 #it("errors if connection is not named", {
4 #expect_error({
5 #with_db_connection(list(TRUE), TRUE)
6 #}, "all(is.named(con)) is not TRUE", fixed = TRUE)
7 #})
8
9 #it("errors if connection is not a DBI connection", {
10 #expect_error({
11 #with_db_connection(list(con = TRUE), TRUE)
12 #}, "all(vlapply(con, methods::is, \"DBIConnection\")) is not TRUE", fixed = TRUE)
13 #})
14
15 it("creates a single connection", {
16 db <- tempfile()
17 on.exit(unlink(db))
18 expect_false(exists("con"))
19 with_db_connection(
20 list(con = DBI::dbConnect(RSQLite::SQLite(), db)), {
21 DBI::dbWriteTable(con, "test", data.frame(a = 1:2, b = 3:4))
22 })
23 expect_false(exists("con"))
24 con2 <- DBI::dbConnect(RSQLite::SQLite(), db)
25 on.exit(DBI::dbDisconnect(con2), add = TRUE)
26 expect_equal(DBI::dbReadTable(con2, "test"), data.frame(a = 1:2, b = 3:4))
27 })
28
29 it("creates multiple connections", {
30 db <- tempfile()
31 db2 <- tempfile()
32 on.exit(unlink(c(db, db2)))
33 expect_false(exists("con"))
34 expect_false(exists("con2"))
35 with_db_connection(
36 list(con = DBI::dbConnect(RSQLite::SQLite(), db),
37 con2 = DBI::dbConnect(RSQLite::SQLite(), db2)), {
38 DBI::dbWriteTable(con, "test", data.frame(a = 1:2, b = 3:4))
39 DBI::dbWriteTable(con2, "test", data.frame(c = 5:6, d = 7:8))
40 })
41 expect_false(exists("con"))
42 expect_false(exists("con2"))
43 con3 <- DBI::dbConnect(RSQLite::SQLite(), db)
44 con4 <- DBI::dbConnect(RSQLite::SQLite(), db2)
45
46 on.exit({
47 DBI::dbDisconnect(con3)
48 DBI::dbDisconnect(con4)
49 }, add = TRUE)
50
51 expect_equal(DBI::dbReadTable(con3, "test"), data.frame(a = 1:2, b = 3:4))
52 expect_equal(DBI::dbReadTable(con4, "test"), data.frame(c = 5:6, d = 7:8))
53 })
54 })
55
56 describe("local_db_connection", {
57 skip_if_not_installed("RSQLite")
58 it("creates a single connection", {
59 db <- tempfile()
60 on.exit(unlink(db))
61 expect_false(exists("con"))
62
63 (function() {
64 con <- local_db_connection(DBI::dbConnect(RSQLite::SQLite(), db))
65 DBI::dbWriteTable(con, "test", data.frame(a = 1:2, b = 3:4))
66 })()
67 expect_false(exists("con"))
68 con2 <- DBI::dbConnect(RSQLite::SQLite(), db)
69 on.exit(DBI::dbDisconnect(con2), add = TRUE)
70 expect_equal(DBI::dbReadTable(con2, "test"), data.frame(a = 1:2, b = 3:4))
71 })
72 })