Skip to content

Commit e56d390

Browse files
committed
Fix NA comparison bug in compare.character
1 parent 4f22448 commit e56d390

3 files changed

Lines changed: 16 additions & 3 deletions

File tree

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* Better default environment for `test_check()` and `test_package()` which
44
allows S4 class creation in tests
55

6+
* `compare.character()` no longer fails when one value is missing.
67

78
# testthat 0.8
89

R/compare.r

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ compare.character <- function(x, y, ..., max_strings = 5, max_lines = 5,
3131
# If they're not the same length, fallback to default method
3232
if (length(x) != length(y)) return(NextMethod())
3333

34-
diff <- x != y
34+
# If vectorwise-equal, fallback to default method
35+
diff <- xor(is.na(x), is.na(y)) || x != y
36+
diff[is.na(diff)] <- FALSE
3537

3638
if (!any(diff)) {
3739
return(NextMethod())
@@ -40,7 +42,7 @@ compare.character <- function(x, y, ..., max_strings = 5, max_lines = 5,
4042
width <- width - 6 # allocate space for labels
4143
n_show <- seq_len(min(length(diff), max_strings))
4244
show <- diff[n_show]
43-
45+
4446
encode <- function(x) encodeString(x, quote = '"')
4547
show_x <- str_chunk(str_trunc(encode(x[show]), max_lines * width), width)
4648
show_y <- str_chunk(str_trunc(encode(y[show]), max_lines * width), width)

tests/testthat/test-compare.r

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
context("Compare")
22

33
test_that("Equal strings with different attributes are not equal", {
4-
54
expect_false(compare(structure("text", y = "foo"), "text")$equal)
5+
})
6+
7+
test_that("different types of missing values are not equal", {
8+
expect_false(compare(NA, NA_character_)$equal)
9+
})
10+
11+
test_that("equal if both missing or both the same", {
12+
expect_true(compare(NA_character_, NA_character_)$equal)
13+
expect_true(compare("ABC", "ABC")$equal)
614

15+
expect_false(compare("ABC", NA_character_)$equal)
16+
expect_false(compare(NA_character_, "ABC")$equal)
717
})

0 commit comments

Comments
 (0)