Testthat: os testes são executados na sessão R, mas a "verificação R CMD" falha

Criado em 18 jul. 2013  ·  11Comentários  ·  Fonte: r-lib/testthat

os testes de um pacote (veja abaixo) falham quando executados por "verificação R CMD", mas se eu executá-los em uma sessão R, está tudo bem. o pacote testado cria alguns arquivos em um tempdir e quero verificar sua existência.

eu notei erros como
"Erro no arquivo (nome do arquivo, \" r \ ", codificação = codificação): não é possível abrir a conexão
Chamadas: local ... eval.parent -> eval -> eval -> eval -> eval -> fonte -> arquivo
Além disso: mensagem de aviso:
No arquivo (nome do arquivo, \ "r \", encoding = encoding): não é possível abrir o arquivo 'startup.Rs': Não existe esse arquivo ou diretório "

minhas funções de pacote usam algumas chamadas setwd (). quando eu crio um arquivo "startup.Rs" fictício no diretório para onde as funções saltam, esses erros desaparecem. Não tenho ideia do que esse arquivo deve fazer ou por que ele só está faltando quando a "verificação R CMD" está executando os testes. de qualquer maneira, os testes ainda falham, afinal.

além disso, testthat não carregou todas as dependências, adicionei manualmente uma chamada require () ao conjunto de testes. aqui está o pacote, se você quiser tentar replicar o problema: http://reaktanz.de/stuff/R/roxyPackage_0.03-11.tar.gz

Comentários muito úteis

Encontrou uma solução alternativa

Este problema está relacionado a estes outros: https://github.com/hadley/testthat/issues/144 e https://github.com/zoonproject/zoon/pull/150.

Uma solução alternativa está aqui: https://github.com/luckyrandom/cmaker/commit/b85813ac2b7aef69932eca8fbb4fa0ec225e0af0

Basta adicionar Sys.setenv("R_TESTS" = "") como a primeira linha em tests/testthat.R

Todos 11 comentários

Hmmm, chamadas para setwd() geralmente são uma má ideia. Os testes provavelmente estão sendo executados em um ambiente diferente do que você espera - só consegui depurar problemas adicionando dolorosamente muitas instruções de impressão :(

Estou tendo problemas semelhantes, embora não esteja ligando para setwd() . Sou capaz de executar meu conjunto de testes usando testthat:::test_dir e devtools:::test(fresh=TRUE) , mas não devtools:::test() (ou seja, com fresh=FALSE ) ou devtools:::check() .

Vou me aprofundar no problema, mas decidi compartilhar o comportamento estranho enquanto trabalho nisso.

Estou encontrando o mesmo problema, usando R 3.2.2 no OSX Mavericks. De acordo com as instruções no README.md , coloco o seguinte em tests/testthat.R com arquivos de teste em tests/testthat :

library(testthat)
library(qFeature)
test_check("qFeature")

Ao executar R CMD CHECK qFeature , ele trava ao iniciar os testes. Romper com Ctrl-C resulta no seguinte:

    Running ‘testthat.R’^C
 ERROR
Running the tests in ‘tests/testthat.R’ failed.
Last 13 lines of output:
  > library(testthat)
  > library(qFeature)
  > 
  > test_check("qFeature")
  Error in file(filename, "r", encoding = encoding) : 
    cannot open the connection
  Calls: local ... eval.parent -> eval -> eval -> eval -> eval -> source -> file
  In addition: Warning message:
  In file(filename, "r", encoding = encoding) :
    cannot open file 'startup.Rs': No such file or directory
  Execution halted

No entanto, se todas as coisas forem iguais, o teste no console R funciona bem:

 > library(testthat)
 > test_package("qFeature")
ddply_getFeatures() - Output Values : .
discFeatures() - Output Values : .........
fitQ() - Summary Values : Loading required package: qFeature
................................
fitQ() - Linear Output Values : ....
fitQ() - Quadratic Output Values : ....
getFeatures() - Output Values : .

DONE 

PS: devtools::check("~/path_to_package/qFeature") produz o mesmo comportamento que executar R CMD CHECK : ele trava e, uma vez quebrado com Cntrl-C , o mesmo erro aparece.

Encontrou uma solução alternativa

Este problema está relacionado a estes outros: https://github.com/hadley/testthat/issues/144 e https://github.com/zoonproject/zoon/pull/150.

Uma solução alternativa está aqui: https://github.com/luckyrandom/cmaker/commit/b85813ac2b7aef69932eca8fbb4fa0ec225e0af0

Basta adicionar Sys.setenv("R_TESTS" = "") como a primeira linha em tests/testthat.R

Este código continua aparecendo em R.
Erro no arquivo (nome do arquivo, "r", codificação = codificação):
não pode abrir a conexão
Além disso: mensagem de aviso:
No arquivo (nome do arquivo, "r", codificação = codificação):
não é possível abrir o arquivo 'rankall.R': Não existe esse arquivo ou diretório
, O que eu posso fazer?

Também vejo esse erro no que considero uma versão mais recente de testthat (1.0.2). Depois de incluir Sys.setenv("R_TESTS" = "") como a primeira linha em tests / testthat.R, como sugerido aqui, ele funciona.

* checking tests ...
  Running ‘testthat.R’^C
 ERROR
Running the tests in ‘tests/testthat.R’ failed.
Last 13 lines of output:
  > 
  > test_check("phylogenetic")
  Error in file(filename, "r", encoding = encoding) : 
    cannot open the connection
  Calls: local ... eval.parent -> eval -> eval -> eval -> eval -> source -> file
  In addition: Warning message:
  In file(filename, "r", encoding = encoding) :
    cannot open file 'startup.Rs': No such file or directory
  Execution halted

  testthat results ================================================================
  OK: 6 SKIPPED: 0 FAILED: 0
  Execution halted

R version 3.3.2 (2016-10-31)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] testthat_1.0.2      phylogenetic_0.1.99

loaded via a namespace (and not attached):
 [1] magrittr_1.5      R6_2.2.0          Matrix_1.2-8      parallel_3.3.2    tools_3.3.2       coda_0.19-1      
 [7] crayon_1.3.2      Rcpp_0.12.9       ABCoptim_0.14.0   nlme_3.1-128      ape_4.0           grid_3.3.2       
[13] numDeriv_2016.8-1 lattice_0.20-34  

Estou recebendo o mesmo erro "RStudio não está funcionando" mesmo com Sys.setenv("R_TESTS" = "") em testthat.r.

Os testes funcionam bem com devtools::test() ou executando-os manualmente. Eles falham com devtools::check() .

> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.4.3  tools_3.4.3     withr_2.1.2     yaml_2.1.19     memoise_1.1.0  
[6] git2r_0.21.0    digest_0.6.15   packrat_0.4.8-1 devtools_1.13.5

Também estou recebendo o mesmo erro, apesar de tentar a solução alternativa Sys.setenv("R_TESTS" = "") em testthat.R.

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.4

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] mongrel_0.1          BiocInstaller_1.30.0 devtools_1.13.6     

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.17              plyr_1.8.4                compiler_3.5.1            pillar_1.2.3             
 [5] git2r_0.21.0              bindr_0.1.1               forcats_0.3.0             tidybayes_0.12.1.9000    
 [9] tools_3.5.1               testthat_2.0.0            svUnit_0.7-12             digest_0.6.15            
