File: test-mocking.R

package info (click to toggle)
r-cran-crul 1.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,620 kB
  • sloc: sh: 13; makefile: 2
file content (81 lines) | stat: -rw-r--r-- 1,731 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
context("mocking: mock function")
test_that("crul_opts env", {
  skip_on_cran()

  expect_is(crul_opts, "environment")
  expect_false(crul_opts$mock)
})

test_that("mock function", {
  skip_on_cran()

  expect_is(mock, "function")
  expect_true(mock())
  expect_true(crul_opts$mock)
  expect_false(mock(FALSE))
  expect_false(crul_opts$mock)
})

context("mocking: HttpClient")
test_that("mocking with HttpClient", {
  skip_on_cran()
  skip_if_not_installed("webmockr")

  loadNamespace("webmockr")
  url <- hb()
  st <- webmockr::stub_request("get", file.path(url, "get"))
  #webmockr:::webmockr_stub_registry

  # webmockr IS NOT enabled
  cli <- HttpClient$new(url = url)
  aa <- cli$get("get")

  # webmockr IS enabled
  mock()
  bb <- cli$get("get")

  # content and times differ btw the two
  expect_is(aa, "HttpResponse")
  expect_is(bb, "HttpResponse")

  expect_is(aa$content, "raw")
  expect_equal(length(bb$content), 0)

  expect_is(aa$times, "numeric")
  expect_null(bb$times)

  # clean up
  webmockr::stub_registry_clear()
})

context("mocking: HttpClient when not stubbed yet")
test_that("mocking with HttpClient: ", {
  skip_on_cran()
  skip_if_not_installed("webmockr")

  loadNamespace("webmockr")
  url <- hb()
  st <- webmockr::stub_request("get", file.path(url, "get"))
  #webmockr:::webmockr_stub_registry

  # webmockr IS NOT enabled
  cli <- HttpClient$new(url = url)
  expect_error(
    cli$post("post"),
    "Real HTTP connections are disabled"
  )
  expect_error(
    cli$post("post"),
    "You can stub this request with the following snippet"
  )
  expect_error(
    cli$post("post"),
    "registered request stubs"
  )

  # clean up
  webmockr::stub_registry_clear()
})

# turn mocking off
mock(FALSE)