Esplorare le istruzioni expect

Sviluppare pacchetti R

Jasmin Ludolf

Content Developer

Expect più comuni

  • Le istruzioni expect convalidano le funzioni R (unit)

Nel pacchetto testthat:

  • expect_equal(): uguaglianza con piccola tolleranza
  • expect_identical(): uguaglianza esatta

  • expect_output(): confronta il testo dell’output di object

 

  • expect_error(): errore dalla chiamata a object
    • Gli errori fermano l’esecuzione; i warning no
  • expect_warning(): warning dalla chiamata a object
Sviluppare pacchetti R

Dall’esempio al test unitario

#' @examples
#' # Convert 32F to C
#' temp_converter(32, "Fahrenheit", "Celsius")
[1] 0

Nel file tests/testthat/test-temp_converter.R:

library(testthat)
expect_equal(

object = temp_converter(32, "Fahrenheit", "Celsius"),
expected = 0
)
Sviluppare pacchetti R

Identico vs uguale

expect_identical()

expect_identical(sqrt(3) ^ 2, 3)
Error: sqrt(3)^2 (`actual`) non è 
identico a 3 (`expected`).

  `actual`: 2.9999999999999996
`expected`: 3.0000000000000000

expect_equal()

  • Usa expect_equal() per confrontare valori numerici
expect_equal(sqrt(3) ^ 2, 3)
  • expect_equal()
    • Consente piccole differenze
    • Ha un argomento tolerance, il default va bene di solito
Sviluppare pacchetti R

Aspettarsi un output

expect_output(

print("Testing R Packages is fun"),
"funk"
)
Error: `print\("Testing R Packages is 
fun"\)` non corrisponde a "funk".
Valore effettivo: "\[1\] "Testing R 
Packages is fun""

Diagramma dell’output

Sviluppare pacchetti R

Aspettarsi un warning

expect_warning(
  temp_converter(-40, 
                 "Celsius", 
                 "Celsius")
)

Segnale di avviso

Sviluppare pacchetti R

Aspettarsi un errore

expect_error(
  temp_converter(300, 
                 "Kelvin", 
                 "Fahrenheit")
)

Segnale di errore

Sviluppare pacchetti R

Ripasso

  • Ogni expectation testa un aspetto della funzione
  • Insieme, i test devono coprire il 100% degli aspetti
Sviluppare pacchetti R

Ayo berlatih!

Sviluppare pacchetti R

Preparing Video For Download...