[13] ggstance_0.3              jsonlite_1.5              memoise_1.1.0             tibble_1.4.2             
[17] gtable_0.2.0              lattice_0.20-35           pkgconfig_2.0.1           rlang_0.2.1              
[21] Matrix_1.2-14             commonmark_1.5            parallel_3.5.1            curl_3.2                 
[25] yaml_2.1.19               LaplacesDemon_16.1.1      bindrcpp_0.2.2            coda_0.19-1              
[29] withr_2.1.2               dplyr_0.7.6               httr_1.3.1                stringr_1.3.1            
[33] roxygen2_6.0.1            xml2_1.2.0                knitr_1.20                arrayhelpers_1.0-20160527
[37] grid_3.5.1                tidyselect_0.2.4          glue_1.2.0                R6_2.2.2                 
[41] purrr_0.2.5               tidyr_0.8.1               ggplot2_3.0.0             driver_0.1.0             
[45] magrittr_1.5              ggridges_0.5.0            MASS_7.3-50               scales_0.5.0             
[49] assertthat_0.2.0          colorspace_1.3-2          stringi_1.2.3             lazyeval_0.2.1           
[53] munsell_0.5.0             RcppEigen_0.3.3.4.0    
checking tests ... ERROR
  Running ‘testthat.R’
Running the tests in ‘tests/testthat.R’ failed.
Last 13 lines of output:
         if (logical.return) 
             message(paste("Error:", msg), domain = NA)
         else stop(msg, call. = FALSE, domain = NA)
     })
  3: tryCatchList(expr, classes, parentenv, handlers)
  4: tryCatchOne(expr, names, parentenv, handlers[[1L]])
  5: value[[3L]](cond)
  6: stop(msg, call. = FALSE, domain = NA)

  ══ testthat results  ════════════════════════════════════════════════════════════════════════════════════════════════
  OK: 13 SKIPPED: 0 FAILED: 1
  1. Error: (unknown) (@test-main.R#3) 

  Error: testthat unit tests failed
  Execution halted

Algum conselho?

@ jsilve24 Abra um novo problema e se possível inclua o pacote no qual está vendo este erro como um link, não será possível depurar isso sem ver o pacote.

No meu caso particular, a discrepância que obtive entre devtools::test() e devtools::check() foi devido a ter a definição de uma nova unidade em um arquivo .R e não dentro de .onLoad() (e removendo-o em .onUnload() ).

Antes

Em R/unit_conversion.R :

units::install_conversion_constant("FL", "ft", 100)

fl_to_foot <- function(fl) {
  fl %>%
    units::set_units(FL) %>%
    units::set_units(ft) %>%
    units::drop_units()
}

em tests/testthat/test-conversion.R :

context("Units convertion")
library(trfcplx)

test_that("fl_to_foot converts flight levels (FL) to feet", {
  expect_equal(fl_to_foot(150), 15000)
})
  • devtools::test() : OK
  • devtools::check() : FALHA

Depois de

Em R/unit_conversion.R :

fl_to_foot <- function(fl) {
  fl %>%
    units::set_units(FL) %>%
    units::set_units(ft) %>%
    units::drop_units()
}

Em zzz.R (novos arquivos como por "Quando você precisa de efeitos colaterais" seção):

# register flight levels (FL) as a unit when loading this package
.onLoad <- function(libname, pkgname) {
  # install user-define unit for flight level
  units::install_conversion_constant("FL", "ft", 100)

  invisible()
}

# register flight levels (FL) as a unit when loading this package
.onUnload <- function(libname, pkgname) {
  # uninstall user-define unit for flight level
  units::remove_symbolic_unit("FL")

  invisible()
}
  • devtools::test() : OK
  • devtools::check() : OK
Esta página foi útil?
0 / 5 - 0 avaliações