Skip to content

Commit

Permalink
Improve capture_output() encoding handling (#1693)
Browse files Browse the repository at this point in the history
Fixes #1574
  • Loading branch information
hadley authored Sep 24, 2022
1 parent 38d7eff commit 98fdf1a
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 14 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# testthat (development version)

* Improve way `capture_output()` handles encoding thanks to suggestion from
Kurt Hornik.

* `test_check()` now suppresses hyperlinks since they'll take you to the wrong
places (#1648).

Expand Down
5 changes: 4 additions & 1 deletion R/capture-output.R
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,18 @@ eval_with_output <- function(code, print = FALSE, width = 80) {
if (!is.null(width)) {
local_width(width)
}

result <- withr::with_output_sink(path, withVisible(code))
if (result$visible && print) {
withr::with_output_sink(path, testthat_print(result$value), append = TRUE)
}

# A sink() will always write in the native encoding, so we read with
# base::readLines() then convert to UTF-8
list(
val = result$value,
vis = result$visible,
out = brio::read_lines(path)
out = enc2utf8(base::readLines(path, warn = FALSE))
)
}

Expand Down
20 changes: 20 additions & 0 deletions tests/testthat/test-capture-output.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
test_that("multiplication works", {
utf8 <- "M\u00e4chler"
latin1 <- "M\xe4chler"
Encoding(latin1) <- "latin1"

expect_equal(capture_output_lines(cat(latin1)), utf8)
})

test_that("capture output captures output", {
out1 <- capture_output(print(1:5))
out2 <- capture_output(1:5, print = TRUE)

expect_equal(out1, "[1] 1 2 3 4 5")
expect_equal(out2, "[1] 1 2 3 4 5")
})

test_that("capture output doesn't print invisible things", {
out <- capture_output(invisible(1), print = TRUE)
expect_equal(out, "")
})
13 changes: 0 additions & 13 deletions tests/testthat/test-evaluate-promise.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,3 @@ test_that("capture_messages captures messages", {
})
expect_equal(out, c("a\n", "b\n")) # message adds LF by default
})

test_that("capture output captures output", {
out1 <- capture_output(print(1:5))
out2 <- capture_output(1:5, print = TRUE)

expect_equal(out1, "[1] 1 2 3 4 5")
expect_equal(out2, "[1] 1 2 3 4 5")
})

test_that("capture output doesn't print invisible things", {
out <- capture_output(invisible(1), print = TRUE)
expect_equal(out, "")
})

0 comments on commit 98fdf1a

Please sign in to comment.