How do I negate testthat::expect_output?

How can I test that the output of a function does not contain a certain string? I have tried to do this with testthat::expect_output(), but to no avail so far. E.g. something like

expect_output(str(iris[c("Species", "Sepal.Length")]), "(?!Petal)", perl = TRUE)

ought to succeed (which it does), whereas something like

expect_output(str(iris[c("Species", "Sepal.Length")]), "(?!Sepal)", perl = TRUE)

ought to fail (which it does not).

Obviously the regex is not correct, yet.

Apparently one should use the Perl-inspired (?s) modifier, which treats a multiple line string like a single line, so that a dot matches all characters, including new lines. See ?regex, in particular the paragraph starting with "Perl-like matching can work in several modes [...]"

library(testthat)
expect_output(str(iris[c("Species", "Sepal.Length")]), "^(?s)(?!.*Petal).*$", perl = TRUE)
expect_output(str(iris[c("Species", "Sepal.Length")]), "^(?s)(?!.*Sepal).*$", perl = TRUE)
#> Error: `str\(iris\[c\("Species", "Sepal\.Length"\)\]\)` does not match "^(?s)(?!.*Sepal).*$".
#> Actual value: "'data\.frame':\\t150 obs\. of  2 variables:\\n \$ Species     : Factor w/ 3 levels "setosa","versicolor",\.\.: 1 1 1 1 1 1 1 1 1 1 \.\.\.\\n \$ Sepal\.Length: num  5\.1 4\.9 4\.7 4\.6 5 5\.4 4\.6 5 4\.4 4\.9 \.\.\."

Kudos to @hwnd over at SO.

1 Like

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.