File: test-interp.R

package info (click to toggle)
r-cran-stringr 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,112 kB
  • sloc: javascript: 11; sh: 9; makefile: 2
file content (76 lines) | stat: -rw-r--r-- 2,002 bytes parent folder | download
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
test_that("str_interp works with default env", {
  subject <- "statistics"
  number <- 7
  floating <- 6.656

  expect_equal(
    str_interp("A ${subject}. B $[d]{number}. C $[.2f]{floating}."),
    "A statistics. B 7. C 6.66."
  )

  expect_equal(
    str_interp("Pi is approximately $[.5f]{pi}"),
    "Pi is approximately 3.14159"
  )
})

test_that("str_interp works with lists and data frames.", {
  expect_equal(
    str_interp(
      "One value, ${value1}, and then another, ${value2*2}.",
      list(value1 = 10, value2 = 20)
    ),
    "One value, 10, and then another, 40."
  )

  expect_equal(
    str_interp(
      "Values are $[.2f]{max(Sepal.Width)} and $[.2f]{min(Sepal.Width)}.",
      iris
    ),
    "Values are 4.40 and 2.00."
  )
})

test_that("str_interp works with nested expressions", {
  amount <- 1337

  expect_equal(
    str_interp("Works with } nested { braces too: $[.2f]{{{2 + 2}*{amount}}}"),
    "Works with } nested { braces too: 5348.00"
  )
})

test_that("str_interp works in the absense of placeholders", {
  expect_equal(
    str_interp("A quite static string here."),
    "A quite static string here."
  )
})

test_that("str_interp fails when encountering nested placeholders", {
  msg <- "This will never see the light of day"
  num <- 1.2345

  expect_snapshot(error = TRUE, {
    str_interp("${${msg}}")
    str_interp("$[.2f]{${msg}}")
  })
})

test_that("str_interp fails when input is not a character string", {
  expect_snapshot(str_interp(3L), error = TRUE)
})

test_that("str_interp wraps parsing errors", {
  expect_snapshot(str_interp("This is a ${1 +}"), error = TRUE)
})

test_that("str_interp formats list independetly of other placeholders", {
  a_list <- c("item1", "item2", "item3")
  other <- "1"
  extract <- function(text) regmatches(text, regexpr("xx[^x]+xx", text))
  from_list <- extract(str_interp("list: xx${a_list}xx"))
  from_both <- extract(str_interp("list: xx${a_list}xx, and another ${other}"))
  expect_equal(from_list, from_both)
})