Skip to content

Commit 8866385

Browse files
authored
Preserve empty lines in snapshot output (#1524)
Fixes #1509.
1 parent a8be18e commit 8866385

File tree

4 files changed

+42
-2
lines changed

4 files changed

+42
-2
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# testthat (development version)
22

3+
* `expect_snapshot()` no longer inadvertently trims trailing new lines off
4+
of errors and messages (#1509).
5+
36
* `test_that()` no longer inappropriately skips when calling `expect_equal()`
47
when you've temporarily set the locale to non-UTF-8 (#1285).
58

R/snapshot.R

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,16 +160,18 @@ snapshot_replay.condition <- function(x,
160160
c(snap_header(state, type), snapshot_lines(msg, transform))
161161
}
162162

163-
snapshot_replay_condition_legacy <- function(x, state, transform = NULL) {
163+
snapshot_replay_condition_legacy <- function(x, state = env(), transform = NULL) {
164164
msg <- cnd_message(x)
165+
165166
if (inherits(x, "error")) {
166167
state$error <- x
167168
type <- "Error"
169+
msg <- add_implict_nl(msg)
168170
} else if (inherits(x, "warning")) {
169171
type <- "Warning"
172+
msg <- paste0(msg, "\n")
170173
} else if (inherits(x, "message")) {
171174
type <- "Message"
172-
msg <- sub("\n$", "", msg)
173175
} else {
174176
type <- "Condition"
175177
}
@@ -188,6 +190,14 @@ snapshot_lines <- function(x, transform = NULL) {
188190
x
189191
}
190192

193+
add_implict_nl <- function(x) {
194+
if (substr(x, nchar(x), nchar(x)) == "\n") {
195+
x
196+
} else {
197+
paste0(x, "\n")
198+
}
199+
}
200+
191201
snap_header <- function(state, header) {
192202
if (!identical(state$header, header)) {
193203
state$header <- header

tests/testthat/_snaps/snapshot.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,23 @@
2727
Error <simpleError>
2828
4
2929

30+
# empty lines are preserved
31+
32+
Code
33+
f()
34+
Output
35+
1
36+
37+
Message <simpleMessage>
38+
2
39+
40+
Warning <simpleWarning>
41+
3
42+
43+
Error <simpleError>
44+
4
45+
46+
3047
# multiple outputs of same type are collapsed
3148

3249
Code

tests/testthat/test-snapshot.R

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,16 @@ test_that("can snapshot everything", {
2020
expect_snapshot(f(), error = TRUE)
2121
})
2222

23+
test_that("empty lines are preserved", {
24+
f <- function() {
25+
cat("1\n\n")
26+
message("2\n")
27+
warning("3\n")
28+
stop("4\n\n")
29+
}
30+
expect_snapshot(f(), error = TRUE)
31+
})
32+
2333
test_that("multiple outputs of same type are collapsed", {
2434
expect_snapshot({
2535
x <- 1

0 commit comments

Comments
 (0)