markvanderloo / tinytest

A lightweight, no-dependency, but full-featured package for unit testing in R
GNU General Public License v3.0
223 stars 20 forks source link

`expect_message()` pattern matching #96

Closed DavidJesse21 closed 2 years ago

DavidJesse21 commented 2 years ago

Hi,

I think other users have opened similar issues before (e.g. here) but this has not helped me and I am somewhat confused by the behaviour of the expect_message function from this package when the pattern argument is used.

Here is an example:

# fails
tinytest::expect_message(
  message(
    sprintf("R6 class file `%s.R` already exists", "MyClass")
  ),
  pattern = "already exists$"
)

This test fails, it also does not matter if I set fixed to true or false.

However, using base R's grepl function this causes no issue:

# returns TRUE
grepl("already exists$", sprintf("R6 class file `%s.R` already exists", "MyClass"))

Is there something I have missed about using expect_message() correctly or is this a bug?

Thank you

markvanderloo commented 2 years ago

confirmed. That should not happen

markvanderloo commented 2 years ago

I was wrong. This should happen. It's because a message gets a free LF character from R (from ?message):

Unlike warnings and errors, a final newline is regarded as part of the message, and is optional.

A bit cryptic. There is an option to avoid adding the LF, see the example below. Or, you could explicitly add the LF character to your regex. I will document this in tinytest.

> tinytest::expect_message(
+   message(
+     sprintf("R6 class file `%s.R` already exists", "MyClass"), appendLF=FALSE
+   ),
+   pattern = "already exists$"
+ )
----- PASSED      : <-->
 call| tinytest::expect_message(message(sprintf("R6 class file `%s.R` already exists", 
 call| "MyClass"), appendLF = FALSE), pattern = "already exists$")